babylon.no-module.max.js 5.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /** @hidden */
  159. this._bonesComputationForcedToCPU = false;
  160. this._uniformBuffersNames = {};
  161. this._isReady = false;
  162. this._compilationError = "";
  163. this.name = baseName;
  164. if (attributesNamesOrOptions.attributes) {
  165. var options = attributesNamesOrOptions;
  166. this._engine = uniformsNamesOrEngine;
  167. this._attributesNames = options.attributes;
  168. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  169. this._samplers = options.samplers.slice();
  170. this.defines = options.defines;
  171. this.onError = options.onError;
  172. this.onCompiled = options.onCompiled;
  173. this._fallbacks = options.fallbacks;
  174. this._indexParameters = options.indexParameters;
  175. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  176. if (options.uniformBuffersNames) {
  177. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  178. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  179. }
  180. }
  181. }
  182. else {
  183. this._engine = engine;
  184. this.defines = defines;
  185. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  186. this._samplers = samplers ? samplers.slice() : [];
  187. this._attributesNames = attributesNamesOrOptions;
  188. this.onError = onError;
  189. this.onCompiled = onCompiled;
  190. this._indexParameters = indexParameters;
  191. this._fallbacks = fallbacks;
  192. }
  193. this.uniqueId = Effect._uniqueIdSeed++;
  194. var vertexSource;
  195. var fragmentSource;
  196. if (baseName.vertexElement) {
  197. vertexSource = document.getElementById(baseName.vertexElement);
  198. if (!vertexSource) {
  199. vertexSource = baseName.vertexElement;
  200. }
  201. }
  202. else {
  203. vertexSource = baseName.vertex || baseName;
  204. }
  205. if (baseName.fragmentElement) {
  206. fragmentSource = document.getElementById(baseName.fragmentElement);
  207. if (!fragmentSource) {
  208. fragmentSource = baseName.fragmentElement;
  209. }
  210. }
  211. else {
  212. fragmentSource = baseName.fragment || baseName;
  213. }
  214. this._loadVertexShader(vertexSource, function (vertexCode) {
  215. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  216. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  217. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  218. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  219. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  220. if (baseName) {
  221. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  222. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  223. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  224. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  225. }
  226. else {
  227. _this._vertexSourceCode = migratedVertexCode;
  228. _this._fragmentSourceCode = migratedFragmentCode;
  229. }
  230. _this._prepareEffect();
  231. });
  232. });
  233. });
  234. });
  235. });
  236. });
  237. }
  238. Object.defineProperty(Effect.prototype, "onBindObservable", {
  239. /**
  240. * Observable that will be called when effect is bound.
  241. */
  242. get: function () {
  243. if (!this._onBindObservable) {
  244. this._onBindObservable = new BABYLON.Observable();
  245. }
  246. return this._onBindObservable;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Object.defineProperty(Effect.prototype, "key", {
  252. /**
  253. * Unique key for this effect
  254. */
  255. get: function () {
  256. return this._key;
  257. },
  258. enumerable: true,
  259. configurable: true
  260. });
  261. /**
  262. * If the effect has been compiled and prepared.
  263. * @returns if the effect is compiled and prepared.
  264. */
  265. Effect.prototype.isReady = function () {
  266. return this._isReady;
  267. };
  268. /**
  269. * The engine the effect was initialized with.
  270. * @returns the engine.
  271. */
  272. Effect.prototype.getEngine = function () {
  273. return this._engine;
  274. };
  275. /**
  276. * The compiled webGL program for the effect
  277. * @returns the webGL program.
  278. */
  279. Effect.prototype.getProgram = function () {
  280. return this._program;
  281. };
  282. /**
  283. * The set of names of attribute variables for the shader.
  284. * @returns An array of attribute names.
  285. */
  286. Effect.prototype.getAttributesNames = function () {
  287. return this._attributesNames;
  288. };
  289. /**
  290. * Returns the attribute at the given index.
  291. * @param index The index of the attribute.
  292. * @returns The location of the attribute.
  293. */
  294. Effect.prototype.getAttributeLocation = function (index) {
  295. return this._attributes[index];
  296. };
  297. /**
  298. * Returns the attribute based on the name of the variable.
  299. * @param name of the attribute to look up.
  300. * @returns the attribute location.
  301. */
  302. Effect.prototype.getAttributeLocationByName = function (name) {
  303. var index = this._attributesNames.indexOf(name);
  304. return this._attributes[index];
  305. };
  306. /**
  307. * The number of attributes.
  308. * @returns the numnber of attributes.
  309. */
  310. Effect.prototype.getAttributesCount = function () {
  311. return this._attributes.length;
  312. };
  313. /**
  314. * Gets the index of a uniform variable.
  315. * @param uniformName of the uniform to look up.
  316. * @returns the index.
  317. */
  318. Effect.prototype.getUniformIndex = function (uniformName) {
  319. return this._uniformsNames.indexOf(uniformName);
  320. };
  321. /**
  322. * Returns the attribute based on the name of the variable.
  323. * @param uniformName of the uniform to look up.
  324. * @returns the location of the uniform.
  325. */
  326. Effect.prototype.getUniform = function (uniformName) {
  327. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  328. };
  329. /**
  330. * Returns an array of sampler variable names
  331. * @returns The array of sampler variable neames.
  332. */
  333. Effect.prototype.getSamplers = function () {
  334. return this._samplers;
  335. };
  336. /**
  337. * The error from the last compilation.
  338. * @returns the error string.
  339. */
  340. Effect.prototype.getCompilationError = function () {
  341. return this._compilationError;
  342. };
  343. /**
  344. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  345. * @param func The callback to be used.
  346. */
  347. Effect.prototype.executeWhenCompiled = function (func) {
  348. if (this.isReady()) {
  349. func(this);
  350. return;
  351. }
  352. this.onCompileObservable.add(function (effect) {
  353. func(effect);
  354. });
  355. };
  356. /** @hidden */
  357. Effect.prototype._loadVertexShader = function (vertex, callback) {
  358. if (BABYLON.Tools.IsWindowObjectExist()) {
  359. // DOM element ?
  360. if (vertex instanceof HTMLElement) {
  361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  362. callback(vertexCode);
  363. return;
  364. }
  365. }
  366. // Base64 encoded ?
  367. if (vertex.substr(0, 7) === "base64:") {
  368. var vertexBinary = window.atob(vertex.substr(7));
  369. callback(vertexBinary);
  370. return;
  371. }
  372. // Is in local store ?
  373. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  374. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  375. return;
  376. }
  377. var vertexShaderUrl;
  378. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  379. vertexShaderUrl = vertex;
  380. }
  381. else {
  382. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  383. }
  384. // Vertex shader
  385. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  386. };
  387. /** @hidden */
  388. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  389. if (BABYLON.Tools.IsWindowObjectExist()) {
  390. // DOM element ?
  391. if (fragment instanceof HTMLElement) {
  392. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  393. callback(fragmentCode);
  394. return;
  395. }
  396. }
  397. // Base64 encoded ?
  398. if (fragment.substr(0, 7) === "base64:") {
  399. var fragmentBinary = window.atob(fragment.substr(7));
  400. callback(fragmentBinary);
  401. return;
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  406. return;
  407. }
  408. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  409. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  410. return;
  411. }
  412. var fragmentShaderUrl;
  413. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  414. fragmentShaderUrl = fragment;
  415. }
  416. else {
  417. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  418. }
  419. // Fragment shader
  420. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  421. };
  422. /** @hidden */
  423. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  424. // Rebuild shaders source code
  425. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  426. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  427. vertexCode = prefix + vertexCode;
  428. fragmentCode = prefix + fragmentCode;
  429. // Number lines of shaders source code
  430. var i = 2;
  431. var regex = /\n/gm;
  432. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  433. i = 2;
  434. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  435. // Dump shaders name and formatted source code
  436. if (this.name.vertexElement) {
  437. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  438. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  439. }
  440. else if (this.name.vertex) {
  441. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  442. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  443. }
  444. else {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  447. }
  448. };
  449. ;
  450. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  451. var preparedSourceCode = this._processPrecision(sourceCode);
  452. if (this._engine.webGLVersion == 1) {
  453. callback(preparedSourceCode);
  454. return;
  455. }
  456. // Already converted
  457. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  458. callback(preparedSourceCode.replace("#version 300 es", ""));
  459. return;
  460. }
  461. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  462. // Remove extensions
  463. // #extension GL_OES_standard_derivatives : enable
  464. // #extension GL_EXT_shader_texture_lod : enable
  465. // #extension GL_EXT_frag_depth : enable
  466. // #extension GL_EXT_draw_buffers : require
  467. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  468. var result = preparedSourceCode.replace(regex, "");
  469. // Migrate to GLSL v300
  470. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  471. result = result.replace(/attribute[ \t]/g, "in ");
  472. result = result.replace(/[ \t]attribute/g, " in");
  473. if (isFragment) {
  474. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  476. result = result.replace(/texture2D\s*\(/g, "texture(");
  477. result = result.replace(/textureCube\s*\(/g, "texture(");
  478. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  479. result = result.replace(/gl_FragColor/g, "glFragColor");
  480. result = result.replace(/gl_FragData/g, "glFragData");
  481. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  482. }
  483. callback(result);
  484. };
  485. Effect.prototype._processIncludes = function (sourceCode, callback) {
  486. var _this = this;
  487. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  488. var match = regex.exec(sourceCode);
  489. var returnValue = new String(sourceCode);
  490. while (match != null) {
  491. var includeFile = match[1];
  492. // Uniform declaration
  493. if (includeFile.indexOf("__decl__") !== -1) {
  494. includeFile = includeFile.replace(/__decl__/, "");
  495. if (this._engine.supportsUniformBuffers) {
  496. includeFile = includeFile.replace(/Vertex/, "Ubo");
  497. includeFile = includeFile.replace(/Fragment/, "Ubo");
  498. }
  499. includeFile = includeFile + "Declaration";
  500. }
  501. if (Effect.IncludesShadersStore[includeFile]) {
  502. // Substitution
  503. var includeContent = Effect.IncludesShadersStore[includeFile];
  504. if (match[2]) {
  505. var splits = match[3].split(",");
  506. for (var index = 0; index < splits.length; index += 2) {
  507. var source = new RegExp(splits[index], "g");
  508. var dest = splits[index + 1];
  509. includeContent = includeContent.replace(source, dest);
  510. }
  511. }
  512. if (match[4]) {
  513. var indexString = match[5];
  514. if (indexString.indexOf("..") !== -1) {
  515. var indexSplits = indexString.split("..");
  516. var minIndex = parseInt(indexSplits[0]);
  517. var maxIndex = parseInt(indexSplits[1]);
  518. var sourceIncludeContent = includeContent.slice(0);
  519. includeContent = "";
  520. if (isNaN(maxIndex)) {
  521. maxIndex = this._indexParameters[indexSplits[1]];
  522. }
  523. for (var i = minIndex; i < maxIndex; i++) {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  531. }
  532. }
  533. else {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent = includeContent.replace(/\{X\}/g, indexString);
  541. }
  542. }
  543. // Replace
  544. returnValue = returnValue.replace(match[0], includeContent);
  545. }
  546. else {
  547. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  548. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  549. Effect.IncludesShadersStore[includeFile] = fileContent;
  550. _this._processIncludes(returnValue, callback);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. callback(returnValue);
  557. };
  558. Effect.prototype._processPrecision = function (source) {
  559. if (source.indexOf("precision highp float") === -1) {
  560. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  561. source = "precision mediump float;\n" + source;
  562. }
  563. else {
  564. source = "precision highp float;\n" + source;
  565. }
  566. }
  567. else {
  568. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  569. source = source.replace("precision highp float", "precision mediump float");
  570. }
  571. }
  572. return source;
  573. };
  574. /**
  575. * Recompiles the webGL program
  576. * @param vertexSourceCode The source code for the vertex shader.
  577. * @param fragmentSourceCode The source code for the fragment shader.
  578. * @param onCompiled Callback called when completed.
  579. * @param onError Callback called on error.
  580. * @hidden
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. * @hidden
  616. */
  617. Effect.prototype._prepareEffect = function () {
  618. var attributesNames = this._attributesNames;
  619. var defines = this.defines;
  620. var fallbacks = this._fallbacks;
  621. this._valueCache = {};
  622. var previousProgram = this._program;
  623. try {
  624. var engine = this._engine;
  625. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  626. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  627. }
  628. else {
  629. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  630. }
  631. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  632. if (engine.supportsUniformBuffers) {
  633. for (var name in this._uniformBuffersNames) {
  634. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  635. }
  636. }
  637. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  638. this._attributes = engine.getAttributes(this._program, attributesNames);
  639. var index;
  640. for (index = 0; index < this._samplers.length; index++) {
  641. var sampler = this.getUniform(this._samplers[index]);
  642. if (sampler == null) {
  643. this._samplers.splice(index, 1);
  644. index--;
  645. }
  646. }
  647. engine.bindSamplers(this);
  648. this._compilationError = "";
  649. this._isReady = true;
  650. if (this.onCompiled) {
  651. this.onCompiled(this);
  652. }
  653. this.onCompileObservable.notifyObservers(this);
  654. this.onCompileObservable.clear();
  655. // Unbind mesh reference in fallbacks
  656. if (this._fallbacks) {
  657. this._fallbacks.unBindMesh();
  658. }
  659. if (previousProgram) {
  660. this.getEngine()._deleteProgram(previousProgram);
  661. }
  662. }
  663. catch (e) {
  664. this._compilationError = e.message;
  665. // Let's go through fallbacks then
  666. BABYLON.Tools.Error("Unable to compile effect:");
  667. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  668. return " " + uniform;
  669. }));
  670. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  671. return " " + attribute;
  672. }));
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else { // Sorry we did everything we can
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. * @hidden
  715. */
  716. Effect.prototype._bindTexture = function (channel, texture) {
  717. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  718. };
  719. /**
  720. * Sets a texture on the engine to be used in the shader.
  721. * @param channel Name of the sampler variable.
  722. * @param texture Texture to set.
  723. */
  724. Effect.prototype.setTexture = function (channel, texture) {
  725. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  726. };
  727. /**
  728. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  733. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets an array of textures on the engine to be used in the shader.
  737. * @param channel Name of the variable.
  738. * @param textures Textures to set.
  739. */
  740. Effect.prototype.setTextureArray = function (channel, textures) {
  741. if (this._samplers.indexOf(channel + "Ex") === -1) {
  742. var initialPos = this._samplers.indexOf(channel);
  743. for (var index = 1; index < textures.length; index++) {
  744. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  745. }
  746. }
  747. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  748. };
  749. /**
  750. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  751. * @param channel Name of the sampler variable.
  752. * @param postProcess Post process to get the input texture from.
  753. */
  754. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  755. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  756. };
  757. /**
  758. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  759. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  760. * @param channel Name of the sampler variable.
  761. * @param postProcess Post process to get the output texture from.
  762. */
  763. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  764. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  765. };
  766. /** @hidden */
  767. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  768. var cache = this._valueCache[uniformName];
  769. var flag = matrix.updateFlag;
  770. if (cache !== undefined && cache === flag) {
  771. return false;
  772. }
  773. this._valueCache[uniformName] = flag;
  774. return true;
  775. };
  776. /** @hidden */
  777. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  778. var cache = this._valueCache[uniformName];
  779. if (!cache) {
  780. cache = [x, y];
  781. this._valueCache[uniformName] = cache;
  782. return true;
  783. }
  784. var changed = false;
  785. if (cache[0] !== x) {
  786. cache[0] = x;
  787. changed = true;
  788. }
  789. if (cache[1] !== y) {
  790. cache[1] = y;
  791. changed = true;
  792. }
  793. return changed;
  794. };
  795. /** @hidden */
  796. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  797. var cache = this._valueCache[uniformName];
  798. if (!cache) {
  799. cache = [x, y, z];
  800. this._valueCache[uniformName] = cache;
  801. return true;
  802. }
  803. var changed = false;
  804. if (cache[0] !== x) {
  805. cache[0] = x;
  806. changed = true;
  807. }
  808. if (cache[1] !== y) {
  809. cache[1] = y;
  810. changed = true;
  811. }
  812. if (cache[2] !== z) {
  813. cache[2] = z;
  814. changed = true;
  815. }
  816. return changed;
  817. };
  818. /** @hidden */
  819. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  820. var cache = this._valueCache[uniformName];
  821. if (!cache) {
  822. cache = [x, y, z, w];
  823. this._valueCache[uniformName] = cache;
  824. return true;
  825. }
  826. var changed = false;
  827. if (cache[0] !== x) {
  828. cache[0] = x;
  829. changed = true;
  830. }
  831. if (cache[1] !== y) {
  832. cache[1] = y;
  833. changed = true;
  834. }
  835. if (cache[2] !== z) {
  836. cache[2] = z;
  837. changed = true;
  838. }
  839. if (cache[3] !== w) {
  840. cache[3] = w;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /**
  846. * Binds a buffer to a uniform.
  847. * @param buffer Buffer to bind.
  848. * @param name Name of the uniform variable to bind to.
  849. */
  850. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  851. var bufferName = this._uniformBuffersNames[name];
  852. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  853. return;
  854. }
  855. Effect._baseCache[bufferName] = buffer;
  856. this._engine.bindUniformBufferBase(buffer, bufferName);
  857. };
  858. /**
  859. * Binds block to a uniform.
  860. * @param blockName Name of the block to bind.
  861. * @param index Index to bind.
  862. */
  863. Effect.prototype.bindUniformBlock = function (blockName, index) {
  864. this._engine.bindUniformBlock(this._program, blockName, index);
  865. };
  866. /**
  867. * Sets an interger value on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param value Value to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setInt = function (uniformName, value) {
  873. var cache = this._valueCache[uniformName];
  874. if (cache !== undefined && cache === value)
  875. return this;
  876. this._valueCache[uniformName] = value;
  877. this._engine.setInt(this.getUniform(uniformName), value);
  878. return this;
  879. };
  880. /**
  881. * Sets an int array on a uniform variable.
  882. * @param uniformName Name of the variable.
  883. * @param array array to be set.
  884. * @returns this effect.
  885. */
  886. Effect.prototype.setIntArray = function (uniformName, array) {
  887. this._valueCache[uniformName] = null;
  888. this._engine.setIntArray(this.getUniform(uniformName), array);
  889. return this;
  890. };
  891. /**
  892. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  893. * @param uniformName Name of the variable.
  894. * @param array array to be set.
  895. * @returns this effect.
  896. */
  897. Effect.prototype.setIntArray2 = function (uniformName, array) {
  898. this._valueCache[uniformName] = null;
  899. this._engine.setIntArray2(this.getUniform(uniformName), array);
  900. return this;
  901. };
  902. /**
  903. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  904. * @param uniformName Name of the variable.
  905. * @param array array to be set.
  906. * @returns this effect.
  907. */
  908. Effect.prototype.setIntArray3 = function (uniformName, array) {
  909. this._valueCache[uniformName] = null;
  910. this._engine.setIntArray3(this.getUniform(uniformName), array);
  911. return this;
  912. };
  913. /**
  914. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  915. * @param uniformName Name of the variable.
  916. * @param array array to be set.
  917. * @returns this effect.
  918. */
  919. Effect.prototype.setIntArray4 = function (uniformName, array) {
  920. this._valueCache[uniformName] = null;
  921. this._engine.setIntArray4(this.getUniform(uniformName), array);
  922. return this;
  923. };
  924. /**
  925. * Sets an float array on a uniform variable.
  926. * @param uniformName Name of the variable.
  927. * @param array array to be set.
  928. * @returns this effect.
  929. */
  930. Effect.prototype.setFloatArray = function (uniformName, array) {
  931. this._valueCache[uniformName] = null;
  932. this._engine.setFloatArray(this.getUniform(uniformName), array);
  933. return this;
  934. };
  935. /**
  936. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  937. * @param uniformName Name of the variable.
  938. * @param array array to be set.
  939. * @returns this effect.
  940. */
  941. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  942. this._valueCache[uniformName] = null;
  943. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  944. return this;
  945. };
  946. /**
  947. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  948. * @param uniformName Name of the variable.
  949. * @param array array to be set.
  950. * @returns this effect.
  951. */
  952. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  953. this._valueCache[uniformName] = null;
  954. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  955. return this;
  956. };
  957. /**
  958. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  959. * @param uniformName Name of the variable.
  960. * @param array array to be set.
  961. * @returns this effect.
  962. */
  963. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  964. this._valueCache[uniformName] = null;
  965. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  966. return this;
  967. };
  968. /**
  969. * Sets an array on a uniform variable.
  970. * @param uniformName Name of the variable.
  971. * @param array array to be set.
  972. * @returns this effect.
  973. */
  974. Effect.prototype.setArray = function (uniformName, array) {
  975. this._valueCache[uniformName] = null;
  976. this._engine.setArray(this.getUniform(uniformName), array);
  977. return this;
  978. };
  979. /**
  980. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  981. * @param uniformName Name of the variable.
  982. * @param array array to be set.
  983. * @returns this effect.
  984. */
  985. Effect.prototype.setArray2 = function (uniformName, array) {
  986. this._valueCache[uniformName] = null;
  987. this._engine.setArray2(this.getUniform(uniformName), array);
  988. return this;
  989. };
  990. /**
  991. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  992. * @param uniformName Name of the variable.
  993. * @param array array to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setArray3 = function (uniformName, array) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setArray3(this.getUniform(uniformName), array);
  999. return this;
  1000. };
  1001. /**
  1002. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1003. * @param uniformName Name of the variable.
  1004. * @param array array to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setArray4 = function (uniformName, array) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setArray4(this.getUniform(uniformName), array);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrices on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrices matrices to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1019. if (!matrices) {
  1020. return this;
  1021. }
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets matrix on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1033. if (this._cacheMatrix(uniformName, matrix)) {
  1034. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1035. }
  1036. return this;
  1037. };
  1038. /**
  1039. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1045. this._valueCache[uniformName] = null;
  1046. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1047. return this;
  1048. };
  1049. /**
  1050. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1051. * @param uniformName Name of the variable.
  1052. * @param matrix matrix to be set.
  1053. * @returns this effect.
  1054. */
  1055. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1056. this._valueCache[uniformName] = null;
  1057. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a float on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param value value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setFloat = function (uniformName, value) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === value)
  1069. return this;
  1070. this._valueCache[uniformName] = value;
  1071. this._engine.setFloat(this.getUniform(uniformName), value);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a boolean on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param bool value to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setBool = function (uniformName, bool) {
  1081. var cache = this._valueCache[uniformName];
  1082. if (cache !== undefined && cache === bool)
  1083. return this;
  1084. this._valueCache[uniformName] = bool;
  1085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a Vector2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param vector2 vector2 to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1095. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1096. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1097. }
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a float2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param x First float in float2.
  1104. * @param y Second float in float2.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1108. if (this._cacheFloat2(uniformName, x, y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a Vector3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param vector3 Value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1120. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a float3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param x First float in float3.
  1129. * @param y Second float in float3.
  1130. * @param z Third float in float3.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1134. if (this._cacheFloat3(uniformName, x, y, z)) {
  1135. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a Vector4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param vector4 Value to be set.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1146. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a float4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param x First float in float4.
  1155. * @param y Second float in float4.
  1156. * @param z Third float in float4.
  1157. * @param w Fourth float in float4.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1161. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setColor3 = function (uniformName, color3) {
  1173. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1174. this._engine.setColor3(this.getUniform(uniformName), color3);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @param alpha Alpha value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1186. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1187. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable
  1193. * @param uniformName defines the name of the variable
  1194. * @param color4 defines the value to be set
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1198. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1199. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * This function will add a new shader to the shader store
  1205. * @param name the name of the shader
  1206. * @param pixelShader optional pixel shader content
  1207. * @param vertexShader optional vertex shader content
  1208. */
  1209. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1210. if (pixelShader) {
  1211. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1212. }
  1213. if (vertexShader) {
  1214. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1215. }
  1216. };
  1217. /**
  1218. * Resets the cache of effects.
  1219. */
  1220. Effect.ResetCache = function () {
  1221. Effect._baseCache = {};
  1222. };
  1223. Effect._uniqueIdSeed = 0;
  1224. Effect._baseCache = {};
  1225. /**
  1226. * Store of each shader (The can be looked up using effect.key)
  1227. */
  1228. Effect.ShadersStore = {};
  1229. /**
  1230. * Store of each included file for a shader (The can be looked up using effect.key)
  1231. */
  1232. Effect.IncludesShadersStore = {};
  1233. return Effect;
  1234. }());
  1235. BABYLON.Effect = Effect;
  1236. })(BABYLON || (BABYLON = {}));
  1237. //# sourceMappingURL=babylon.effect.js.map
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. var BABYLON;
  1240. (function (BABYLON) {
  1241. var KeyboardEventTypes = /** @class */ (function () {
  1242. function KeyboardEventTypes() {
  1243. }
  1244. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1245. get: function () {
  1246. return KeyboardEventTypes._KEYDOWN;
  1247. },
  1248. enumerable: true,
  1249. configurable: true
  1250. });
  1251. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1252. get: function () {
  1253. return KeyboardEventTypes._KEYUP;
  1254. },
  1255. enumerable: true,
  1256. configurable: true
  1257. });
  1258. KeyboardEventTypes._KEYDOWN = 0x01;
  1259. KeyboardEventTypes._KEYUP = 0x02;
  1260. return KeyboardEventTypes;
  1261. }());
  1262. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1263. var KeyboardInfo = /** @class */ (function () {
  1264. function KeyboardInfo(type, event) {
  1265. this.type = type;
  1266. this.event = event;
  1267. }
  1268. return KeyboardInfo;
  1269. }());
  1270. BABYLON.KeyboardInfo = KeyboardInfo;
  1271. /**
  1272. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1273. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1274. */
  1275. var KeyboardInfoPre = /** @class */ (function (_super) {
  1276. __extends(KeyboardInfoPre, _super);
  1277. function KeyboardInfoPre(type, event) {
  1278. var _this = _super.call(this, type, event) || this;
  1279. _this.skipOnPointerObservable = false;
  1280. return _this;
  1281. }
  1282. return KeyboardInfoPre;
  1283. }(KeyboardInfo));
  1284. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1285. })(BABYLON || (BABYLON = {}));
  1286. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1287. var BABYLON;
  1288. (function (BABYLON) {
  1289. var PointerEventTypes = /** @class */ (function () {
  1290. function PointerEventTypes() {
  1291. }
  1292. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1293. get: function () {
  1294. return PointerEventTypes._POINTERDOWN;
  1295. },
  1296. enumerable: true,
  1297. configurable: true
  1298. });
  1299. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1300. get: function () {
  1301. return PointerEventTypes._POINTERUP;
  1302. },
  1303. enumerable: true,
  1304. configurable: true
  1305. });
  1306. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1307. get: function () {
  1308. return PointerEventTypes._POINTERMOVE;
  1309. },
  1310. enumerable: true,
  1311. configurable: true
  1312. });
  1313. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1314. get: function () {
  1315. return PointerEventTypes._POINTERWHEEL;
  1316. },
  1317. enumerable: true,
  1318. configurable: true
  1319. });
  1320. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1321. get: function () {
  1322. return PointerEventTypes._POINTERPICK;
  1323. },
  1324. enumerable: true,
  1325. configurable: true
  1326. });
  1327. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1328. get: function () {
  1329. return PointerEventTypes._POINTERTAP;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1335. get: function () {
  1336. return PointerEventTypes._POINTERDOUBLETAP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. PointerEventTypes._POINTERDOWN = 0x01;
  1342. PointerEventTypes._POINTERUP = 0x02;
  1343. PointerEventTypes._POINTERMOVE = 0x04;
  1344. PointerEventTypes._POINTERWHEEL = 0x08;
  1345. PointerEventTypes._POINTERPICK = 0x10;
  1346. PointerEventTypes._POINTERTAP = 0x20;
  1347. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1348. return PointerEventTypes;
  1349. }());
  1350. BABYLON.PointerEventTypes = PointerEventTypes;
  1351. var PointerInfoBase = /** @class */ (function () {
  1352. function PointerInfoBase(type, event) {
  1353. this.type = type;
  1354. this.event = event;
  1355. }
  1356. return PointerInfoBase;
  1357. }());
  1358. BABYLON.PointerInfoBase = PointerInfoBase;
  1359. /**
  1360. * This class is used to store pointer related info for the onPrePointerObservable event.
  1361. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1362. */
  1363. var PointerInfoPre = /** @class */ (function (_super) {
  1364. __extends(PointerInfoPre, _super);
  1365. function PointerInfoPre(type, event, localX, localY) {
  1366. var _this = _super.call(this, type, event) || this;
  1367. /**
  1368. * Ray from a pointer if availible (eg. 6dof controller)
  1369. */
  1370. _this.ray = null;
  1371. _this.skipOnPointerObservable = false;
  1372. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1373. return _this;
  1374. }
  1375. return PointerInfoPre;
  1376. }(PointerInfoBase));
  1377. BABYLON.PointerInfoPre = PointerInfoPre;
  1378. /**
  1379. * This type contains all the data related to a pointer event in Babylon.js.
  1380. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1381. */
  1382. var PointerInfo = /** @class */ (function (_super) {
  1383. __extends(PointerInfo, _super);
  1384. function PointerInfo(type, event, pickInfo) {
  1385. var _this = _super.call(this, type, event) || this;
  1386. _this.pickInfo = pickInfo;
  1387. return _this;
  1388. }
  1389. return PointerInfo;
  1390. }(PointerInfoBase));
  1391. BABYLON.PointerInfo = PointerInfo;
  1392. })(BABYLON || (BABYLON = {}));
  1393. //# sourceMappingURL=babylon.pointerEvents.js.map
  1394. var BABYLON;
  1395. (function (BABYLON) {
  1396. BABYLON.ToGammaSpace = 1 / 2.2;
  1397. BABYLON.ToLinearSpace = 2.2;
  1398. BABYLON.Epsilon = 0.001;
  1399. /**
  1400. * Class used to hold a RBG color
  1401. */
  1402. var Color3 = /** @class */ (function () {
  1403. /**
  1404. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1405. * @param r defines the red component (between 0 and 1, default is 0)
  1406. * @param g defines the green component (between 0 and 1, default is 0)
  1407. * @param b defines the blue component (between 0 and 1, default is 0)
  1408. */
  1409. function Color3(
  1410. /**
  1411. * Defines the red component (between 0 and 1, default is 0)
  1412. */
  1413. r,
  1414. /**
  1415. * Defines the green component (between 0 and 1, default is 0)
  1416. */
  1417. g,
  1418. /**
  1419. * Defines the blue component (between 0 and 1, default is 0)
  1420. */
  1421. b) {
  1422. if (r === void 0) { r = 0; }
  1423. if (g === void 0) { g = 0; }
  1424. if (b === void 0) { b = 0; }
  1425. this.r = r;
  1426. this.g = g;
  1427. this.b = b;
  1428. }
  1429. /**
  1430. * Creates a string with the Color3 current values
  1431. * @returns the string representation of the Color3 object
  1432. */
  1433. Color3.prototype.toString = function () {
  1434. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1435. };
  1436. /**
  1437. * Returns the string "Color3"
  1438. * @returns "Color3"
  1439. */
  1440. Color3.prototype.getClassName = function () {
  1441. return "Color3";
  1442. };
  1443. /**
  1444. * Compute the Color3 hash code
  1445. * @returns an unique number that can be used to hash Color3 objects
  1446. */
  1447. Color3.prototype.getHashCode = function () {
  1448. var hash = this.r || 0;
  1449. hash = (hash * 397) ^ (this.g || 0);
  1450. hash = (hash * 397) ^ (this.b || 0);
  1451. return hash;
  1452. };
  1453. // Operators
  1454. /**
  1455. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1456. * @param array defines the array where to store the r,g,b components
  1457. * @param index defines an optional index in the target array to define where to start storing values
  1458. * @returns the current Color3 object
  1459. */
  1460. Color3.prototype.toArray = function (array, index) {
  1461. if (index === undefined) {
  1462. index = 0;
  1463. }
  1464. array[index] = this.r;
  1465. array[index + 1] = this.g;
  1466. array[index + 2] = this.b;
  1467. return this;
  1468. };
  1469. /**
  1470. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1471. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1472. * @returns a new {BABYLON.Color4} object
  1473. */
  1474. Color3.prototype.toColor4 = function (alpha) {
  1475. if (alpha === void 0) { alpha = 1; }
  1476. return new Color4(this.r, this.g, this.b, alpha);
  1477. };
  1478. /**
  1479. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1480. * @returns the new array
  1481. */
  1482. Color3.prototype.asArray = function () {
  1483. var result = new Array();
  1484. this.toArray(result, 0);
  1485. return result;
  1486. };
  1487. /**
  1488. * Returns the luminance value
  1489. * @returns a float value
  1490. */
  1491. Color3.prototype.toLuminance = function () {
  1492. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1493. };
  1494. /**
  1495. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1496. * @param otherColor defines the second operand
  1497. * @returns the new Color3 object
  1498. */
  1499. Color3.prototype.multiply = function (otherColor) {
  1500. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1501. };
  1502. /**
  1503. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1504. * @param otherColor defines the second operand
  1505. * @param result defines the Color3 object where to store the result
  1506. * @returns the current Color3
  1507. */
  1508. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1509. result.r = this.r * otherColor.r;
  1510. result.g = this.g * otherColor.g;
  1511. result.b = this.b * otherColor.b;
  1512. return this;
  1513. };
  1514. /**
  1515. * Determines equality between Color3 objects
  1516. * @param otherColor defines the second operand
  1517. * @returns true if the rgb values are equal to the given ones
  1518. */
  1519. Color3.prototype.equals = function (otherColor) {
  1520. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1521. };
  1522. /**
  1523. * Determines equality between the current Color3 object and a set of r,b,g values
  1524. * @param r defines the red component to check
  1525. * @param g defines the green component to check
  1526. * @param b defines the blue component to check
  1527. * @returns true if the rgb values are equal to the given ones
  1528. */
  1529. Color3.prototype.equalsFloats = function (r, g, b) {
  1530. return this.r === r && this.g === g && this.b === b;
  1531. };
  1532. /**
  1533. * Multiplies in place each rgb value by scale
  1534. * @param scale defines the scaling factor
  1535. * @returns the updated Color3
  1536. */
  1537. Color3.prototype.scale = function (scale) {
  1538. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1539. };
  1540. /**
  1541. * Multiplies the rgb values by scale and stores the result into "result"
  1542. * @param scale defines the scaling factor
  1543. * @param result defines the Color3 object where to store the result
  1544. * @returns the unmodified current Color3
  1545. */
  1546. Color3.prototype.scaleToRef = function (scale, result) {
  1547. result.r = this.r * scale;
  1548. result.g = this.g * scale;
  1549. result.b = this.b * scale;
  1550. return this;
  1551. };
  1552. /**
  1553. * Scale the current Color3 values by a factor and add the result to a given Color3
  1554. * @param scale defines the scale factor
  1555. * @param result defines color to store the result into
  1556. * @returns the unmodified current Color3
  1557. */
  1558. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1559. result.r += this.r * scale;
  1560. result.g += this.g * scale;
  1561. result.b += this.b * scale;
  1562. return this;
  1563. };
  1564. /**
  1565. * Clamps the rgb values by the min and max values and stores the result into "result"
  1566. * @param min defines minimum clamping value (default is 0)
  1567. * @param max defines maximum clamping value (default is 1)
  1568. * @param result defines color to store the result into
  1569. * @returns the original Color3
  1570. */
  1571. Color3.prototype.clampToRef = function (min, max, result) {
  1572. if (min === void 0) { min = 0; }
  1573. if (max === void 0) { max = 1; }
  1574. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1575. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1576. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1577. return this;
  1578. };
  1579. /**
  1580. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1581. * @param otherColor defines the second operand
  1582. * @returns the new Color3
  1583. */
  1584. Color3.prototype.add = function (otherColor) {
  1585. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1586. };
  1587. /**
  1588. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1589. * @param otherColor defines the second operand
  1590. * @param result defines Color3 object to store the result into
  1591. * @returns the unmodified current Color3
  1592. */
  1593. Color3.prototype.addToRef = function (otherColor, result) {
  1594. result.r = this.r + otherColor.r;
  1595. result.g = this.g + otherColor.g;
  1596. result.b = this.b + otherColor.b;
  1597. return this;
  1598. };
  1599. /**
  1600. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1601. * @param otherColor defines the second operand
  1602. * @returns the new Color3
  1603. */
  1604. Color3.prototype.subtract = function (otherColor) {
  1605. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1606. };
  1607. /**
  1608. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1609. * @param otherColor defines the second operand
  1610. * @param result defines Color3 object to store the result into
  1611. * @returns the unmodified current Color3
  1612. */
  1613. Color3.prototype.subtractToRef = function (otherColor, result) {
  1614. result.r = this.r - otherColor.r;
  1615. result.g = this.g - otherColor.g;
  1616. result.b = this.b - otherColor.b;
  1617. return this;
  1618. };
  1619. /**
  1620. * Copy the current object
  1621. * @returns a new Color3 copied the current one
  1622. */
  1623. Color3.prototype.clone = function () {
  1624. return new Color3(this.r, this.g, this.b);
  1625. };
  1626. /**
  1627. * Copies the rgb values from the source in the current Color3
  1628. * @param source defines the source Color3 object
  1629. * @returns the updated Color3 object
  1630. */
  1631. Color3.prototype.copyFrom = function (source) {
  1632. this.r = source.r;
  1633. this.g = source.g;
  1634. this.b = source.b;
  1635. return this;
  1636. };
  1637. /**
  1638. * Updates the Color3 rgb values from the given floats
  1639. * @param r defines the red component to read from
  1640. * @param g defines the green component to read from
  1641. * @param b defines the blue component to read from
  1642. * @returns the current Color3 object
  1643. */
  1644. Color3.prototype.copyFromFloats = function (r, g, b) {
  1645. this.r = r;
  1646. this.g = g;
  1647. this.b = b;
  1648. return this;
  1649. };
  1650. /**
  1651. * Updates the Color3 rgb values from the given floats
  1652. * @param r defines the red component to read from
  1653. * @param g defines the green component to read from
  1654. * @param b defines the blue component to read from
  1655. * @returns the current Color3 object
  1656. */
  1657. Color3.prototype.set = function (r, g, b) {
  1658. return this.copyFromFloats(r, g, b);
  1659. };
  1660. /**
  1661. * Compute the Color3 hexadecimal code as a string
  1662. * @returns a string containing the hexadecimal representation of the Color3 object
  1663. */
  1664. Color3.prototype.toHexString = function () {
  1665. var intR = (this.r * 255) | 0;
  1666. var intG = (this.g * 255) | 0;
  1667. var intB = (this.b * 255) | 0;
  1668. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1669. };
  1670. /**
  1671. * Computes a new Color3 converted from the current one to linear space
  1672. * @returns a new Color3 object
  1673. */
  1674. Color3.prototype.toLinearSpace = function () {
  1675. var convertedColor = new Color3();
  1676. this.toLinearSpaceToRef(convertedColor);
  1677. return convertedColor;
  1678. };
  1679. /**
  1680. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1681. * @param convertedColor defines the Color3 object where to store the linear space version
  1682. * @returns the unmodified Color3
  1683. */
  1684. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1685. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1686. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1687. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1688. return this;
  1689. };
  1690. /**
  1691. * Computes a new Color3 converted from the current one to gamma space
  1692. * @returns a new Color3 object
  1693. */
  1694. Color3.prototype.toGammaSpace = function () {
  1695. var convertedColor = new Color3();
  1696. this.toGammaSpaceToRef(convertedColor);
  1697. return convertedColor;
  1698. };
  1699. /**
  1700. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1701. * @param convertedColor defines the Color3 object where to store the gamma space version
  1702. * @returns the unmodified Color3
  1703. */
  1704. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1705. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1706. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1707. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1708. return this;
  1709. };
  1710. // Statics
  1711. /**
  1712. * Creates a new Color3 from the string containing valid hexadecimal values
  1713. * @param hex defines a string containing valid hexadecimal values
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromHexString = function (hex) {
  1717. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1718. return new Color3(0, 0, 0);
  1719. }
  1720. var r = parseInt(hex.substring(1, 3), 16);
  1721. var g = parseInt(hex.substring(3, 5), 16);
  1722. var b = parseInt(hex.substring(5, 7), 16);
  1723. return Color3.FromInts(r, g, b);
  1724. };
  1725. /**
  1726. * Creates a new Vector3 from the starting index of the given array
  1727. * @param array defines the source array
  1728. * @param offset defines an offset in the source array
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.FromArray = function (array, offset) {
  1732. if (offset === void 0) { offset = 0; }
  1733. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1734. };
  1735. /**
  1736. * Creates a new Color3 from integer values (< 256)
  1737. * @param r defines the red component to read from (value between 0 and 255)
  1738. * @param g defines the green component to read from (value between 0 and 255)
  1739. * @param b defines the blue component to read from (value between 0 and 255)
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.FromInts = function (r, g, b) {
  1743. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1744. };
  1745. /**
  1746. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1747. * @param start defines the start Color3 value
  1748. * @param end defines the end Color3 value
  1749. * @param amount defines the gradient value between start and end
  1750. * @returns a new Color3 object
  1751. */
  1752. Color3.Lerp = function (start, end, amount) {
  1753. var r = start.r + ((end.r - start.r) * amount);
  1754. var g = start.g + ((end.g - start.g) * amount);
  1755. var b = start.b + ((end.b - start.b) * amount);
  1756. return new Color3(r, g, b);
  1757. };
  1758. /**
  1759. * Returns a Color3 value containing a red color
  1760. * @returns a new Color3 object
  1761. */
  1762. Color3.Red = function () { return new Color3(1, 0, 0); };
  1763. /**
  1764. * Returns a Color3 value containing a green color
  1765. * @returns a new Color3 object
  1766. */
  1767. Color3.Green = function () { return new Color3(0, 1, 0); };
  1768. /**
  1769. * Returns a Color3 value containing a blue color
  1770. * @returns a new Color3 object
  1771. */
  1772. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1773. /**
  1774. * Returns a Color3 value containing a black color
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.Black = function () { return new Color3(0, 0, 0); };
  1778. /**
  1779. * Returns a Color3 value containing a white color
  1780. * @returns a new Color3 object
  1781. */
  1782. Color3.White = function () { return new Color3(1, 1, 1); };
  1783. /**
  1784. * Returns a Color3 value containing a purple color
  1785. * @returns a new Color3 object
  1786. */
  1787. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1788. /**
  1789. * Returns a Color3 value containing a magenta color
  1790. * @returns a new Color3 object
  1791. */
  1792. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1793. /**
  1794. * Returns a Color3 value containing a yellow color
  1795. * @returns a new Color3 object
  1796. */
  1797. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1798. /**
  1799. * Returns a Color3 value containing a gray color
  1800. * @returns a new Color3 object
  1801. */
  1802. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1803. /**
  1804. * Returns a Color3 value containing a teal color
  1805. * @returns a new Color3 object
  1806. */
  1807. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1808. /**
  1809. * Returns a Color3 value containing a random color
  1810. * @returns a new Color3 object
  1811. */
  1812. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1813. return Color3;
  1814. }());
  1815. BABYLON.Color3 = Color3;
  1816. /**
  1817. * Class used to hold a RBGA color
  1818. */
  1819. var Color4 = /** @class */ (function () {
  1820. /**
  1821. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1822. * @param r defines the red component (between 0 and 1, default is 0)
  1823. * @param g defines the green component (between 0 and 1, default is 0)
  1824. * @param b defines the blue component (between 0 and 1, default is 0)
  1825. * @param a defines the alpha component (between 0 and 1, default is 1)
  1826. */
  1827. function Color4(
  1828. /**
  1829. * Defines the red component (between 0 and 1, default is 0)
  1830. */
  1831. r,
  1832. /**
  1833. * Defines the green component (between 0 and 1, default is 0)
  1834. */
  1835. g,
  1836. /**
  1837. * Defines the blue component (between 0 and 1, default is 0)
  1838. */
  1839. b,
  1840. /**
  1841. * Defines the alpha component (between 0 and 1, default is 1)
  1842. */
  1843. a) {
  1844. if (r === void 0) { r = 0; }
  1845. if (g === void 0) { g = 0; }
  1846. if (b === void 0) { b = 0; }
  1847. if (a === void 0) { a = 1; }
  1848. this.r = r;
  1849. this.g = g;
  1850. this.b = b;
  1851. this.a = a;
  1852. }
  1853. // Operators
  1854. /**
  1855. * Adds in place the given Color4 values to the current Color4 object
  1856. * @param right defines the second operand
  1857. * @returns the current updated Color4 object
  1858. */
  1859. Color4.prototype.addInPlace = function (right) {
  1860. this.r += right.r;
  1861. this.g += right.g;
  1862. this.b += right.b;
  1863. this.a += right.a;
  1864. return this;
  1865. };
  1866. /**
  1867. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1868. * @returns the new array
  1869. */
  1870. Color4.prototype.asArray = function () {
  1871. var result = new Array();
  1872. this.toArray(result, 0);
  1873. return result;
  1874. };
  1875. /**
  1876. * Stores from the starting index in the given array the Color4 successive values
  1877. * @param array defines the array where to store the r,g,b components
  1878. * @param index defines an optional index in the target array to define where to start storing values
  1879. * @returns the current Color4 object
  1880. */
  1881. Color4.prototype.toArray = function (array, index) {
  1882. if (index === undefined) {
  1883. index = 0;
  1884. }
  1885. array[index] = this.r;
  1886. array[index + 1] = this.g;
  1887. array[index + 2] = this.b;
  1888. array[index + 3] = this.a;
  1889. return this;
  1890. };
  1891. /**
  1892. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1893. * @param right defines the second operand
  1894. * @returns a new Color4 object
  1895. */
  1896. Color4.prototype.add = function (right) {
  1897. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1898. };
  1899. /**
  1900. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1901. * @param right defines the second operand
  1902. * @returns a new Color4 object
  1903. */
  1904. Color4.prototype.subtract = function (right) {
  1905. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1906. };
  1907. /**
  1908. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1909. * @param right defines the second operand
  1910. * @param result defines the Color4 object where to store the result
  1911. * @returns the current Color4 object
  1912. */
  1913. Color4.prototype.subtractToRef = function (right, result) {
  1914. result.r = this.r - right.r;
  1915. result.g = this.g - right.g;
  1916. result.b = this.b - right.b;
  1917. result.a = this.a - right.a;
  1918. return this;
  1919. };
  1920. /**
  1921. * Creates a new Color4 with the current Color4 values multiplied by scale
  1922. * @param scale defines the scaling factor to apply
  1923. * @returns a new Color4 object
  1924. */
  1925. Color4.prototype.scale = function (scale) {
  1926. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1927. };
  1928. /**
  1929. * Multiplies the current Color4 values by scale and stores the result in "result"
  1930. * @param scale defines the scaling factor to apply
  1931. * @param result defines the Color4 object where to store the result
  1932. * @returns the current unmodified Color4
  1933. */
  1934. Color4.prototype.scaleToRef = function (scale, result) {
  1935. result.r = this.r * scale;
  1936. result.g = this.g * scale;
  1937. result.b = this.b * scale;
  1938. result.a = this.a * scale;
  1939. return this;
  1940. };
  1941. /**
  1942. * Scale the current Color4 values by a factor and add the result to a given Color4
  1943. * @param scale defines the scale factor
  1944. * @param result defines the Color4 object where to store the result
  1945. * @returns the unmodified current Color4
  1946. */
  1947. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1948. result.r += this.r * scale;
  1949. result.g += this.g * scale;
  1950. result.b += this.b * scale;
  1951. result.a += this.a * scale;
  1952. return this;
  1953. };
  1954. /**
  1955. * Clamps the rgb values by the min and max values and stores the result into "result"
  1956. * @param min defines minimum clamping value (default is 0)
  1957. * @param max defines maximum clamping value (default is 1)
  1958. * @param result defines color to store the result into.
  1959. * @returns the cuurent Color4
  1960. */
  1961. Color4.prototype.clampToRef = function (min, max, result) {
  1962. if (min === void 0) { min = 0; }
  1963. if (max === void 0) { max = 1; }
  1964. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1965. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1966. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1967. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1968. return this;
  1969. };
  1970. /**
  1971. * Multipy an Color4 value by another and return a new Color4 object
  1972. * @param color defines the Color4 value to multiply by
  1973. * @returns a new Color4 object
  1974. */
  1975. Color4.prototype.multiply = function (color) {
  1976. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1977. };
  1978. /**
  1979. * Multipy a Color4 value by another and push the result in a reference value
  1980. * @param color defines the Color4 value to multiply by
  1981. * @param result defines the Color4 to fill the result in
  1982. * @returns the result Color4
  1983. */
  1984. Color4.prototype.multiplyToRef = function (color, result) {
  1985. result.r = this.r * color.r;
  1986. result.g = this.g * color.g;
  1987. result.b = this.b * color.b;
  1988. result.a = this.a * color.a;
  1989. return result;
  1990. };
  1991. /**
  1992. * Creates a string with the Color4 current values
  1993. * @returns the string representation of the Color4 object
  1994. */
  1995. Color4.prototype.toString = function () {
  1996. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1997. };
  1998. /**
  1999. * Returns the string "Color4"
  2000. * @returns "Color4"
  2001. */
  2002. Color4.prototype.getClassName = function () {
  2003. return "Color4";
  2004. };
  2005. /**
  2006. * Compute the Color4 hash code
  2007. * @returns an unique number that can be used to hash Color4 objects
  2008. */
  2009. Color4.prototype.getHashCode = function () {
  2010. var hash = this.r || 0;
  2011. hash = (hash * 397) ^ (this.g || 0);
  2012. hash = (hash * 397) ^ (this.b || 0);
  2013. hash = (hash * 397) ^ (this.a || 0);
  2014. return hash;
  2015. };
  2016. /**
  2017. * Creates a new Color4 copied from the current one
  2018. * @returns a new Color4 object
  2019. */
  2020. Color4.prototype.clone = function () {
  2021. return new Color4(this.r, this.g, this.b, this.a);
  2022. };
  2023. /**
  2024. * Copies the given Color4 values into the current one
  2025. * @param source defines the source Color4 object
  2026. * @returns the current updated Color4 object
  2027. */
  2028. Color4.prototype.copyFrom = function (source) {
  2029. this.r = source.r;
  2030. this.g = source.g;
  2031. this.b = source.b;
  2032. this.a = source.a;
  2033. return this;
  2034. };
  2035. /**
  2036. * Copies the given float values into the current one
  2037. * @param r defines the red component to read from
  2038. * @param g defines the green component to read from
  2039. * @param b defines the blue component to read from
  2040. * @param a defines the alpha component to read from
  2041. * @returns the current updated Color4 object
  2042. */
  2043. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2044. this.r = r;
  2045. this.g = g;
  2046. this.b = b;
  2047. this.a = a;
  2048. return this;
  2049. };
  2050. /**
  2051. * Copies the given float values into the current one
  2052. * @param r defines the red component to read from
  2053. * @param g defines the green component to read from
  2054. * @param b defines the blue component to read from
  2055. * @param a defines the alpha component to read from
  2056. * @returns the current updated Color4 object
  2057. */
  2058. Color4.prototype.set = function (r, g, b, a) {
  2059. return this.copyFromFloats(r, g, b, a);
  2060. };
  2061. /**
  2062. * Compute the Color4 hexadecimal code as a string
  2063. * @returns a string containing the hexadecimal representation of the Color4 object
  2064. */
  2065. Color4.prototype.toHexString = function () {
  2066. var intR = (this.r * 255) | 0;
  2067. var intG = (this.g * 255) | 0;
  2068. var intB = (this.b * 255) | 0;
  2069. var intA = (this.a * 255) | 0;
  2070. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2071. };
  2072. /**
  2073. * Computes a new Color4 converted from the current one to linear space
  2074. * @returns a new Color4 object
  2075. */
  2076. Color4.prototype.toLinearSpace = function () {
  2077. var convertedColor = new Color4();
  2078. this.toLinearSpaceToRef(convertedColor);
  2079. return convertedColor;
  2080. };
  2081. /**
  2082. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2083. * @param convertedColor defines the Color4 object where to store the linear space version
  2084. * @returns the unmodified Color4
  2085. */
  2086. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2087. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2088. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2089. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2090. convertedColor.a = this.a;
  2091. return this;
  2092. };
  2093. /**
  2094. * Computes a new Color4 converted from the current one to gamma space
  2095. * @returns a new Color4 object
  2096. */
  2097. Color4.prototype.toGammaSpace = function () {
  2098. var convertedColor = new Color4();
  2099. this.toGammaSpaceToRef(convertedColor);
  2100. return convertedColor;
  2101. };
  2102. /**
  2103. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2104. * @param convertedColor defines the Color4 object where to store the gamma space version
  2105. * @returns the unmodified Color4
  2106. */
  2107. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2108. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2109. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2110. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2111. convertedColor.a = this.a;
  2112. return this;
  2113. };
  2114. // Statics
  2115. /**
  2116. * Creates a new Color4 from the string containing valid hexadecimal values
  2117. * @param hex defines a string containing valid hexadecimal values
  2118. * @returns a new Color4 object
  2119. */
  2120. Color4.FromHexString = function (hex) {
  2121. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2122. return new Color4(0.0, 0.0, 0.0, 0.0);
  2123. }
  2124. var r = parseInt(hex.substring(1, 3), 16);
  2125. var g = parseInt(hex.substring(3, 5), 16);
  2126. var b = parseInt(hex.substring(5, 7), 16);
  2127. var a = parseInt(hex.substring(7, 9), 16);
  2128. return Color4.FromInts(r, g, b, a);
  2129. };
  2130. /**
  2131. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2132. * @param left defines the start value
  2133. * @param right defines the end value
  2134. * @param amount defines the gradient factor
  2135. * @returns a new Color4 object
  2136. */
  2137. Color4.Lerp = function (left, right, amount) {
  2138. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2139. Color4.LerpToRef(left, right, amount, result);
  2140. return result;
  2141. };
  2142. /**
  2143. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2144. * @param left defines the start value
  2145. * @param right defines the end value
  2146. * @param amount defines the gradient factor
  2147. * @param result defines the Color4 object where to store data
  2148. */
  2149. Color4.LerpToRef = function (left, right, amount, result) {
  2150. result.r = left.r + (right.r - left.r) * amount;
  2151. result.g = left.g + (right.g - left.g) * amount;
  2152. result.b = left.b + (right.b - left.b) * amount;
  2153. result.a = left.a + (right.a - left.a) * amount;
  2154. };
  2155. /**
  2156. * Creates a new Color4 from the starting index element of the given array
  2157. * @param array defines the source array to read from
  2158. * @param offset defines the offset in the source array
  2159. * @returns a new Color4 object
  2160. */
  2161. Color4.FromArray = function (array, offset) {
  2162. if (offset === void 0) { offset = 0; }
  2163. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2164. };
  2165. /**
  2166. * Creates a new Color3 from integer values (< 256)
  2167. * @param r defines the red component to read from (value between 0 and 255)
  2168. * @param g defines the green component to read from (value between 0 and 255)
  2169. * @param b defines the blue component to read from (value between 0 and 255)
  2170. * @param a defines the alpha component to read from (value between 0 and 255)
  2171. * @returns a new Color3 object
  2172. */
  2173. Color4.FromInts = function (r, g, b, a) {
  2174. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2175. };
  2176. /**
  2177. * Check the content of a given array and convert it to an array containing RGBA data
  2178. * If the original array was already containing count * 4 values then it is returned directly
  2179. * @param colors defines the array to check
  2180. * @param count defines the number of RGBA data to expect
  2181. * @returns an array containing count * 4 values (RGBA)
  2182. */
  2183. Color4.CheckColors4 = function (colors, count) {
  2184. // Check if color3 was used
  2185. if (colors.length === count * 3) {
  2186. var colors4 = [];
  2187. for (var index = 0; index < colors.length; index += 3) {
  2188. var newIndex = (index / 3) * 4;
  2189. colors4[newIndex] = colors[index];
  2190. colors4[newIndex + 1] = colors[index + 1];
  2191. colors4[newIndex + 2] = colors[index + 2];
  2192. colors4[newIndex + 3] = 1.0;
  2193. }
  2194. return colors4;
  2195. }
  2196. return colors;
  2197. };
  2198. return Color4;
  2199. }());
  2200. BABYLON.Color4 = Color4;
  2201. /**
  2202. * Class representing a vector containing 2 coordinates
  2203. */
  2204. var Vector2 = /** @class */ (function () {
  2205. /**
  2206. * Creates a new Vector2 from the given x and y coordinates
  2207. * @param x defines the first coordinate
  2208. * @param y defines the second coordinate
  2209. */
  2210. function Vector2(
  2211. /** defines the first coordinate */
  2212. x,
  2213. /** defines the second coordinate */
  2214. y) {
  2215. if (x === void 0) { x = 0; }
  2216. if (y === void 0) { y = 0; }
  2217. this.x = x;
  2218. this.y = y;
  2219. }
  2220. /**
  2221. * Gets a string with the Vector2 coordinates
  2222. * @returns a string with the Vector2 coordinates
  2223. */
  2224. Vector2.prototype.toString = function () {
  2225. return "{X: " + this.x + " Y:" + this.y + "}";
  2226. };
  2227. /**
  2228. * Gets class name
  2229. * @returns the string "Vector2"
  2230. */
  2231. Vector2.prototype.getClassName = function () {
  2232. return "Vector2";
  2233. };
  2234. /**
  2235. * Gets current vector hash code
  2236. * @returns the Vector2 hash code as a number
  2237. */
  2238. Vector2.prototype.getHashCode = function () {
  2239. var hash = this.x || 0;
  2240. hash = (hash * 397) ^ (this.y || 0);
  2241. return hash;
  2242. };
  2243. // Operators
  2244. /**
  2245. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2246. * @param array defines the source array
  2247. * @param index defines the offset in source array
  2248. * @returns the current Vector2
  2249. */
  2250. Vector2.prototype.toArray = function (array, index) {
  2251. if (index === void 0) { index = 0; }
  2252. array[index] = this.x;
  2253. array[index + 1] = this.y;
  2254. return this;
  2255. };
  2256. /**
  2257. * Copy the current vector to an array
  2258. * @returns a new array with 2 elements: the Vector2 coordinates.
  2259. */
  2260. Vector2.prototype.asArray = function () {
  2261. var result = new Array();
  2262. this.toArray(result, 0);
  2263. return result;
  2264. };
  2265. /**
  2266. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2267. * @param source defines the source Vector2
  2268. * @returns the current updated Vector2
  2269. */
  2270. Vector2.prototype.copyFrom = function (source) {
  2271. this.x = source.x;
  2272. this.y = source.y;
  2273. return this;
  2274. };
  2275. /**
  2276. * Sets the Vector2 coordinates with the given floats
  2277. * @param x defines the first coordinate
  2278. * @param y defines the second coordinate
  2279. * @returns the current updated Vector2
  2280. */
  2281. Vector2.prototype.copyFromFloats = function (x, y) {
  2282. this.x = x;
  2283. this.y = y;
  2284. return this;
  2285. };
  2286. /**
  2287. * Sets the Vector2 coordinates with the given floats
  2288. * @param x defines the first coordinate
  2289. * @param y defines the second coordinate
  2290. * @returns the current updated Vector2
  2291. */
  2292. Vector2.prototype.set = function (x, y) {
  2293. return this.copyFromFloats(x, y);
  2294. };
  2295. /**
  2296. * Add another vector with the current one
  2297. * @param otherVector defines the other vector
  2298. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2299. */
  2300. Vector2.prototype.add = function (otherVector) {
  2301. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2302. };
  2303. /**
  2304. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2305. * @param otherVector defines the other vector
  2306. * @param result defines the target vector
  2307. * @returns the unmodified current Vector2
  2308. */
  2309. Vector2.prototype.addToRef = function (otherVector, result) {
  2310. result.x = this.x + otherVector.x;
  2311. result.y = this.y + otherVector.y;
  2312. return this;
  2313. };
  2314. /**
  2315. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2316. * @param otherVector defines the other vector
  2317. * @returns the current updated Vector2
  2318. */
  2319. Vector2.prototype.addInPlace = function (otherVector) {
  2320. this.x += otherVector.x;
  2321. this.y += otherVector.y;
  2322. return this;
  2323. };
  2324. /**
  2325. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2326. * @param otherVector defines the other vector
  2327. * @returns a new Vector2
  2328. */
  2329. Vector2.prototype.addVector3 = function (otherVector) {
  2330. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2331. };
  2332. /**
  2333. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2334. * @param otherVector defines the other vector
  2335. * @returns a new Vector2
  2336. */
  2337. Vector2.prototype.subtract = function (otherVector) {
  2338. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2339. };
  2340. /**
  2341. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2342. * @param otherVector defines the other vector
  2343. * @param result defines the target vector
  2344. * @returns the unmodified current Vector2
  2345. */
  2346. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2347. result.x = this.x - otherVector.x;
  2348. result.y = this.y - otherVector.y;
  2349. return this;
  2350. };
  2351. /**
  2352. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2353. * @param otherVector defines the other vector
  2354. * @returns the current updated Vector2
  2355. */
  2356. Vector2.prototype.subtractInPlace = function (otherVector) {
  2357. this.x -= otherVector.x;
  2358. this.y -= otherVector.y;
  2359. return this;
  2360. };
  2361. /**
  2362. * Multiplies in place the current Vector2 coordinates by the given ones
  2363. * @param otherVector defines the other vector
  2364. * @returns the current updated Vector2
  2365. */
  2366. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2367. this.x *= otherVector.x;
  2368. this.y *= otherVector.y;
  2369. return this;
  2370. };
  2371. /**
  2372. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2373. * @param otherVector defines the other vector
  2374. * @returns a new Vector2
  2375. */
  2376. Vector2.prototype.multiply = function (otherVector) {
  2377. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2378. };
  2379. /**
  2380. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2381. * @param otherVector defines the other vector
  2382. * @param result defines the target vector
  2383. * @returns the unmodified current Vector2
  2384. */
  2385. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2386. result.x = this.x * otherVector.x;
  2387. result.y = this.y * otherVector.y;
  2388. return this;
  2389. };
  2390. /**
  2391. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2392. * @param x defines the first coordinate
  2393. * @param y defines the second coordinate
  2394. * @returns a new Vector2
  2395. */
  2396. Vector2.prototype.multiplyByFloats = function (x, y) {
  2397. return new Vector2(this.x * x, this.y * y);
  2398. };
  2399. /**
  2400. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.divide = function (otherVector) {
  2405. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2406. };
  2407. /**
  2408. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2409. * @param otherVector defines the other vector
  2410. * @param result defines the target vector
  2411. * @returns the unmodified current Vector2
  2412. */
  2413. Vector2.prototype.divideToRef = function (otherVector, result) {
  2414. result.x = this.x / otherVector.x;
  2415. result.y = this.y / otherVector.y;
  2416. return this;
  2417. };
  2418. /**
  2419. * Divides the current Vector2 coordinates by the given ones
  2420. * @param otherVector defines the other vector
  2421. * @returns the current updated Vector2
  2422. */
  2423. Vector2.prototype.divideInPlace = function (otherVector) {
  2424. return this.divideToRef(otherVector, this);
  2425. };
  2426. /**
  2427. * Gets a new Vector2 with current Vector2 negated coordinates
  2428. * @returns a new Vector2
  2429. */
  2430. Vector2.prototype.negate = function () {
  2431. return new Vector2(-this.x, -this.y);
  2432. };
  2433. /**
  2434. * Multiply the Vector2 coordinates by scale
  2435. * @param scale defines the scaling factor
  2436. * @returns the current updated Vector2
  2437. */
  2438. Vector2.prototype.scaleInPlace = function (scale) {
  2439. this.x *= scale;
  2440. this.y *= scale;
  2441. return this;
  2442. };
  2443. /**
  2444. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2445. * @param scale defines the scaling factor
  2446. * @returns a new Vector2
  2447. */
  2448. Vector2.prototype.scale = function (scale) {
  2449. var result = new Vector2(0, 0);
  2450. this.scaleToRef(scale, result);
  2451. return result;
  2452. };
  2453. /**
  2454. * Scale the current Vector2 values by a factor to a given Vector2
  2455. * @param scale defines the scale factor
  2456. * @param result defines the Vector2 object where to store the result
  2457. * @returns the unmodified current Vector2
  2458. */
  2459. Vector2.prototype.scaleToRef = function (scale, result) {
  2460. result.x = this.x * scale;
  2461. result.y = this.y * scale;
  2462. return this;
  2463. };
  2464. /**
  2465. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2466. * @param scale defines the scale factor
  2467. * @param result defines the Vector2 object where to store the result
  2468. * @returns the unmodified current Vector2
  2469. */
  2470. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2471. result.x += this.x * scale;
  2472. result.y += this.y * scale;
  2473. return this;
  2474. };
  2475. /**
  2476. * Gets a boolean if two vectors are equals
  2477. * @param otherVector defines the other vector
  2478. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2479. */
  2480. Vector2.prototype.equals = function (otherVector) {
  2481. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2482. };
  2483. /**
  2484. * Gets a boolean if two vectors are equals (using an epsilon value)
  2485. * @param otherVector defines the other vector
  2486. * @param epsilon defines the minimal distance to consider equality
  2487. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2488. */
  2489. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2490. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2491. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2492. };
  2493. /**
  2494. * Gets a new Vector2 from current Vector2 floored values
  2495. * @returns a new Vector2
  2496. */
  2497. Vector2.prototype.floor = function () {
  2498. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2499. };
  2500. /**
  2501. * Gets a new Vector2 from current Vector2 floored values
  2502. * @returns a new Vector2
  2503. */
  2504. Vector2.prototype.fract = function () {
  2505. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2506. };
  2507. // Properties
  2508. /**
  2509. * Gets the length of the vector
  2510. * @returns the vector length (float)
  2511. */
  2512. Vector2.prototype.length = function () {
  2513. return Math.sqrt(this.x * this.x + this.y * this.y);
  2514. };
  2515. /**
  2516. * Gets the vector squared length
  2517. * @returns the vector squared length (float)
  2518. */
  2519. Vector2.prototype.lengthSquared = function () {
  2520. return (this.x * this.x + this.y * this.y);
  2521. };
  2522. // Methods
  2523. /**
  2524. * Normalize the vector
  2525. * @returns the current updated Vector2
  2526. */
  2527. Vector2.prototype.normalize = function () {
  2528. var len = this.length();
  2529. if (len === 0)
  2530. return this;
  2531. var num = 1.0 / len;
  2532. this.x *= num;
  2533. this.y *= num;
  2534. return this;
  2535. };
  2536. /**
  2537. * Gets a new Vector2 copied from the Vector2
  2538. * @returns a new Vector2
  2539. */
  2540. Vector2.prototype.clone = function () {
  2541. return new Vector2(this.x, this.y);
  2542. };
  2543. // Statics
  2544. /**
  2545. * Gets a new Vector2(0, 0)
  2546. * @returns a new Vector2
  2547. */
  2548. Vector2.Zero = function () {
  2549. return new Vector2(0, 0);
  2550. };
  2551. /**
  2552. * Gets a new Vector2(1, 1)
  2553. * @returns a new Vector2
  2554. */
  2555. Vector2.One = function () {
  2556. return new Vector2(1, 1);
  2557. };
  2558. /**
  2559. * Gets a new Vector2 set from the given index element of the given array
  2560. * @param array defines the data source
  2561. * @param offset defines the offset in the data source
  2562. * @returns a new Vector2
  2563. */
  2564. Vector2.FromArray = function (array, offset) {
  2565. if (offset === void 0) { offset = 0; }
  2566. return new Vector2(array[offset], array[offset + 1]);
  2567. };
  2568. /**
  2569. * Sets "result" from the given index element of the given array
  2570. * @param array defines the data source
  2571. * @param offset defines the offset in the data source
  2572. * @param result defines the target vector
  2573. */
  2574. Vector2.FromArrayToRef = function (array, offset, result) {
  2575. result.x = array[offset];
  2576. result.y = array[offset + 1];
  2577. };
  2578. /**
  2579. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2580. * @param value1 defines 1st point of control
  2581. * @param value2 defines 2nd point of control
  2582. * @param value3 defines 3rd point of control
  2583. * @param value4 defines 4th point of control
  2584. * @param amount defines the interpolation factor
  2585. * @returns a new Vector2
  2586. */
  2587. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2588. var squared = amount * amount;
  2589. var cubed = amount * squared;
  2590. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2591. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2592. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2593. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2594. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2595. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2596. return new Vector2(x, y);
  2597. };
  2598. /**
  2599. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2600. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2601. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2602. * @param value defines the value to clamp
  2603. * @param min defines the lower limit
  2604. * @param max defines the upper limit
  2605. * @returns a new Vector2
  2606. */
  2607. Vector2.Clamp = function (value, min, max) {
  2608. var x = value.x;
  2609. x = (x > max.x) ? max.x : x;
  2610. x = (x < min.x) ? min.x : x;
  2611. var y = value.y;
  2612. y = (y > max.y) ? max.y : y;
  2613. y = (y < min.y) ? min.y : y;
  2614. return new Vector2(x, y);
  2615. };
  2616. /**
  2617. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2618. * @param value1 defines the 1st control point
  2619. * @param tangent1 defines the outgoing tangent
  2620. * @param value2 defines the 2nd control point
  2621. * @param tangent2 defines the incoming tangent
  2622. * @param amount defines the interpolation factor
  2623. * @returns a new Vector2
  2624. */
  2625. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2626. var squared = amount * amount;
  2627. var cubed = amount * squared;
  2628. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2629. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2630. var part3 = (cubed - (2.0 * squared)) + amount;
  2631. var part4 = cubed - squared;
  2632. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2633. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2634. return new Vector2(x, y);
  2635. };
  2636. /**
  2637. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2638. * @param start defines the start vector
  2639. * @param end defines the end vector
  2640. * @param amount defines the interpolation factor
  2641. * @returns a new Vector2
  2642. */
  2643. Vector2.Lerp = function (start, end, amount) {
  2644. var x = start.x + ((end.x - start.x) * amount);
  2645. var y = start.y + ((end.y - start.y) * amount);
  2646. return new Vector2(x, y);
  2647. };
  2648. /**
  2649. * Gets the dot product of the vector "left" and the vector "right"
  2650. * @param left defines first vector
  2651. * @param right defines second vector
  2652. * @returns the dot product (float)
  2653. */
  2654. Vector2.Dot = function (left, right) {
  2655. return left.x * right.x + left.y * right.y;
  2656. };
  2657. /**
  2658. * Returns a new Vector2 equal to the normalized given vector
  2659. * @param vector defines the vector to normalize
  2660. * @returns a new Vector2
  2661. */
  2662. Vector2.Normalize = function (vector) {
  2663. var newVector = vector.clone();
  2664. newVector.normalize();
  2665. return newVector;
  2666. };
  2667. /**
  2668. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2669. * @param left defines 1st vector
  2670. * @param right defines 2nd vector
  2671. * @returns a new Vector2
  2672. */
  2673. Vector2.Minimize = function (left, right) {
  2674. var x = (left.x < right.x) ? left.x : right.x;
  2675. var y = (left.y < right.y) ? left.y : right.y;
  2676. return new Vector2(x, y);
  2677. };
  2678. /**
  2679. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2680. * @param left defines 1st vector
  2681. * @param right defines 2nd vector
  2682. * @returns a new Vector2
  2683. */
  2684. Vector2.Maximize = function (left, right) {
  2685. var x = (left.x > right.x) ? left.x : right.x;
  2686. var y = (left.y > right.y) ? left.y : right.y;
  2687. return new Vector2(x, y);
  2688. };
  2689. /**
  2690. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2691. * @param vector defines the vector to transform
  2692. * @param transformation defines the matrix to apply
  2693. * @returns a new Vector2
  2694. */
  2695. Vector2.Transform = function (vector, transformation) {
  2696. var r = Vector2.Zero();
  2697. Vector2.TransformToRef(vector, transformation, r);
  2698. return r;
  2699. };
  2700. /**
  2701. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2702. * @param vector defines the vector to transform
  2703. * @param transformation defines the matrix to apply
  2704. * @param result defines the target vector
  2705. */
  2706. Vector2.TransformToRef = function (vector, transformation, result) {
  2707. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2708. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2709. result.x = x;
  2710. result.y = y;
  2711. };
  2712. /**
  2713. * Determines if a given vector is included in a triangle
  2714. * @param p defines the vector to test
  2715. * @param p0 defines 1st triangle point
  2716. * @param p1 defines 2nd triangle point
  2717. * @param p2 defines 3rd triangle point
  2718. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2719. */
  2720. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2721. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2722. var sign = a < 0 ? -1 : 1;
  2723. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2724. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2725. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2726. };
  2727. /**
  2728. * Gets the distance between the vectors "value1" and "value2"
  2729. * @param value1 defines first vector
  2730. * @param value2 defines second vector
  2731. * @returns the distance between vectors
  2732. */
  2733. Vector2.Distance = function (value1, value2) {
  2734. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2735. };
  2736. /**
  2737. * Returns the squared distance between the vectors "value1" and "value2"
  2738. * @param value1 defines first vector
  2739. * @param value2 defines second vector
  2740. * @returns the squared distance between vectors
  2741. */
  2742. Vector2.DistanceSquared = function (value1, value2) {
  2743. var x = value1.x - value2.x;
  2744. var y = value1.y - value2.y;
  2745. return (x * x) + (y * y);
  2746. };
  2747. /**
  2748. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2749. * @param value1 defines first vector
  2750. * @param value2 defines second vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Center = function (value1, value2) {
  2754. var center = value1.add(value2);
  2755. center.scaleInPlace(0.5);
  2756. return center;
  2757. };
  2758. /**
  2759. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2760. * @param p defines the middle point
  2761. * @param segA defines one point of the segment
  2762. * @param segB defines the other point of the segment
  2763. * @returns the shortest distance
  2764. */
  2765. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2766. var l2 = Vector2.DistanceSquared(segA, segB);
  2767. if (l2 === 0.0) {
  2768. return Vector2.Distance(p, segA);
  2769. }
  2770. var v = segB.subtract(segA);
  2771. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2772. var proj = segA.add(v.multiplyByFloats(t, t));
  2773. return Vector2.Distance(p, proj);
  2774. };
  2775. return Vector2;
  2776. }());
  2777. BABYLON.Vector2 = Vector2;
  2778. /**
  2779. * Classed used to store (x,y,z) vector representation
  2780. * A Vector3 is the main object used in 3D geometry
  2781. * It can represent etiher the coordinates of a point the space, either a direction
  2782. * Reminder: Babylon.js uses a left handed forward facing system
  2783. */
  2784. var Vector3 = /** @class */ (function () {
  2785. /**
  2786. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2787. * @param x defines the first coordinates (on X axis)
  2788. * @param y defines the second coordinates (on Y axis)
  2789. * @param z defines the third coordinates (on Z axis)
  2790. */
  2791. function Vector3(
  2792. /**
  2793. * Defines the first coordinates (on X axis)
  2794. */
  2795. x,
  2796. /**
  2797. * Defines the second coordinates (on Y axis)
  2798. */
  2799. y,
  2800. /**
  2801. * Defines the third coordinates (on Z axis)
  2802. */
  2803. z) {
  2804. if (x === void 0) { x = 0; }
  2805. if (y === void 0) { y = 0; }
  2806. if (z === void 0) { z = 0; }
  2807. this.x = x;
  2808. this.y = y;
  2809. this.z = z;
  2810. }
  2811. /**
  2812. * Creates a string representation of the Vector3
  2813. * @returns a string with the Vector3 coordinates.
  2814. */
  2815. Vector3.prototype.toString = function () {
  2816. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2817. };
  2818. /**
  2819. * Gets the class name
  2820. * @returns the string "Vector3"
  2821. */
  2822. Vector3.prototype.getClassName = function () {
  2823. return "Vector3";
  2824. };
  2825. /**
  2826. * Creates the Vector3 hash code
  2827. * @returns a number which tends to be unique between Vector3 instances
  2828. */
  2829. Vector3.prototype.getHashCode = function () {
  2830. var hash = this.x || 0;
  2831. hash = (hash * 397) ^ (this.y || 0);
  2832. hash = (hash * 397) ^ (this.z || 0);
  2833. return hash;
  2834. };
  2835. // Operators
  2836. /**
  2837. * Creates an array containing three elements : the coordinates of the Vector3
  2838. * @returns a new array of numbers
  2839. */
  2840. Vector3.prototype.asArray = function () {
  2841. var result = [];
  2842. this.toArray(result, 0);
  2843. return result;
  2844. };
  2845. /**
  2846. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2847. * @param array defines the destination array
  2848. * @param index defines the offset in the destination array
  2849. * @returns the current Vector3
  2850. */
  2851. Vector3.prototype.toArray = function (array, index) {
  2852. if (index === void 0) { index = 0; }
  2853. array[index] = this.x;
  2854. array[index + 1] = this.y;
  2855. array[index + 2] = this.z;
  2856. return this;
  2857. };
  2858. /**
  2859. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2860. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2861. */
  2862. Vector3.prototype.toQuaternion = function () {
  2863. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2864. };
  2865. /**
  2866. * Adds the given vector to the current Vector3
  2867. * @param otherVector defines the second operand
  2868. * @returns the current updated Vector3
  2869. */
  2870. Vector3.prototype.addInPlace = function (otherVector) {
  2871. this.x += otherVector.x;
  2872. this.y += otherVector.y;
  2873. this.z += otherVector.z;
  2874. return this;
  2875. };
  2876. /**
  2877. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2878. * @param otherVector defines the second operand
  2879. * @returns the resulting Vector3
  2880. */
  2881. Vector3.prototype.add = function (otherVector) {
  2882. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2883. };
  2884. /**
  2885. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2886. * @param otherVector defines the second operand
  2887. * @param result defines the Vector3 object where to store the result
  2888. * @returns the current Vector3
  2889. */
  2890. Vector3.prototype.addToRef = function (otherVector, result) {
  2891. result.x = this.x + otherVector.x;
  2892. result.y = this.y + otherVector.y;
  2893. result.z = this.z + otherVector.z;
  2894. return this;
  2895. };
  2896. /**
  2897. * Subtract the given vector from the current Vector3
  2898. * @param otherVector defines the second operand
  2899. * @returns the current updated Vector3
  2900. */
  2901. Vector3.prototype.subtractInPlace = function (otherVector) {
  2902. this.x -= otherVector.x;
  2903. this.y -= otherVector.y;
  2904. this.z -= otherVector.z;
  2905. return this;
  2906. };
  2907. /**
  2908. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2909. * @param otherVector defines the second operand
  2910. * @returns the resulting Vector3
  2911. */
  2912. Vector3.prototype.subtract = function (otherVector) {
  2913. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2914. };
  2915. /**
  2916. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2917. * @param otherVector defines the second operand
  2918. * @param result defines the Vector3 object where to store the result
  2919. * @returns the current Vector3
  2920. */
  2921. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2922. result.x = this.x - otherVector.x;
  2923. result.y = this.y - otherVector.y;
  2924. result.z = this.z - otherVector.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2929. * @param x defines the x coordinate of the operand
  2930. * @param y defines the y coordinate of the operand
  2931. * @param z defines the z coordinate of the operand
  2932. * @returns the resulting Vector3
  2933. */
  2934. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2935. return new Vector3(this.x - x, this.y - y, this.z - z);
  2936. };
  2937. /**
  2938. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2939. * @param x defines the x coordinate of the operand
  2940. * @param y defines the y coordinate of the operand
  2941. * @param z defines the z coordinate of the operand
  2942. * @param result defines the Vector3 object where to store the result
  2943. * @returns the current Vector3
  2944. */
  2945. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2946. result.x = this.x - x;
  2947. result.y = this.y - y;
  2948. result.z = this.z - z;
  2949. return this;
  2950. };
  2951. /**
  2952. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2953. * @returns a new Vector3
  2954. */
  2955. Vector3.prototype.negate = function () {
  2956. return new Vector3(-this.x, -this.y, -this.z);
  2957. };
  2958. /**
  2959. * Multiplies the Vector3 coordinates by the float "scale"
  2960. * @param scale defines the multiplier factor
  2961. * @returns the current updated Vector3
  2962. */
  2963. Vector3.prototype.scaleInPlace = function (scale) {
  2964. this.x *= scale;
  2965. this.y *= scale;
  2966. this.z *= scale;
  2967. return this;
  2968. };
  2969. /**
  2970. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2971. * @param scale defines the multiplier factor
  2972. * @returns a new Vector3
  2973. */
  2974. Vector3.prototype.scale = function (scale) {
  2975. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2976. };
  2977. /**
  2978. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2979. * @param scale defines the multiplier factor
  2980. * @param result defines the Vector3 object where to store the result
  2981. * @returns the current Vector3
  2982. */
  2983. Vector3.prototype.scaleToRef = function (scale, result) {
  2984. result.x = this.x * scale;
  2985. result.y = this.y * scale;
  2986. result.z = this.z * scale;
  2987. return this;
  2988. };
  2989. /**
  2990. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2991. * @param scale defines the scale factor
  2992. * @param result defines the Vector3 object where to store the result
  2993. * @returns the unmodified current Vector3
  2994. */
  2995. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2996. result.x += this.x * scale;
  2997. result.y += this.y * scale;
  2998. result.z += this.z * scale;
  2999. return this;
  3000. };
  3001. /**
  3002. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3003. * @param otherVector defines the second operand
  3004. * @returns true if both vectors are equals
  3005. */
  3006. Vector3.prototype.equals = function (otherVector) {
  3007. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3008. };
  3009. /**
  3010. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3011. * @param otherVector defines the second operand
  3012. * @param epsilon defines the minimal distance to define values as equals
  3013. * @returns true if both vectors are distant less than epsilon
  3014. */
  3015. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3016. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3017. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3018. };
  3019. /**
  3020. * Returns true if the current Vector3 coordinates equals the given floats
  3021. * @param x defines the x coordinate of the operand
  3022. * @param y defines the y coordinate of the operand
  3023. * @param z defines the z coordinate of the operand
  3024. * @returns true if both vectors are equals
  3025. */
  3026. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3027. return this.x === x && this.y === y && this.z === z;
  3028. };
  3029. /**
  3030. * Multiplies the current Vector3 coordinates by the given ones
  3031. * @param otherVector defines the second operand
  3032. * @returns the current updated Vector3
  3033. */
  3034. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3035. this.x *= otherVector.x;
  3036. this.y *= otherVector.y;
  3037. this.z *= otherVector.z;
  3038. return this;
  3039. };
  3040. /**
  3041. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3042. * @param otherVector defines the second operand
  3043. * @returns the new Vector3
  3044. */
  3045. Vector3.prototype.multiply = function (otherVector) {
  3046. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3047. };
  3048. /**
  3049. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3050. * @param otherVector defines the second operand
  3051. * @param result defines the Vector3 object where to store the result
  3052. * @returns the current Vector3
  3053. */
  3054. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3055. result.x = this.x * otherVector.x;
  3056. result.y = this.y * otherVector.y;
  3057. result.z = this.z * otherVector.z;
  3058. return this;
  3059. };
  3060. /**
  3061. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3062. * @param x defines the x coordinate of the operand
  3063. * @param y defines the y coordinate of the operand
  3064. * @param z defines the z coordinate of the operand
  3065. * @returns the new Vector3
  3066. */
  3067. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3068. return new Vector3(this.x * x, this.y * y, this.z * z);
  3069. };
  3070. /**
  3071. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3072. * @param otherVector defines the second operand
  3073. * @returns the new Vector3
  3074. */
  3075. Vector3.prototype.divide = function (otherVector) {
  3076. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3077. };
  3078. /**
  3079. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3080. * @param otherVector defines the second operand
  3081. * @param result defines the Vector3 object where to store the result
  3082. * @returns the current Vector3
  3083. */
  3084. Vector3.prototype.divideToRef = function (otherVector, result) {
  3085. result.x = this.x / otherVector.x;
  3086. result.y = this.y / otherVector.y;
  3087. result.z = this.z / otherVector.z;
  3088. return this;
  3089. };
  3090. /**
  3091. * Divides the current Vector3 coordinates by the given ones.
  3092. * @param otherVector defines the second operand
  3093. * @returns the current updated Vector3
  3094. */
  3095. Vector3.prototype.divideInPlace = function (otherVector) {
  3096. return this.divideToRef(otherVector, this);
  3097. };
  3098. /**
  3099. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3100. * @param other defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.minimizeInPlace = function (other) {
  3104. if (other.x < this.x)
  3105. this.x = other.x;
  3106. if (other.y < this.y)
  3107. this.y = other.y;
  3108. if (other.z < this.z)
  3109. this.z = other.z;
  3110. return this;
  3111. };
  3112. /**
  3113. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3114. * @param other defines the second operand
  3115. * @returns the current updated Vector3
  3116. */
  3117. Vector3.prototype.maximizeInPlace = function (other) {
  3118. if (other.x > this.x)
  3119. this.x = other.x;
  3120. if (other.y > this.y)
  3121. this.y = other.y;
  3122. if (other.z > this.z)
  3123. this.z = other.z;
  3124. return this;
  3125. };
  3126. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3127. /**
  3128. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3129. */
  3130. get: function () {
  3131. var absX = Math.abs(this.x);
  3132. var absY = Math.abs(this.y);
  3133. if (absX !== absY) {
  3134. return true;
  3135. }
  3136. var absZ = Math.abs(this.z);
  3137. if (absX !== absZ) {
  3138. return true;
  3139. }
  3140. if (absY !== absZ) {
  3141. return true;
  3142. }
  3143. return false;
  3144. },
  3145. enumerable: true,
  3146. configurable: true
  3147. });
  3148. /**
  3149. * Gets a new Vector3 from current Vector3 floored values
  3150. * @returns a new Vector3
  3151. */
  3152. Vector3.prototype.floor = function () {
  3153. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3154. };
  3155. /**
  3156. * Gets a new Vector3 from current Vector3 floored values
  3157. * @returns a new Vector3
  3158. */
  3159. Vector3.prototype.fract = function () {
  3160. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3161. };
  3162. // Properties
  3163. /**
  3164. * Gets the length of the Vector3
  3165. * @returns the length of the Vecto3
  3166. */
  3167. Vector3.prototype.length = function () {
  3168. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3169. };
  3170. /**
  3171. * Gets the squared length of the Vector3
  3172. * @returns squared length of the Vector3
  3173. */
  3174. Vector3.prototype.lengthSquared = function () {
  3175. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3176. };
  3177. /**
  3178. * Normalize the current Vector3.
  3179. * Please note that this is an in place operation.
  3180. * @returns the current updated Vector3
  3181. */
  3182. Vector3.prototype.normalize = function () {
  3183. var len = this.length();
  3184. if (len === 0 || len === 1.0)
  3185. return this;
  3186. var num = 1.0 / len;
  3187. this.x *= num;
  3188. this.y *= num;
  3189. this.z *= num;
  3190. return this;
  3191. };
  3192. /**
  3193. * Normalize the current Vector3 to a new vector
  3194. * @returns the new Vector3
  3195. */
  3196. Vector3.prototype.normalizeToNew = function () {
  3197. var normalized = new Vector3(0, 0, 0);
  3198. this.normalizeToRef(normalized);
  3199. return normalized;
  3200. };
  3201. /**
  3202. * Normalize the current Vector3 to the reference
  3203. * @param reference define the Vector3 to update
  3204. * @returns the updated Vector3
  3205. */
  3206. Vector3.prototype.normalizeToRef = function (reference) {
  3207. var len = this.length();
  3208. if (len === 0 || len === 1.0) {
  3209. reference.set(this.x, this.y, this.z);
  3210. return reference;
  3211. }
  3212. var scale = 1.0 / len;
  3213. this.scaleToRef(scale, reference);
  3214. return reference;
  3215. };
  3216. /**
  3217. * Creates a new Vector3 copied from the current Vector3
  3218. * @returns the new Vector3
  3219. */
  3220. Vector3.prototype.clone = function () {
  3221. return new Vector3(this.x, this.y, this.z);
  3222. };
  3223. /**
  3224. * Copies the given vector coordinates to the current Vector3 ones
  3225. * @param source defines the source Vector3
  3226. * @returns the current updated Vector3
  3227. */
  3228. Vector3.prototype.copyFrom = function (source) {
  3229. this.x = source.x;
  3230. this.y = source.y;
  3231. this.z = source.z;
  3232. return this;
  3233. };
  3234. /**
  3235. * Copies the given floats to the current Vector3 coordinates
  3236. * @param x defines the x coordinate of the operand
  3237. * @param y defines the y coordinate of the operand
  3238. * @param z defines the z coordinate of the operand
  3239. * @returns the current updated Vector3
  3240. */
  3241. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3242. this.x = x;
  3243. this.y = y;
  3244. this.z = z;
  3245. return this;
  3246. };
  3247. /**
  3248. * Copies the given floats to the current Vector3 coordinates
  3249. * @param x defines the x coordinate of the operand
  3250. * @param y defines the y coordinate of the operand
  3251. * @param z defines the z coordinate of the operand
  3252. * @returns the current updated Vector3
  3253. */
  3254. Vector3.prototype.set = function (x, y, z) {
  3255. return this.copyFromFloats(x, y, z);
  3256. };
  3257. // Statics
  3258. /**
  3259. * Get the clip factor between two vectors
  3260. * @param vector0 defines the first operand
  3261. * @param vector1 defines the second operand
  3262. * @param axis defines the axis to use
  3263. * @param size defines the size along the axis
  3264. * @returns the clip factor
  3265. */
  3266. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3267. var d0 = Vector3.Dot(vector0, axis) - size;
  3268. var d1 = Vector3.Dot(vector1, axis) - size;
  3269. var s = d0 / (d0 - d1);
  3270. return s;
  3271. };
  3272. /**
  3273. * Get angle between two vectors
  3274. * @param vector0 angle between vector0 and vector1
  3275. * @param vector1 angle between vector0 and vector1
  3276. * @param normal direction of the normal
  3277. * @return the angle between vector0 and vector1
  3278. */
  3279. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3280. var v0 = vector0.clone().normalize();
  3281. var v1 = vector1.clone().normalize();
  3282. var dot = Vector3.Dot(v0, v1);
  3283. var n = Vector3.Cross(v0, v1);
  3284. if (Vector3.Dot(n, normal) > 0) {
  3285. return Math.acos(dot);
  3286. }
  3287. return -Math.acos(dot);
  3288. };
  3289. /**
  3290. * Returns a new Vector3 set from the index "offset" of the given array
  3291. * @param array defines the source array
  3292. * @param offset defines the offset in the source array
  3293. * @returns the new Vector3
  3294. */
  3295. Vector3.FromArray = function (array, offset) {
  3296. if (!offset) {
  3297. offset = 0;
  3298. }
  3299. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3300. };
  3301. /**
  3302. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3303. * This function is deprecated. Use FromArray instead
  3304. * @param array defines the source array
  3305. * @param offset defines the offset in the source array
  3306. * @returns the new Vector3
  3307. */
  3308. Vector3.FromFloatArray = function (array, offset) {
  3309. return Vector3.FromArray(array, offset);
  3310. };
  3311. /**
  3312. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3313. * @param array defines the source array
  3314. * @param offset defines the offset in the source array
  3315. * @param result defines the Vector3 where to store the result
  3316. */
  3317. Vector3.FromArrayToRef = function (array, offset, result) {
  3318. result.x = array[offset];
  3319. result.y = array[offset + 1];
  3320. result.z = array[offset + 2];
  3321. };
  3322. /**
  3323. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3324. * This function is deprecated. Use FromArrayToRef instead.
  3325. * @param array defines the source array
  3326. * @param offset defines the offset in the source array
  3327. * @param result defines the Vector3 where to store the result
  3328. */
  3329. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3330. return Vector3.FromArrayToRef(array, offset, result);
  3331. };
  3332. /**
  3333. * Sets the given vector "result" with the given floats.
  3334. * @param x defines the x coordinate of the source
  3335. * @param y defines the y coordinate of the source
  3336. * @param z defines the z coordinate of the source
  3337. * @param result defines the Vector3 where to store the result
  3338. */
  3339. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3340. result.x = x;
  3341. result.y = y;
  3342. result.z = z;
  3343. };
  3344. /**
  3345. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3346. * @returns a new empty Vector3
  3347. */
  3348. Vector3.Zero = function () {
  3349. return new Vector3(0.0, 0.0, 0.0);
  3350. };
  3351. /**
  3352. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3353. * @returns a new unit Vector3
  3354. */
  3355. Vector3.One = function () {
  3356. return new Vector3(1.0, 1.0, 1.0);
  3357. };
  3358. /**
  3359. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3360. * @returns a new up Vector3
  3361. */
  3362. Vector3.Up = function () {
  3363. return new Vector3(0.0, 1.0, 0.0);
  3364. };
  3365. /**
  3366. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3367. * @returns a new down Vector3
  3368. */
  3369. Vector3.Down = function () {
  3370. return new Vector3(0.0, -1.0, 0.0);
  3371. };
  3372. /**
  3373. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3374. * @returns a new forward Vector3
  3375. */
  3376. Vector3.Forward = function () {
  3377. return new Vector3(0.0, 0.0, 1.0);
  3378. };
  3379. /**
  3380. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3381. * @returns a new right Vector3
  3382. */
  3383. Vector3.Right = function () {
  3384. return new Vector3(1.0, 0.0, 0.0);
  3385. };
  3386. /**
  3387. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3388. * @returns a new left Vector3
  3389. */
  3390. Vector3.Left = function () {
  3391. return new Vector3(-1.0, 0.0, 0.0);
  3392. };
  3393. /**
  3394. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3395. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3396. * @param vector defines the Vector3 to transform
  3397. * @param transformation defines the transformation matrix
  3398. * @returns the transformed Vector3
  3399. */
  3400. Vector3.TransformCoordinates = function (vector, transformation) {
  3401. var result = Vector3.Zero();
  3402. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3403. return result;
  3404. };
  3405. /**
  3406. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3407. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3408. * @param vector defines the Vector3 to transform
  3409. * @param transformation defines the transformation matrix
  3410. * @param result defines the Vector3 where to store the result
  3411. */
  3412. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3413. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3414. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3415. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3416. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3417. result.x = x / w;
  3418. result.y = y / w;
  3419. result.z = z / w;
  3420. };
  3421. /**
  3422. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3423. * This method computes tranformed coordinates only, not transformed direction vectors
  3424. * @param x define the x coordinate of the source vector
  3425. * @param y define the y coordinate of the source vector
  3426. * @param z define the z coordinate of the source vector
  3427. * @param transformation defines the transformation matrix
  3428. * @param result defines the Vector3 where to store the result
  3429. */
  3430. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3431. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3432. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3433. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3434. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3435. result.x = rx / rw;
  3436. result.y = ry / rw;
  3437. result.z = rz / rw;
  3438. };
  3439. /**
  3440. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3441. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3442. * @param vector defines the Vector3 to transform
  3443. * @param transformation defines the transformation matrix
  3444. * @returns the new Vector3
  3445. */
  3446. Vector3.TransformNormal = function (vector, transformation) {
  3447. var result = Vector3.Zero();
  3448. Vector3.TransformNormalToRef(vector, transformation, result);
  3449. return result;
  3450. };
  3451. /**
  3452. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3453. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3454. * @param vector defines the Vector3 to transform
  3455. * @param transformation defines the transformation matrix
  3456. * @param result defines the Vector3 where to store the result
  3457. */
  3458. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3459. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3460. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3461. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3462. result.x = x;
  3463. result.y = y;
  3464. result.z = z;
  3465. };
  3466. /**
  3467. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3468. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3469. * @param x define the x coordinate of the source vector
  3470. * @param y define the y coordinate of the source vector
  3471. * @param z define the z coordinate of the source vector
  3472. * @param transformation defines the transformation matrix
  3473. * @param result defines the Vector3 where to store the result
  3474. */
  3475. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3476. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3477. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3478. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3479. };
  3480. /**
  3481. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3482. * @param value1 defines the first control point
  3483. * @param value2 defines the second control point
  3484. * @param value3 defines the third control point
  3485. * @param value4 defines the fourth control point
  3486. * @param amount defines the amount on the spline to use
  3487. * @returns the new Vector3
  3488. */
  3489. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3490. var squared = amount * amount;
  3491. var cubed = amount * squared;
  3492. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3493. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3494. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3495. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3496. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3497. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3498. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3499. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3500. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3501. return new Vector3(x, y, z);
  3502. };
  3503. /**
  3504. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3505. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3506. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3507. * @param value defines the current value
  3508. * @param min defines the lower range value
  3509. * @param max defines the upper range value
  3510. * @returns the new Vector3
  3511. */
  3512. Vector3.Clamp = function (value, min, max) {
  3513. var x = value.x;
  3514. x = (x > max.x) ? max.x : x;
  3515. x = (x < min.x) ? min.x : x;
  3516. var y = value.y;
  3517. y = (y > max.y) ? max.y : y;
  3518. y = (y < min.y) ? min.y : y;
  3519. var z = value.z;
  3520. z = (z > max.z) ? max.z : z;
  3521. z = (z < min.z) ? min.z : z;
  3522. return new Vector3(x, y, z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3526. * @param value1 defines the first control point
  3527. * @param tangent1 defines the first tangent vector
  3528. * @param value2 defines the second control point
  3529. * @param tangent2 defines the second tangent vector
  3530. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3531. * @returns the new Vector3
  3532. */
  3533. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3534. var squared = amount * amount;
  3535. var cubed = amount * squared;
  3536. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3537. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3538. var part3 = (cubed - (2.0 * squared)) + amount;
  3539. var part4 = cubed - squared;
  3540. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3541. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3542. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3543. return new Vector3(x, y, z);
  3544. };
  3545. /**
  3546. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3547. * @param start defines the start value
  3548. * @param end defines the end value
  3549. * @param amount max defines amount between both (between 0 and 1)
  3550. * @returns the new Vector3
  3551. */
  3552. Vector3.Lerp = function (start, end, amount) {
  3553. var result = new Vector3(0, 0, 0);
  3554. Vector3.LerpToRef(start, end, amount, result);
  3555. return result;
  3556. };
  3557. /**
  3558. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3559. * @param start defines the start value
  3560. * @param end defines the end value
  3561. * @param amount max defines amount between both (between 0 and 1)
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.LerpToRef = function (start, end, amount, result) {
  3565. result.x = start.x + ((end.x - start.x) * amount);
  3566. result.y = start.y + ((end.y - start.y) * amount);
  3567. result.z = start.z + ((end.z - start.z) * amount);
  3568. };
  3569. /**
  3570. * Returns the dot product (float) between the vectors "left" and "right"
  3571. * @param left defines the left operand
  3572. * @param right defines the right operand
  3573. * @returns the dot product
  3574. */
  3575. Vector3.Dot = function (left, right) {
  3576. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3577. };
  3578. /**
  3579. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3580. * The cross product is then orthogonal to both "left" and "right"
  3581. * @param left defines the left operand
  3582. * @param right defines the right operand
  3583. * @returns the cross product
  3584. */
  3585. Vector3.Cross = function (left, right) {
  3586. var result = Vector3.Zero();
  3587. Vector3.CrossToRef(left, right, result);
  3588. return result;
  3589. };
  3590. /**
  3591. * Sets the given vector "result" with the cross product of "left" and "right"
  3592. * The cross product is then orthogonal to both "left" and "right"
  3593. * @param left defines the left operand
  3594. * @param right defines the right operand
  3595. * @param result defines the Vector3 where to store the result
  3596. */
  3597. Vector3.CrossToRef = function (left, right, result) {
  3598. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3599. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3600. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3601. result.copyFrom(MathTmp.Vector3[0]);
  3602. };
  3603. /**
  3604. * Returns a new Vector3 as the normalization of the given vector
  3605. * @param vector defines the Vector3 to normalize
  3606. * @returns the new Vector3
  3607. */
  3608. Vector3.Normalize = function (vector) {
  3609. var result = Vector3.Zero();
  3610. Vector3.NormalizeToRef(vector, result);
  3611. return result;
  3612. };
  3613. /**
  3614. * Sets the given vector "result" with the normalization of the given first vector
  3615. * @param vector defines the Vector3 to normalize
  3616. * @param result defines the Vector3 where to store the result
  3617. */
  3618. Vector3.NormalizeToRef = function (vector, result) {
  3619. result.copyFrom(vector);
  3620. result.normalize();
  3621. };
  3622. /**
  3623. * Project a Vector3 onto screen space
  3624. * @param vector defines the Vector3 to project
  3625. * @param world defines the world matrix to use
  3626. * @param transform defines the transform (view x projection) matrix to use
  3627. * @param viewport defines the screen viewport to use
  3628. * @returns the new Vector3
  3629. */
  3630. Vector3.Project = function (vector, world, transform, viewport) {
  3631. var cw = viewport.width;
  3632. var ch = viewport.height;
  3633. var cx = viewport.x;
  3634. var cy = viewport.y;
  3635. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3636. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3637. var matrix = MathTmp.Matrix[0];
  3638. world.multiplyToRef(transform, matrix);
  3639. matrix.multiplyToRef(viewportMatrix, matrix);
  3640. return Vector3.TransformCoordinates(vector, matrix);
  3641. };
  3642. /**
  3643. * Unproject from screen space to object space
  3644. * @param source defines the screen space Vector3 to use
  3645. * @param viewportWidth defines the current width of the viewport
  3646. * @param viewportHeight defines the current height of the viewport
  3647. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3648. * @param transform defines the transform (view x projection) matrix to use
  3649. * @returns the new Vector3
  3650. */
  3651. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3652. var matrix = MathTmp.Matrix[0];
  3653. world.multiplyToRef(transform, matrix);
  3654. matrix.invert();
  3655. source.x = source.x / viewportWidth * 2 - 1;
  3656. source.y = -(source.y / viewportHeight * 2 - 1);
  3657. var vector = Vector3.TransformCoordinates(source, matrix);
  3658. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3659. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3660. vector = vector.scale(1.0 / num);
  3661. }
  3662. return vector;
  3663. };
  3664. /**
  3665. * Unproject from screen space to object space
  3666. * @param source defines the screen space Vector3 to use
  3667. * @param viewportWidth defines the current width of the viewport
  3668. * @param viewportHeight defines the current height of the viewport
  3669. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3670. * @param view defines the view matrix to use
  3671. * @param projection defines the projection matrix to use
  3672. * @returns the new Vector3
  3673. */
  3674. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3675. var result = Vector3.Zero();
  3676. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3677. return result;
  3678. };
  3679. /**
  3680. * Unproject from screen space to object space
  3681. * @param source defines the screen space Vector3 to use
  3682. * @param viewportWidth defines the current width of the viewport
  3683. * @param viewportHeight defines the current height of the viewport
  3684. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3685. * @param view defines the view matrix to use
  3686. * @param projection defines the projection matrix to use
  3687. * @param result defines the Vector3 where to store the result
  3688. */
  3689. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3690. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3691. };
  3692. /**
  3693. * Unproject from screen space to object space
  3694. * @param sourceX defines the screen space x coordinate to use
  3695. * @param sourceY defines the screen space y coordinate to use
  3696. * @param sourceZ defines the screen space z coordinate to use
  3697. * @param viewportWidth defines the current width of the viewport
  3698. * @param viewportHeight defines the current height of the viewport
  3699. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3700. * @param view defines the view matrix to use
  3701. * @param projection defines the projection matrix to use
  3702. * @param result defines the Vector3 where to store the result
  3703. */
  3704. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3705. var matrix = MathTmp.Matrix[0];
  3706. world.multiplyToRef(view, matrix);
  3707. matrix.multiplyToRef(projection, matrix);
  3708. matrix.invert();
  3709. var screenSource = MathTmp.Vector3[0];
  3710. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3711. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3712. screenSource.z = 2 * sourceZ - 1.0;
  3713. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3714. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3715. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3716. result.scaleInPlace(1.0 / num);
  3717. }
  3718. };
  3719. /**
  3720. * Gets the minimal coordinate values between two Vector3
  3721. * @param left defines the first operand
  3722. * @param right defines the second operand
  3723. * @returns the new Vector3
  3724. */
  3725. Vector3.Minimize = function (left, right) {
  3726. var min = left.clone();
  3727. min.minimizeInPlace(right);
  3728. return min;
  3729. };
  3730. /**
  3731. * Gets the maximal coordinate values between two Vector3
  3732. * @param left defines the first operand
  3733. * @param right defines the second operand
  3734. * @returns the new Vector3
  3735. */
  3736. Vector3.Maximize = function (left, right) {
  3737. var max = left.clone();
  3738. max.maximizeInPlace(right);
  3739. return max;
  3740. };
  3741. /**
  3742. * Returns the distance between the vectors "value1" and "value2"
  3743. * @param value1 defines the first operand
  3744. * @param value2 defines the second operand
  3745. * @returns the distance
  3746. */
  3747. Vector3.Distance = function (value1, value2) {
  3748. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3749. };
  3750. /**
  3751. * Returns the squared distance between the vectors "value1" and "value2"
  3752. * @param value1 defines the first operand
  3753. * @param value2 defines the second operand
  3754. * @returns the squared distance
  3755. */
  3756. Vector3.DistanceSquared = function (value1, value2) {
  3757. var x = value1.x - value2.x;
  3758. var y = value1.y - value2.y;
  3759. var z = value1.z - value2.z;
  3760. return (x * x) + (y * y) + (z * z);
  3761. };
  3762. /**
  3763. * Returns a new Vector3 located at the center between "value1" and "value2"
  3764. * @param value1 defines the first operand
  3765. * @param value2 defines the second operand
  3766. * @returns the new Vector3
  3767. */
  3768. Vector3.Center = function (value1, value2) {
  3769. var center = value1.add(value2);
  3770. center.scaleInPlace(0.5);
  3771. return center;
  3772. };
  3773. /**
  3774. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3775. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3776. * to something in order to rotate it from its local system to the given target system
  3777. * Note: axis1, axis2 and axis3 are normalized during this operation
  3778. * @param axis1 defines the first axis
  3779. * @param axis2 defines the second axis
  3780. * @param axis3 defines the third axis
  3781. * @returns a new Vector3
  3782. */
  3783. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3784. var rotation = Vector3.Zero();
  3785. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3786. return rotation;
  3787. };
  3788. /**
  3789. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3790. * @param axis1 defines the first axis
  3791. * @param axis2 defines the second axis
  3792. * @param axis3 defines the third axis
  3793. * @param ref defines the Vector3 where to store the result
  3794. */
  3795. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3796. var quat = MathTmp.Quaternion[0];
  3797. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3798. quat.toEulerAnglesToRef(ref);
  3799. };
  3800. return Vector3;
  3801. }());
  3802. BABYLON.Vector3 = Vector3;
  3803. //Vector4 class created for EulerAngle class conversion to Quaternion
  3804. var Vector4 = /** @class */ (function () {
  3805. /**
  3806. * Creates a Vector4 object from the given floats.
  3807. */
  3808. function Vector4(x, y, z, w) {
  3809. this.x = x;
  3810. this.y = y;
  3811. this.z = z;
  3812. this.w = w;
  3813. }
  3814. /**
  3815. * Returns the string with the Vector4 coordinates.
  3816. */
  3817. Vector4.prototype.toString = function () {
  3818. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3819. };
  3820. /**
  3821. * Returns the string "Vector4".
  3822. */
  3823. Vector4.prototype.getClassName = function () {
  3824. return "Vector4";
  3825. };
  3826. /**
  3827. * Returns the Vector4 hash code.
  3828. */
  3829. Vector4.prototype.getHashCode = function () {
  3830. var hash = this.x || 0;
  3831. hash = (hash * 397) ^ (this.y || 0);
  3832. hash = (hash * 397) ^ (this.z || 0);
  3833. hash = (hash * 397) ^ (this.w || 0);
  3834. return hash;
  3835. };
  3836. // Operators
  3837. /**
  3838. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3839. */
  3840. Vector4.prototype.asArray = function () {
  3841. var result = new Array();
  3842. this.toArray(result, 0);
  3843. return result;
  3844. };
  3845. /**
  3846. * Populates the given array from the given index with the Vector4 coordinates.
  3847. * Returns the Vector4.
  3848. */
  3849. Vector4.prototype.toArray = function (array, index) {
  3850. if (index === undefined) {
  3851. index = 0;
  3852. }
  3853. array[index] = this.x;
  3854. array[index + 1] = this.y;
  3855. array[index + 2] = this.z;
  3856. array[index + 3] = this.w;
  3857. return this;
  3858. };
  3859. /**
  3860. * Adds the given vector to the current Vector4.
  3861. * Returns the updated Vector4.
  3862. */
  3863. Vector4.prototype.addInPlace = function (otherVector) {
  3864. this.x += otherVector.x;
  3865. this.y += otherVector.y;
  3866. this.z += otherVector.z;
  3867. this.w += otherVector.w;
  3868. return this;
  3869. };
  3870. /**
  3871. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3872. */
  3873. Vector4.prototype.add = function (otherVector) {
  3874. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3875. };
  3876. /**
  3877. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3878. * Returns the current Vector4.
  3879. */
  3880. Vector4.prototype.addToRef = function (otherVector, result) {
  3881. result.x = this.x + otherVector.x;
  3882. result.y = this.y + otherVector.y;
  3883. result.z = this.z + otherVector.z;
  3884. result.w = this.w + otherVector.w;
  3885. return this;
  3886. };
  3887. /**
  3888. * Subtract in place the given vector from the current Vector4.
  3889. * Returns the updated Vector4.
  3890. */
  3891. Vector4.prototype.subtractInPlace = function (otherVector) {
  3892. this.x -= otherVector.x;
  3893. this.y -= otherVector.y;
  3894. this.z -= otherVector.z;
  3895. this.w -= otherVector.w;
  3896. return this;
  3897. };
  3898. /**
  3899. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3900. */
  3901. Vector4.prototype.subtract = function (otherVector) {
  3902. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3903. };
  3904. /**
  3905. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3906. * Returns the current Vector4.
  3907. */
  3908. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3909. result.x = this.x - otherVector.x;
  3910. result.y = this.y - otherVector.y;
  3911. result.z = this.z - otherVector.z;
  3912. result.w = this.w - otherVector.w;
  3913. return this;
  3914. };
  3915. /**
  3916. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3917. */
  3918. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3919. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3920. };
  3921. /**
  3922. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3923. * Returns the current Vector4.
  3924. */
  3925. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3926. result.x = this.x - x;
  3927. result.y = this.y - y;
  3928. result.z = this.z - z;
  3929. result.w = this.w - w;
  3930. return this;
  3931. };
  3932. /**
  3933. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3934. */
  3935. Vector4.prototype.negate = function () {
  3936. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3937. };
  3938. /**
  3939. * Multiplies the current Vector4 coordinates by scale (float).
  3940. * Returns the updated Vector4.
  3941. */
  3942. Vector4.prototype.scaleInPlace = function (scale) {
  3943. this.x *= scale;
  3944. this.y *= scale;
  3945. this.z *= scale;
  3946. this.w *= scale;
  3947. return this;
  3948. };
  3949. /**
  3950. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3951. */
  3952. Vector4.prototype.scale = function (scale) {
  3953. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3954. };
  3955. /**
  3956. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3957. * Returns the current Vector4.
  3958. */
  3959. Vector4.prototype.scaleToRef = function (scale, result) {
  3960. result.x = this.x * scale;
  3961. result.y = this.y * scale;
  3962. result.z = this.z * scale;
  3963. result.w = this.w * scale;
  3964. return this;
  3965. };
  3966. /**
  3967. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3968. * @param scale defines the scale factor
  3969. * @param result defines the Vector4 object where to store the result
  3970. * @returns the unmodified current Vector4
  3971. */
  3972. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3973. result.x += this.x * scale;
  3974. result.y += this.y * scale;
  3975. result.z += this.z * scale;
  3976. result.w += this.w * scale;
  3977. return this;
  3978. };
  3979. /**
  3980. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3981. */
  3982. Vector4.prototype.equals = function (otherVector) {
  3983. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3984. };
  3985. /**
  3986. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3987. */
  3988. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3989. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3990. return otherVector
  3991. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3992. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3993. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3994. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3995. };
  3996. /**
  3997. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3998. */
  3999. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4000. return this.x === x && this.y === y && this.z === z && this.w === w;
  4001. };
  4002. /**
  4003. * Multiplies in place the current Vector4 by the given one.
  4004. * Returns the updated Vector4.
  4005. */
  4006. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4007. this.x *= otherVector.x;
  4008. this.y *= otherVector.y;
  4009. this.z *= otherVector.z;
  4010. this.w *= otherVector.w;
  4011. return this;
  4012. };
  4013. /**
  4014. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4015. */
  4016. Vector4.prototype.multiply = function (otherVector) {
  4017. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4018. };
  4019. /**
  4020. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4021. * Returns the current Vector4.
  4022. */
  4023. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4024. result.x = this.x * otherVector.x;
  4025. result.y = this.y * otherVector.y;
  4026. result.z = this.z * otherVector.z;
  4027. result.w = this.w * otherVector.w;
  4028. return this;
  4029. };
  4030. /**
  4031. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4032. */
  4033. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4034. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4035. };
  4036. /**
  4037. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4038. */
  4039. Vector4.prototype.divide = function (otherVector) {
  4040. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4041. };
  4042. /**
  4043. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4044. * Returns the current Vector4.
  4045. */
  4046. Vector4.prototype.divideToRef = function (otherVector, result) {
  4047. result.x = this.x / otherVector.x;
  4048. result.y = this.y / otherVector.y;
  4049. result.z = this.z / otherVector.z;
  4050. result.w = this.w / otherVector.w;
  4051. return this;
  4052. };
  4053. /**
  4054. * Divides the current Vector3 coordinates by the given ones.
  4055. * @returns the updated Vector3.
  4056. */
  4057. Vector4.prototype.divideInPlace = function (otherVector) {
  4058. return this.divideToRef(otherVector, this);
  4059. };
  4060. /**
  4061. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4062. * @param other defines the second operand
  4063. * @returns the current updated Vector4
  4064. */
  4065. Vector4.prototype.minimizeInPlace = function (other) {
  4066. if (other.x < this.x)
  4067. this.x = other.x;
  4068. if (other.y < this.y)
  4069. this.y = other.y;
  4070. if (other.z < this.z)
  4071. this.z = other.z;
  4072. if (other.w < this.w)
  4073. this.w = other.w;
  4074. return this;
  4075. };
  4076. /**
  4077. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4078. * @param other defines the second operand
  4079. * @returns the current updated Vector4
  4080. */
  4081. Vector4.prototype.maximizeInPlace = function (other) {
  4082. if (other.x > this.x)
  4083. this.x = other.x;
  4084. if (other.y > this.y)
  4085. this.y = other.y;
  4086. if (other.z > this.z)
  4087. this.z = other.z;
  4088. if (other.w > this.w)
  4089. this.w = other.w;
  4090. return this;
  4091. };
  4092. /**
  4093. * Gets a new Vector4 from current Vector4 floored values
  4094. * @returns a new Vector4
  4095. */
  4096. Vector4.prototype.floor = function () {
  4097. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4098. };
  4099. /**
  4100. * Gets a new Vector4 from current Vector3 floored values
  4101. * @returns a new Vector4
  4102. */
  4103. Vector4.prototype.fract = function () {
  4104. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4105. };
  4106. // Properties
  4107. /**
  4108. * Returns the Vector4 length (float).
  4109. */
  4110. Vector4.prototype.length = function () {
  4111. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4112. };
  4113. /**
  4114. * Returns the Vector4 squared length (float).
  4115. */
  4116. Vector4.prototype.lengthSquared = function () {
  4117. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4118. };
  4119. // Methods
  4120. /**
  4121. * Normalizes in place the Vector4.
  4122. * Returns the updated Vector4.
  4123. */
  4124. Vector4.prototype.normalize = function () {
  4125. var len = this.length();
  4126. if (len === 0)
  4127. return this;
  4128. var num = 1.0 / len;
  4129. this.x *= num;
  4130. this.y *= num;
  4131. this.z *= num;
  4132. this.w *= num;
  4133. return this;
  4134. };
  4135. /**
  4136. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4137. */
  4138. Vector4.prototype.toVector3 = function () {
  4139. return new Vector3(this.x, this.y, this.z);
  4140. };
  4141. /**
  4142. * Returns a new Vector4 copied from the current one.
  4143. */
  4144. Vector4.prototype.clone = function () {
  4145. return new Vector4(this.x, this.y, this.z, this.w);
  4146. };
  4147. /**
  4148. * Updates the current Vector4 with the given one coordinates.
  4149. * Returns the updated Vector4.
  4150. */
  4151. Vector4.prototype.copyFrom = function (source) {
  4152. this.x = source.x;
  4153. this.y = source.y;
  4154. this.z = source.z;
  4155. this.w = source.w;
  4156. return this;
  4157. };
  4158. /**
  4159. * Updates the current Vector4 coordinates with the given floats.
  4160. * Returns the updated Vector4.
  4161. */
  4162. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4163. this.x = x;
  4164. this.y = y;
  4165. this.z = z;
  4166. this.w = w;
  4167. return this;
  4168. };
  4169. /**
  4170. * Updates the current Vector4 coordinates with the given floats.
  4171. * Returns the updated Vector4.
  4172. */
  4173. Vector4.prototype.set = function (x, y, z, w) {
  4174. return this.copyFromFloats(x, y, z, w);
  4175. };
  4176. // Statics
  4177. /**
  4178. * Returns a new Vector4 set from the starting index of the given array.
  4179. */
  4180. Vector4.FromArray = function (array, offset) {
  4181. if (!offset) {
  4182. offset = 0;
  4183. }
  4184. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4185. };
  4186. /**
  4187. * Updates the given vector "result" from the starting index of the given array.
  4188. */
  4189. Vector4.FromArrayToRef = function (array, offset, result) {
  4190. result.x = array[offset];
  4191. result.y = array[offset + 1];
  4192. result.z = array[offset + 2];
  4193. result.w = array[offset + 3];
  4194. };
  4195. /**
  4196. * Updates the given vector "result" from the starting index of the given Float32Array.
  4197. */
  4198. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4199. Vector4.FromArrayToRef(array, offset, result);
  4200. };
  4201. /**
  4202. * Updates the given vector "result" coordinates from the given floats.
  4203. */
  4204. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4205. result.x = x;
  4206. result.y = y;
  4207. result.z = z;
  4208. result.w = w;
  4209. };
  4210. /**
  4211. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4212. */
  4213. Vector4.Zero = function () {
  4214. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4215. };
  4216. /**
  4217. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4218. */
  4219. Vector4.One = function () {
  4220. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4221. };
  4222. /**
  4223. * Returns a new normalized Vector4 from the given one.
  4224. */
  4225. Vector4.Normalize = function (vector) {
  4226. var result = Vector4.Zero();
  4227. Vector4.NormalizeToRef(vector, result);
  4228. return result;
  4229. };
  4230. /**
  4231. * Updates the given vector "result" from the normalization of the given one.
  4232. */
  4233. Vector4.NormalizeToRef = function (vector, result) {
  4234. result.copyFrom(vector);
  4235. result.normalize();
  4236. };
  4237. Vector4.Minimize = function (left, right) {
  4238. var min = left.clone();
  4239. min.minimizeInPlace(right);
  4240. return min;
  4241. };
  4242. Vector4.Maximize = function (left, right) {
  4243. var max = left.clone();
  4244. max.maximizeInPlace(right);
  4245. return max;
  4246. };
  4247. /**
  4248. * Returns the distance (float) between the vectors "value1" and "value2".
  4249. */
  4250. Vector4.Distance = function (value1, value2) {
  4251. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4252. };
  4253. /**
  4254. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4255. */
  4256. Vector4.DistanceSquared = function (value1, value2) {
  4257. var x = value1.x - value2.x;
  4258. var y = value1.y - value2.y;
  4259. var z = value1.z - value2.z;
  4260. var w = value1.w - value2.w;
  4261. return (x * x) + (y * y) + (z * z) + (w * w);
  4262. };
  4263. /**
  4264. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4265. */
  4266. Vector4.Center = function (value1, value2) {
  4267. var center = value1.add(value2);
  4268. center.scaleInPlace(0.5);
  4269. return center;
  4270. };
  4271. /**
  4272. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4273. * This methods computes transformed normalized direction vectors only.
  4274. */
  4275. Vector4.TransformNormal = function (vector, transformation) {
  4276. var result = Vector4.Zero();
  4277. Vector4.TransformNormalToRef(vector, transformation, result);
  4278. return result;
  4279. };
  4280. /**
  4281. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4282. * This methods computes transformed normalized direction vectors only.
  4283. */
  4284. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4285. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4286. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4287. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4288. result.x = x;
  4289. result.y = y;
  4290. result.z = z;
  4291. result.w = vector.w;
  4292. };
  4293. /**
  4294. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4295. * This methods computes transformed normalized direction vectors only.
  4296. */
  4297. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4298. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4299. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4300. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4301. result.w = w;
  4302. };
  4303. return Vector4;
  4304. }());
  4305. BABYLON.Vector4 = Vector4;
  4306. var Size = /** @class */ (function () {
  4307. /**
  4308. * Creates a Size object from the given width and height (floats).
  4309. */
  4310. function Size(width, height) {
  4311. this.width = width;
  4312. this.height = height;
  4313. }
  4314. // Returns a string with the Size width and height.
  4315. Size.prototype.toString = function () {
  4316. return "{W: " + this.width + ", H: " + this.height + "}";
  4317. };
  4318. /**
  4319. * Returns the string "Size"
  4320. */
  4321. Size.prototype.getClassName = function () {
  4322. return "Size";
  4323. };
  4324. /**
  4325. * Returns the Size hash code.
  4326. */
  4327. Size.prototype.getHashCode = function () {
  4328. var hash = this.width || 0;
  4329. hash = (hash * 397) ^ (this.height || 0);
  4330. return hash;
  4331. };
  4332. /**
  4333. * Updates the current size from the given one.
  4334. * Returns the updated Size.
  4335. */
  4336. Size.prototype.copyFrom = function (src) {
  4337. this.width = src.width;
  4338. this.height = src.height;
  4339. };
  4340. /**
  4341. * Updates in place the current Size from the given floats.
  4342. * Returns the updated Size.
  4343. */
  4344. Size.prototype.copyFromFloats = function (width, height) {
  4345. this.width = width;
  4346. this.height = height;
  4347. return this;
  4348. };
  4349. /**
  4350. * Updates in place the current Size from the given floats.
  4351. * Returns the updated Size.
  4352. */
  4353. Size.prototype.set = function (width, height) {
  4354. return this.copyFromFloats(width, height);
  4355. };
  4356. /**
  4357. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4358. */
  4359. Size.prototype.multiplyByFloats = function (w, h) {
  4360. return new Size(this.width * w, this.height * h);
  4361. };
  4362. /**
  4363. * Returns a new Size copied from the given one.
  4364. */
  4365. Size.prototype.clone = function () {
  4366. return new Size(this.width, this.height);
  4367. };
  4368. /**
  4369. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4370. */
  4371. Size.prototype.equals = function (other) {
  4372. if (!other) {
  4373. return false;
  4374. }
  4375. return (this.width === other.width) && (this.height === other.height);
  4376. };
  4377. Object.defineProperty(Size.prototype, "surface", {
  4378. /**
  4379. * Returns the surface of the Size : width * height (float).
  4380. */
  4381. get: function () {
  4382. return this.width * this.height;
  4383. },
  4384. enumerable: true,
  4385. configurable: true
  4386. });
  4387. /**
  4388. * Returns a new Size set to (0.0, 0.0)
  4389. */
  4390. Size.Zero = function () {
  4391. return new Size(0.0, 0.0);
  4392. };
  4393. /**
  4394. * Returns a new Size set as the addition result of the current Size and the given one.
  4395. */
  4396. Size.prototype.add = function (otherSize) {
  4397. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4398. return r;
  4399. };
  4400. /**
  4401. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4402. */
  4403. Size.prototype.subtract = function (otherSize) {
  4404. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4405. return r;
  4406. };
  4407. /**
  4408. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4409. */
  4410. Size.Lerp = function (start, end, amount) {
  4411. var w = start.width + ((end.width - start.width) * amount);
  4412. var h = start.height + ((end.height - start.height) * amount);
  4413. return new Size(w, h);
  4414. };
  4415. return Size;
  4416. }());
  4417. BABYLON.Size = Size;
  4418. /**
  4419. * Class used to store quaternion data
  4420. * @see https://en.wikipedia.org/wiki/Quaternion
  4421. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4422. */
  4423. var Quaternion = /** @class */ (function () {
  4424. /**
  4425. * Creates a new Quaternion from the given floats
  4426. * @param x defines the first component (0 by default)
  4427. * @param y defines the second component (0 by default)
  4428. * @param z defines the third component (0 by default)
  4429. * @param w defines the fourth component (1.0 by default)
  4430. */
  4431. function Quaternion(
  4432. /** defines the first component (0 by default) */
  4433. x,
  4434. /** defines the second component (0 by default) */
  4435. y,
  4436. /** defines the third component (0 by default) */
  4437. z,
  4438. /** defines the fourth component (1.0 by default) */
  4439. w) {
  4440. if (x === void 0) { x = 0.0; }
  4441. if (y === void 0) { y = 0.0; }
  4442. if (z === void 0) { z = 0.0; }
  4443. if (w === void 0) { w = 1.0; }
  4444. this.x = x;
  4445. this.y = y;
  4446. this.z = z;
  4447. this.w = w;
  4448. }
  4449. /**
  4450. * Gets a string representation for the current quaternion
  4451. * @returns a string with the Quaternion coordinates
  4452. */
  4453. Quaternion.prototype.toString = function () {
  4454. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4455. };
  4456. /**
  4457. * Gets the class name of the quaternion
  4458. * @returns the string "Quaternion"
  4459. */
  4460. Quaternion.prototype.getClassName = function () {
  4461. return "Quaternion";
  4462. };
  4463. /**
  4464. * Gets a hash code for this quaternion
  4465. * @returns the quaternion hash code
  4466. */
  4467. Quaternion.prototype.getHashCode = function () {
  4468. var hash = this.x || 0;
  4469. hash = (hash * 397) ^ (this.y || 0);
  4470. hash = (hash * 397) ^ (this.z || 0);
  4471. hash = (hash * 397) ^ (this.w || 0);
  4472. return hash;
  4473. };
  4474. /**
  4475. * Copy the quaternion to an array
  4476. * @returns a new array populated with 4 elements from the quaternion coordinates
  4477. */
  4478. Quaternion.prototype.asArray = function () {
  4479. return [this.x, this.y, this.z, this.w];
  4480. };
  4481. /**
  4482. * Check if two quaternions are equals
  4483. * @param otherQuaternion defines the second operand
  4484. * @return true if the current quaternion and the given one coordinates are strictly equals
  4485. */
  4486. Quaternion.prototype.equals = function (otherQuaternion) {
  4487. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4488. };
  4489. /**
  4490. * Clone the current quaternion
  4491. * @returns a new quaternion copied from the current one
  4492. */
  4493. Quaternion.prototype.clone = function () {
  4494. return new Quaternion(this.x, this.y, this.z, this.w);
  4495. };
  4496. /**
  4497. * Copy a quaternion to the current one
  4498. * @param other defines the other quaternion
  4499. * @returns the updated current quaternion
  4500. */
  4501. Quaternion.prototype.copyFrom = function (other) {
  4502. this.x = other.x;
  4503. this.y = other.y;
  4504. this.z = other.z;
  4505. this.w = other.w;
  4506. return this;
  4507. };
  4508. /**
  4509. * Updates the current quaternion with the given float coordinates
  4510. * @param x defines the x coordinate
  4511. * @param y defines the y coordinate
  4512. * @param z defines the z coordinate
  4513. * @param w defines the w coordinate
  4514. * @returns the updated current quaternion
  4515. */
  4516. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4517. this.x = x;
  4518. this.y = y;
  4519. this.z = z;
  4520. this.w = w;
  4521. return this;
  4522. };
  4523. /**
  4524. * Updates the current quaternion from the given float coordinates
  4525. * @param x defines the x coordinate
  4526. * @param y defines the y coordinate
  4527. * @param z defines the z coordinate
  4528. * @param w defines the w coordinate
  4529. * @returns the updated current quaternion
  4530. */
  4531. Quaternion.prototype.set = function (x, y, z, w) {
  4532. return this.copyFromFloats(x, y, z, w);
  4533. };
  4534. /**
  4535. * Adds two quaternions
  4536. * @param other defines the second operand
  4537. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4538. */
  4539. Quaternion.prototype.add = function (other) {
  4540. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4541. };
  4542. /**
  4543. * Add a quaternion to the current one
  4544. * @param other defines the quaternion to add
  4545. * @returns the current quaternion
  4546. */
  4547. Quaternion.prototype.addInPlace = function (other) {
  4548. this.x += other.x;
  4549. this.y += other.y;
  4550. this.z += other.z;
  4551. this.w += other.w;
  4552. return this;
  4553. };
  4554. /**
  4555. * Subtract two quaternions
  4556. * @param other defines the second operand
  4557. * @returns a new quaternion as the subtraction result of the given one from the current one
  4558. */
  4559. Quaternion.prototype.subtract = function (other) {
  4560. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4561. };
  4562. /**
  4563. * Multiplies the current quaternion by a scale factor
  4564. * @param value defines the scale factor
  4565. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4566. */
  4567. Quaternion.prototype.scale = function (value) {
  4568. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4569. };
  4570. /**
  4571. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4572. * @param scale defines the scale factor
  4573. * @param result defines the Quaternion object where to store the result
  4574. * @returns the unmodified current quaternion
  4575. */
  4576. Quaternion.prototype.scaleToRef = function (scale, result) {
  4577. result.x = this.x * scale;
  4578. result.y = this.y * scale;
  4579. result.z = this.z * scale;
  4580. result.w = this.w * scale;
  4581. return this;
  4582. };
  4583. /**
  4584. * Multiplies in place the current quaternion by a scale factor
  4585. * @param value defines the scale factor
  4586. * @returns the current modified quaternion
  4587. */
  4588. Quaternion.prototype.scaleInPlace = function (value) {
  4589. this.x *= value;
  4590. this.y *= value;
  4591. this.z *= value;
  4592. this.w *= value;
  4593. return this;
  4594. };
  4595. /**
  4596. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4597. * @param scale defines the scale factor
  4598. * @param result defines the Quaternion object where to store the result
  4599. * @returns the unmodified current quaternion
  4600. */
  4601. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4602. result.x += this.x * scale;
  4603. result.y += this.y * scale;
  4604. result.z += this.z * scale;
  4605. result.w += this.w * scale;
  4606. return this;
  4607. };
  4608. /**
  4609. * Multiplies two quaternions
  4610. * @param q1 defines the second operand
  4611. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4612. */
  4613. Quaternion.prototype.multiply = function (q1) {
  4614. var result = new Quaternion(0, 0, 0, 1.0);
  4615. this.multiplyToRef(q1, result);
  4616. return result;
  4617. };
  4618. /**
  4619. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4620. * @param q1 defines the second operand
  4621. * @param result defines the target quaternion
  4622. * @returns the current quaternion
  4623. */
  4624. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4625. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4626. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4627. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4628. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4629. result.copyFromFloats(x, y, z, w);
  4630. return this;
  4631. };
  4632. /**
  4633. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4634. * @param q1 defines the second operand
  4635. * @returns the currentupdated quaternion
  4636. */
  4637. Quaternion.prototype.multiplyInPlace = function (q1) {
  4638. this.multiplyToRef(q1, this);
  4639. return this;
  4640. };
  4641. /**
  4642. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4643. * @param ref defines the target quaternion
  4644. * @returns the current quaternion
  4645. */
  4646. Quaternion.prototype.conjugateToRef = function (ref) {
  4647. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4648. return this;
  4649. };
  4650. /**
  4651. * Conjugates in place (1-q) the current quaternion
  4652. * @returns the current updated quaternion
  4653. */
  4654. Quaternion.prototype.conjugateInPlace = function () {
  4655. this.x *= -1;
  4656. this.y *= -1;
  4657. this.z *= -1;
  4658. return this;
  4659. };
  4660. /**
  4661. * Conjugates in place (1-q) the current quaternion
  4662. * @returns a new quaternion
  4663. */
  4664. Quaternion.prototype.conjugate = function () {
  4665. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4666. return result;
  4667. };
  4668. /**
  4669. * Gets length of current quaternion
  4670. * @returns the quaternion length (float)
  4671. */
  4672. Quaternion.prototype.length = function () {
  4673. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4674. };
  4675. /**
  4676. * Normalize in place the current quaternion
  4677. * @returns the current updated quaternion
  4678. */
  4679. Quaternion.prototype.normalize = function () {
  4680. var length = 1.0 / this.length();
  4681. this.x *= length;
  4682. this.y *= length;
  4683. this.z *= length;
  4684. this.w *= length;
  4685. return this;
  4686. };
  4687. /**
  4688. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4689. * @param order is a reserved parameter and is ignore for now
  4690. * @returns a new Vector3 containing the Euler angles
  4691. */
  4692. Quaternion.prototype.toEulerAngles = function (order) {
  4693. if (order === void 0) { order = "YZX"; }
  4694. var result = Vector3.Zero();
  4695. this.toEulerAnglesToRef(result, order);
  4696. return result;
  4697. };
  4698. /**
  4699. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4700. * @param result defines the vector which will be filled with the Euler angles
  4701. * @param order is a reserved parameter and is ignore for now
  4702. * @returns the current unchanged quaternion
  4703. */
  4704. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4705. if (order === void 0) { order = "YZX"; }
  4706. var qz = this.z;
  4707. var qx = this.x;
  4708. var qy = this.y;
  4709. var qw = this.w;
  4710. var sqw = qw * qw;
  4711. var sqz = qz * qz;
  4712. var sqx = qx * qx;
  4713. var sqy = qy * qy;
  4714. var zAxisY = qy * qz - qx * qw;
  4715. var limit = .4999999;
  4716. if (zAxisY < -limit) {
  4717. result.y = 2 * Math.atan2(qy, qw);
  4718. result.x = Math.PI / 2;
  4719. result.z = 0;
  4720. }
  4721. else if (zAxisY > limit) {
  4722. result.y = 2 * Math.atan2(qy, qw);
  4723. result.x = -Math.PI / 2;
  4724. result.z = 0;
  4725. }
  4726. else {
  4727. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4728. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4729. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4730. }
  4731. return this;
  4732. };
  4733. /**
  4734. * Updates the given rotation matrix with the current quaternion values
  4735. * @param result defines the target matrix
  4736. * @returns the current unchanged quaternion
  4737. */
  4738. Quaternion.prototype.toRotationMatrix = function (result) {
  4739. var xx = this.x * this.x;
  4740. var yy = this.y * this.y;
  4741. var zz = this.z * this.z;
  4742. var xy = this.x * this.y;
  4743. var zw = this.z * this.w;
  4744. var zx = this.z * this.x;
  4745. var yw = this.y * this.w;
  4746. var yz = this.y * this.z;
  4747. var xw = this.x * this.w;
  4748. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4749. result.m[1] = 2.0 * (xy + zw);
  4750. result.m[2] = 2.0 * (zx - yw);
  4751. result.m[3] = 0;
  4752. result.m[4] = 2.0 * (xy - zw);
  4753. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4754. result.m[6] = 2.0 * (yz + xw);
  4755. result.m[7] = 0;
  4756. result.m[8] = 2.0 * (zx + yw);
  4757. result.m[9] = 2.0 * (yz - xw);
  4758. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4759. result.m[11] = 0;
  4760. result.m[12] = 0;
  4761. result.m[13] = 0;
  4762. result.m[14] = 0;
  4763. result.m[15] = 1.0;
  4764. result._markAsUpdated();
  4765. return this;
  4766. };
  4767. /**
  4768. * Updates the current quaternion from the given rotation matrix values
  4769. * @param matrix defines the source matrix
  4770. * @returns the current updated quaternion
  4771. */
  4772. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4773. Quaternion.FromRotationMatrixToRef(matrix, this);
  4774. return this;
  4775. };
  4776. // Statics
  4777. /**
  4778. * Creates a new quaternion from a rotation matrix
  4779. * @param matrix defines the source matrix
  4780. * @returns a new quaternion created from the given rotation matrix values
  4781. */
  4782. Quaternion.FromRotationMatrix = function (matrix) {
  4783. var result = new Quaternion();
  4784. Quaternion.FromRotationMatrixToRef(matrix, result);
  4785. return result;
  4786. };
  4787. /**
  4788. * Updates the given quaternion with the given rotation matrix values
  4789. * @param matrix defines the source matrix
  4790. * @param result defines the target quaternion
  4791. */
  4792. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4793. var data = matrix.m;
  4794. var m11 = data[0], m12 = data[4], m13 = data[8];
  4795. var m21 = data[1], m22 = data[5], m23 = data[9];
  4796. var m31 = data[2], m32 = data[6], m33 = data[10];
  4797. var trace = m11 + m22 + m33;
  4798. var s;
  4799. if (trace > 0) {
  4800. s = 0.5 / Math.sqrt(trace + 1.0);
  4801. result.w = 0.25 / s;
  4802. result.x = (m32 - m23) * s;
  4803. result.y = (m13 - m31) * s;
  4804. result.z = (m21 - m12) * s;
  4805. }
  4806. else if (m11 > m22 && m11 > m33) {
  4807. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4808. result.w = (m32 - m23) / s;
  4809. result.x = 0.25 * s;
  4810. result.y = (m12 + m21) / s;
  4811. result.z = (m13 + m31) / s;
  4812. }
  4813. else if (m22 > m33) {
  4814. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4815. result.w = (m13 - m31) / s;
  4816. result.x = (m12 + m21) / s;
  4817. result.y = 0.25 * s;
  4818. result.z = (m23 + m32) / s;
  4819. }
  4820. else {
  4821. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4822. result.w = (m21 - m12) / s;
  4823. result.x = (m13 + m31) / s;
  4824. result.y = (m23 + m32) / s;
  4825. result.z = 0.25 * s;
  4826. }
  4827. };
  4828. /**
  4829. * Returns the dot product (float) between the quaternions "left" and "right"
  4830. * @param left defines the left operand
  4831. * @param right defines the right operand
  4832. * @returns the dot product
  4833. */
  4834. Quaternion.Dot = function (left, right) {
  4835. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4836. };
  4837. /**
  4838. * Checks if the two quaternions are close to each other
  4839. * @param quat0 defines the first quaternion to check
  4840. * @param quat1 defines the second quaternion to check
  4841. * @returns true if the two quaternions are close to each other
  4842. */
  4843. Quaternion.AreClose = function (quat0, quat1) {
  4844. var dot = Quaternion.Dot(quat0, quat1);
  4845. return dot >= 0;
  4846. };
  4847. /**
  4848. * Creates an empty quaternion
  4849. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4850. */
  4851. Quaternion.Zero = function () {
  4852. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4853. };
  4854. /**
  4855. * Inverse a given quaternion
  4856. * @param q defines the source quaternion
  4857. * @returns a new quaternion as the inverted current quaternion
  4858. */
  4859. Quaternion.Inverse = function (q) {
  4860. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4861. };
  4862. /**
  4863. * Creates an identity quaternion
  4864. * @returns the identity quaternion
  4865. */
  4866. Quaternion.Identity = function () {
  4867. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4868. };
  4869. /**
  4870. * Gets a boolean indicating if the given quaternion is identity
  4871. * @param quaternion defines the quaternion to check
  4872. * @returns true if the quaternion is identity
  4873. */
  4874. Quaternion.IsIdentity = function (quaternion) {
  4875. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4876. };
  4877. /**
  4878. * Creates a quaternion from a rotation around an axis
  4879. * @param axis defines the axis to use
  4880. * @param angle defines the angle to use
  4881. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4882. */
  4883. Quaternion.RotationAxis = function (axis, angle) {
  4884. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4885. };
  4886. /**
  4887. * Creates a rotation around an axis and stores it into the given quaternion
  4888. * @param axis defines the axis to use
  4889. * @param angle defines the angle to use
  4890. * @param result defines the target quaternion
  4891. * @returns the target quaternion
  4892. */
  4893. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4894. var sin = Math.sin(angle / 2);
  4895. axis.normalize();
  4896. result.w = Math.cos(angle / 2);
  4897. result.x = axis.x * sin;
  4898. result.y = axis.y * sin;
  4899. result.z = axis.z * sin;
  4900. return result;
  4901. };
  4902. /**
  4903. * Creates a new quaternion from data stored into an array
  4904. * @param array defines the data source
  4905. * @param offset defines the offset in the source array where the data starts
  4906. * @returns a new quaternion
  4907. */
  4908. Quaternion.FromArray = function (array, offset) {
  4909. if (!offset) {
  4910. offset = 0;
  4911. }
  4912. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4913. };
  4914. /**
  4915. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4916. * @param yaw defines the rotation around Y axis
  4917. * @param pitch defines the rotation around X axis
  4918. * @param roll defines the rotation around Z axis
  4919. * @returns the new quaternion
  4920. */
  4921. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4922. var q = new Quaternion();
  4923. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4924. return q;
  4925. };
  4926. /**
  4927. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4928. * @param yaw defines the rotation around Y axis
  4929. * @param pitch defines the rotation around X axis
  4930. * @param roll defines the rotation around Z axis
  4931. * @param result defines the target quaternion
  4932. */
  4933. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4934. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4935. var halfRoll = roll * 0.5;
  4936. var halfPitch = pitch * 0.5;
  4937. var halfYaw = yaw * 0.5;
  4938. var sinRoll = Math.sin(halfRoll);
  4939. var cosRoll = Math.cos(halfRoll);
  4940. var sinPitch = Math.sin(halfPitch);
  4941. var cosPitch = Math.cos(halfPitch);
  4942. var sinYaw = Math.sin(halfYaw);
  4943. var cosYaw = Math.cos(halfYaw);
  4944. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4945. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4946. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4947. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4948. };
  4949. /**
  4950. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4951. * @param alpha defines the rotation around first axis
  4952. * @param beta defines the rotation around second axis
  4953. * @param gamma defines the rotation around third axis
  4954. * @returns the new quaternion
  4955. */
  4956. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4957. var result = new Quaternion();
  4958. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4959. return result;
  4960. };
  4961. /**
  4962. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4963. * @param alpha defines the rotation around first axis
  4964. * @param beta defines the rotation around second axis
  4965. * @param gamma defines the rotation around third axis
  4966. * @param result defines the target quaternion
  4967. */
  4968. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4969. // Produces a quaternion from Euler angles in the z-x-z orientation
  4970. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4971. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4972. var halfBeta = beta * 0.5;
  4973. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4974. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4975. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4976. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4977. };
  4978. /**
  4979. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4980. * @param axis1 defines the first axis
  4981. * @param axis2 defines the second axis
  4982. * @param axis3 defines the third axis
  4983. * @returns the new quaternion
  4984. */
  4985. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4986. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4987. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4988. return quat;
  4989. };
  4990. /**
  4991. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4992. * @param axis1 defines the first axis
  4993. * @param axis2 defines the second axis
  4994. * @param axis3 defines the third axis
  4995. * @param ref defines the target quaternion
  4996. */
  4997. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4998. var rotMat = MathTmp.Matrix[0];
  4999. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5000. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5001. };
  5002. /**
  5003. * Interpolates between two quaternions
  5004. * @param left defines first quaternion
  5005. * @param right defines second quaternion
  5006. * @param amount defines the gradient to use
  5007. * @returns the new interpolated quaternion
  5008. */
  5009. Quaternion.Slerp = function (left, right, amount) {
  5010. var result = Quaternion.Identity();
  5011. Quaternion.SlerpToRef(left, right, amount, result);
  5012. return result;
  5013. };
  5014. /**
  5015. * Interpolates between two quaternions and stores it into a target quaternion
  5016. * @param left defines first quaternion
  5017. * @param right defines second quaternion
  5018. * @param amount defines the gradient to use
  5019. * @param result defines the target quaternion
  5020. */
  5021. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5022. var num2;
  5023. var num3;
  5024. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5025. var flag = false;
  5026. if (num4 < 0) {
  5027. flag = true;
  5028. num4 = -num4;
  5029. }
  5030. if (num4 > 0.999999) {
  5031. num3 = 1 - amount;
  5032. num2 = flag ? -amount : amount;
  5033. }
  5034. else {
  5035. var num5 = Math.acos(num4);
  5036. var num6 = (1.0 / Math.sin(num5));
  5037. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5038. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5039. }
  5040. result.x = (num3 * left.x) + (num2 * right.x);
  5041. result.y = (num3 * left.y) + (num2 * right.y);
  5042. result.z = (num3 * left.z) + (num2 * right.z);
  5043. result.w = (num3 * left.w) + (num2 * right.w);
  5044. };
  5045. /**
  5046. * Interpolate between two quaternions using Hermite interpolation
  5047. * @param value1 defines first quaternion
  5048. * @param tangent1 defines the incoming tangent
  5049. * @param value2 defines second quaternion
  5050. * @param tangent2 defines the outgoing tangent
  5051. * @param amount defines the target quaternion
  5052. * @returns the new interpolated quaternion
  5053. */
  5054. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5055. var squared = amount * amount;
  5056. var cubed = amount * squared;
  5057. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5058. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5059. var part3 = (cubed - (2.0 * squared)) + amount;
  5060. var part4 = cubed - squared;
  5061. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5062. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5063. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5064. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5065. return new Quaternion(x, y, z, w);
  5066. };
  5067. return Quaternion;
  5068. }());
  5069. BABYLON.Quaternion = Quaternion;
  5070. /**
  5071. * Class used to store matrix data (4x4)
  5072. */
  5073. var Matrix = /** @class */ (function () {
  5074. /**
  5075. * Creates an empty matrix (filled with zeros)
  5076. */
  5077. function Matrix() {
  5078. this._isIdentity = false;
  5079. this._isIdentityDirty = true;
  5080. /**
  5081. * Gets or sets the internal data of the matrix
  5082. */
  5083. this.m = new Float32Array(16);
  5084. this._markAsUpdated();
  5085. }
  5086. /** @hidden */
  5087. Matrix.prototype._markAsUpdated = function () {
  5088. this.updateFlag = Matrix._updateFlagSeed++;
  5089. this._isIdentityDirty = true;
  5090. };
  5091. // Properties
  5092. /**
  5093. * Check if the current matrix is indentity
  5094. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5095. * @returns true is the matrix is the identity matrix
  5096. */
  5097. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5098. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5099. if (this._isIdentityDirty) {
  5100. this._isIdentityDirty = false;
  5101. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5102. this._isIdentity = false;
  5103. }
  5104. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5105. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5106. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5107. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5108. this._isIdentity = false;
  5109. }
  5110. else {
  5111. this._isIdentity = true;
  5112. }
  5113. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5114. this._isIdentity = false;
  5115. }
  5116. }
  5117. return this._isIdentity;
  5118. };
  5119. /**
  5120. * Gets the determinant of the matrix
  5121. * @returns the matrix determinant
  5122. */
  5123. Matrix.prototype.determinant = function () {
  5124. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5125. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5126. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5127. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5128. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5129. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5130. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5131. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5132. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5133. };
  5134. // Methods
  5135. /**
  5136. * Returns the matrix as a Float32Array
  5137. * @returns the matrix underlying array
  5138. */
  5139. Matrix.prototype.toArray = function () {
  5140. return this.m;
  5141. };
  5142. /**
  5143. * Returns the matrix as a Float32Array
  5144. * @returns the matrix underlying array.
  5145. */
  5146. Matrix.prototype.asArray = function () {
  5147. return this.toArray();
  5148. };
  5149. /**
  5150. * Inverts the current matrix in place
  5151. * @returns the current inverted matrix
  5152. */
  5153. Matrix.prototype.invert = function () {
  5154. this.invertToRef(this);
  5155. return this;
  5156. };
  5157. /**
  5158. * Sets all the matrix elements to zero
  5159. * @returns the current matrix
  5160. */
  5161. Matrix.prototype.reset = function () {
  5162. for (var index = 0; index < 16; index++) {
  5163. this.m[index] = 0.0;
  5164. }
  5165. this._markAsUpdated();
  5166. return this;
  5167. };
  5168. /**
  5169. * Adds the current matrix with a second one
  5170. * @param other defines the matrix to add
  5171. * @returns a new matrix as the addition of the current matrix and the given one
  5172. */
  5173. Matrix.prototype.add = function (other) {
  5174. var result = new Matrix();
  5175. this.addToRef(other, result);
  5176. return result;
  5177. };
  5178. /**
  5179. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5180. * @param other defines the matrix to add
  5181. * @param result defines the target matrix
  5182. * @returns the current matrix
  5183. */
  5184. Matrix.prototype.addToRef = function (other, result) {
  5185. for (var index = 0; index < 16; index++) {
  5186. result.m[index] = this.m[index] + other.m[index];
  5187. }
  5188. result._markAsUpdated();
  5189. return this;
  5190. };
  5191. /**
  5192. * Adds in place the given matrix to the current matrix
  5193. * @param other defines the second operand
  5194. * @returns the current updated matrix
  5195. */
  5196. Matrix.prototype.addToSelf = function (other) {
  5197. for (var index = 0; index < 16; index++) {
  5198. this.m[index] += other.m[index];
  5199. }
  5200. this._markAsUpdated();
  5201. return this;
  5202. };
  5203. /**
  5204. * Sets the given matrix to the current inverted Matrix
  5205. * @param other defines the target matrix
  5206. * @returns the unmodified current matrix
  5207. */
  5208. Matrix.prototype.invertToRef = function (other) {
  5209. var l1 = this.m[0];
  5210. var l2 = this.m[1];
  5211. var l3 = this.m[2];
  5212. var l4 = this.m[3];
  5213. var l5 = this.m[4];
  5214. var l6 = this.m[5];
  5215. var l7 = this.m[6];
  5216. var l8 = this.m[7];
  5217. var l9 = this.m[8];
  5218. var l10 = this.m[9];
  5219. var l11 = this.m[10];
  5220. var l12 = this.m[11];
  5221. var l13 = this.m[12];
  5222. var l14 = this.m[13];
  5223. var l15 = this.m[14];
  5224. var l16 = this.m[15];
  5225. var l17 = (l11 * l16) - (l12 * l15);
  5226. var l18 = (l10 * l16) - (l12 * l14);
  5227. var l19 = (l10 * l15) - (l11 * l14);
  5228. var l20 = (l9 * l16) - (l12 * l13);
  5229. var l21 = (l9 * l15) - (l11 * l13);
  5230. var l22 = (l9 * l14) - (l10 * l13);
  5231. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5232. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5233. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5234. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5235. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5236. var l28 = (l7 * l16) - (l8 * l15);
  5237. var l29 = (l6 * l16) - (l8 * l14);
  5238. var l30 = (l6 * l15) - (l7 * l14);
  5239. var l31 = (l5 * l16) - (l8 * l13);
  5240. var l32 = (l5 * l15) - (l7 * l13);
  5241. var l33 = (l5 * l14) - (l6 * l13);
  5242. var l34 = (l7 * l12) - (l8 * l11);
  5243. var l35 = (l6 * l12) - (l8 * l10);
  5244. var l36 = (l6 * l11) - (l7 * l10);
  5245. var l37 = (l5 * l12) - (l8 * l9);
  5246. var l38 = (l5 * l11) - (l7 * l9);
  5247. var l39 = (l5 * l10) - (l6 * l9);
  5248. other.m[0] = l23 * l27;
  5249. other.m[4] = l24 * l27;
  5250. other.m[8] = l25 * l27;
  5251. other.m[12] = l26 * l27;
  5252. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5253. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5254. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5255. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5256. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5257. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5258. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5259. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5260. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5261. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5262. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5263. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5264. other._markAsUpdated();
  5265. return this;
  5266. };
  5267. /**
  5268. * Inserts the translation vector (using 3 floats) in the current matrix
  5269. * @param x defines the 1st component of the translation
  5270. * @param y defines the 2nd component of the translation
  5271. * @param z defines the 3rd component of the translation
  5272. * @returns the current updated matrix
  5273. */
  5274. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5275. this.m[12] = x;
  5276. this.m[13] = y;
  5277. this.m[14] = z;
  5278. this._markAsUpdated();
  5279. return this;
  5280. };
  5281. /**
  5282. * Inserts the translation vector in the current matrix
  5283. * @param vector3 defines the translation to insert
  5284. * @returns the current updated matrix
  5285. */
  5286. Matrix.prototype.setTranslation = function (vector3) {
  5287. this.m[12] = vector3.x;
  5288. this.m[13] = vector3.y;
  5289. this.m[14] = vector3.z;
  5290. this._markAsUpdated();
  5291. return this;
  5292. };
  5293. /**
  5294. * Gets the translation value of the current matrix
  5295. * @returns a new Vector3 as the extracted translation from the matrix
  5296. */
  5297. Matrix.prototype.getTranslation = function () {
  5298. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5299. };
  5300. /**
  5301. * Fill a Vector3 with the extracted translation from the matrix
  5302. * @param result defines the Vector3 where to store the translation
  5303. * @returns the current matrix
  5304. */
  5305. Matrix.prototype.getTranslationToRef = function (result) {
  5306. result.x = this.m[12];
  5307. result.y = this.m[13];
  5308. result.z = this.m[14];
  5309. return this;
  5310. };
  5311. /**
  5312. * Remove rotation and scaling part from the matrix
  5313. * @returns the updated matrix
  5314. */
  5315. Matrix.prototype.removeRotationAndScaling = function () {
  5316. this.setRowFromFloats(0, 1, 0, 0, 0);
  5317. this.setRowFromFloats(1, 0, 1, 0, 0);
  5318. this.setRowFromFloats(2, 0, 0, 1, 0);
  5319. return this;
  5320. };
  5321. /**
  5322. * Multiply two matrices
  5323. * @param other defines the second operand
  5324. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5325. */
  5326. Matrix.prototype.multiply = function (other) {
  5327. var result = new Matrix();
  5328. this.multiplyToRef(other, result);
  5329. return result;
  5330. };
  5331. /**
  5332. * Copy the current matrix from the given one
  5333. * @param other defines the source matrix
  5334. * @returns the current updated matrix
  5335. */
  5336. Matrix.prototype.copyFrom = function (other) {
  5337. for (var index = 0; index < 16; index++) {
  5338. this.m[index] = other.m[index];
  5339. }
  5340. this._markAsUpdated();
  5341. return this;
  5342. };
  5343. /**
  5344. * Populates the given array from the starting index with the current matrix values
  5345. * @param array defines the target array
  5346. * @param offset defines the offset in the target array where to start storing values
  5347. * @returns the current matrix
  5348. */
  5349. Matrix.prototype.copyToArray = function (array, offset) {
  5350. if (offset === void 0) { offset = 0; }
  5351. for (var index = 0; index < 16; index++) {
  5352. array[offset + index] = this.m[index];
  5353. }
  5354. return this;
  5355. };
  5356. /**
  5357. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5358. * @param other defines the second operand
  5359. * @param result defines the matrix where to store the multiplication
  5360. * @returns the current matrix
  5361. */
  5362. Matrix.prototype.multiplyToRef = function (other, result) {
  5363. this.multiplyToArray(other, result.m, 0);
  5364. result._markAsUpdated();
  5365. return this;
  5366. };
  5367. /**
  5368. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5369. * @param other defines the second operand
  5370. * @param result defines the array where to store the multiplication
  5371. * @param offset defines the offset in the target array where to start storing values
  5372. * @returns the current matrix
  5373. */
  5374. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5375. var tm0 = this.m[0];
  5376. var tm1 = this.m[1];
  5377. var tm2 = this.m[2];
  5378. var tm3 = this.m[3];
  5379. var tm4 = this.m[4];
  5380. var tm5 = this.m[5];
  5381. var tm6 = this.m[6];
  5382. var tm7 = this.m[7];
  5383. var tm8 = this.m[8];
  5384. var tm9 = this.m[9];
  5385. var tm10 = this.m[10];
  5386. var tm11 = this.m[11];
  5387. var tm12 = this.m[12];
  5388. var tm13 = this.m[13];
  5389. var tm14 = this.m[14];
  5390. var tm15 = this.m[15];
  5391. var om0 = other.m[0];
  5392. var om1 = other.m[1];
  5393. var om2 = other.m[2];
  5394. var om3 = other.m[3];
  5395. var om4 = other.m[4];
  5396. var om5 = other.m[5];
  5397. var om6 = other.m[6];
  5398. var om7 = other.m[7];
  5399. var om8 = other.m[8];
  5400. var om9 = other.m[9];
  5401. var om10 = other.m[10];
  5402. var om11 = other.m[11];
  5403. var om12 = other.m[12];
  5404. var om13 = other.m[13];
  5405. var om14 = other.m[14];
  5406. var om15 = other.m[15];
  5407. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5408. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5409. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5410. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5411. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5412. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5413. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5414. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5415. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5416. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5417. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5418. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5419. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5420. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5421. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5422. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5423. return this;
  5424. };
  5425. /**
  5426. * Check equality between this matrix and a second one
  5427. * @param value defines the second matrix to compare
  5428. * @returns true is the current matrix and the given one values are strictly equal
  5429. */
  5430. Matrix.prototype.equals = function (value) {
  5431. return value &&
  5432. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5433. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5434. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5435. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5436. };
  5437. /**
  5438. * Clone the current matrix
  5439. * @returns a new matrix from the current matrix
  5440. */
  5441. Matrix.prototype.clone = function () {
  5442. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5443. };
  5444. /**
  5445. * Returns the name of the current matrix class
  5446. * @returns the string "Matrix"
  5447. */
  5448. Matrix.prototype.getClassName = function () {
  5449. return "Matrix";
  5450. };
  5451. /**
  5452. * Gets the hash code of the current matrix
  5453. * @returns the hash code
  5454. */
  5455. Matrix.prototype.getHashCode = function () {
  5456. var hash = this.m[0] || 0;
  5457. for (var i = 1; i < 16; i++) {
  5458. hash = (hash * 397) ^ (this.m[i] || 0);
  5459. }
  5460. return hash;
  5461. };
  5462. /**
  5463. * Decomposes the current Matrix into a translation, rotation and scaling components
  5464. * @param scale defines the scale vector3 given as a reference to update
  5465. * @param rotation defines the rotation quaternion given as a reference to update
  5466. * @param translation defines the translation vector3 given as a reference to update
  5467. * @returns true if operation was successful
  5468. */
  5469. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5470. if (translation) {
  5471. translation.x = this.m[12];
  5472. translation.y = this.m[13];
  5473. translation.z = this.m[14];
  5474. }
  5475. scale = scale || MathTmp.Vector3[0];
  5476. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5477. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5478. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5479. if (this.determinant() <= 0) {
  5480. scale.y *= -1;
  5481. }
  5482. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5483. if (rotation) {
  5484. rotation.x = 0;
  5485. rotation.y = 0;
  5486. rotation.z = 0;
  5487. rotation.w = 1;
  5488. }
  5489. return false;
  5490. }
  5491. if (rotation) {
  5492. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5493. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5494. }
  5495. return true;
  5496. };
  5497. /**
  5498. * Gets specific row of the matrix
  5499. * @param index defines the number of the row to get
  5500. * @returns the index-th row of the current matrix as a new Vector4
  5501. */
  5502. Matrix.prototype.getRow = function (index) {
  5503. if (index < 0 || index > 3) {
  5504. return null;
  5505. }
  5506. var i = index * 4;
  5507. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5508. };
  5509. /**
  5510. * Sets the index-th row of the current matrix to the vector4 values
  5511. * @param index defines the number of the row to set
  5512. * @param row defines the target vector4
  5513. * @returns the updated current matrix
  5514. */
  5515. Matrix.prototype.setRow = function (index, row) {
  5516. if (index < 0 || index > 3) {
  5517. return this;
  5518. }
  5519. var i = index * 4;
  5520. this.m[i + 0] = row.x;
  5521. this.m[i + 1] = row.y;
  5522. this.m[i + 2] = row.z;
  5523. this.m[i + 3] = row.w;
  5524. this._markAsUpdated();
  5525. return this;
  5526. };
  5527. /**
  5528. * Compute the transpose of the matrix
  5529. * @returns the new transposed matrix
  5530. */
  5531. Matrix.prototype.transpose = function () {
  5532. return Matrix.Transpose(this);
  5533. };
  5534. /**
  5535. * Compute the transpose of the matrix and store it in a given matrix
  5536. * @param result defines the target matrix
  5537. * @returns the current matrix
  5538. */
  5539. Matrix.prototype.transposeToRef = function (result) {
  5540. Matrix.TransposeToRef(this, result);
  5541. return this;
  5542. };
  5543. /**
  5544. * Sets the index-th row of the current matrix with the given 4 x float values
  5545. * @param index defines the row index
  5546. * @param x defines the x component to set
  5547. * @param y defines the y component to set
  5548. * @param z defines the z component to set
  5549. * @param w defines the w component to set
  5550. * @returns the updated current matrix
  5551. */
  5552. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5553. if (index < 0 || index > 3) {
  5554. return this;
  5555. }
  5556. var i = index * 4;
  5557. this.m[i + 0] = x;
  5558. this.m[i + 1] = y;
  5559. this.m[i + 2] = z;
  5560. this.m[i + 3] = w;
  5561. this._markAsUpdated();
  5562. return this;
  5563. };
  5564. /**
  5565. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5566. * @param scale defines the scale factor
  5567. * @returns a new matrix
  5568. */
  5569. Matrix.prototype.scale = function (scale) {
  5570. var result = new Matrix();
  5571. this.scaleToRef(scale, result);
  5572. return result;
  5573. };
  5574. /**
  5575. * Scale the current matrix values by a factor to a given result matrix
  5576. * @param scale defines the scale factor
  5577. * @param result defines the matrix to store the result
  5578. * @returns the current matrix
  5579. */
  5580. Matrix.prototype.scaleToRef = function (scale, result) {
  5581. for (var index = 0; index < 16; index++) {
  5582. result.m[index] = this.m[index] * scale;
  5583. }
  5584. result._markAsUpdated();
  5585. return this;
  5586. };
  5587. /**
  5588. * Scale the current matrix values by a factor and add the result to a given matrix
  5589. * @param scale defines the scale factor
  5590. * @param result defines the Matrix to store the result
  5591. * @returns the current matrix
  5592. */
  5593. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] += this.m[index] * scale;
  5596. }
  5597. result._markAsUpdated();
  5598. return this;
  5599. };
  5600. /**
  5601. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5602. * @param ref matrix to store the result
  5603. */
  5604. Matrix.prototype.toNormalMatrix = function (ref) {
  5605. this.invertToRef(ref);
  5606. ref.transpose();
  5607. var m = ref.m;
  5608. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5609. };
  5610. /**
  5611. * Gets only rotation part of the current matrix
  5612. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5613. */
  5614. Matrix.prototype.getRotationMatrix = function () {
  5615. var result = Matrix.Identity();
  5616. this.getRotationMatrixToRef(result);
  5617. return result;
  5618. };
  5619. /**
  5620. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5621. * @param result defines the target matrix to store data to
  5622. * @returns the current matrix
  5623. */
  5624. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5625. var m = this.m;
  5626. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5627. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5628. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5629. if (this.determinant() <= 0) {
  5630. sy *= -1;
  5631. }
  5632. if (sx === 0 || sy === 0 || sz === 0) {
  5633. Matrix.IdentityToRef(result);
  5634. }
  5635. else {
  5636. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5637. }
  5638. return this;
  5639. };
  5640. // Statics
  5641. /**
  5642. * Creates a matrix from an array
  5643. * @param array defines the source array
  5644. * @param offset defines an offset in the source array
  5645. * @returns a new Matrix set from the starting index of the given array
  5646. */
  5647. Matrix.FromArray = function (array, offset) {
  5648. var result = new Matrix();
  5649. if (!offset) {
  5650. offset = 0;
  5651. }
  5652. Matrix.FromArrayToRef(array, offset, result);
  5653. return result;
  5654. };
  5655. /**
  5656. * Copy the content of an array into a given matrix
  5657. * @param array defines the source array
  5658. * @param offset defines an offset in the source array
  5659. * @param result defines the target matrix
  5660. */
  5661. Matrix.FromArrayToRef = function (array, offset, result) {
  5662. for (var index = 0; index < 16; index++) {
  5663. result.m[index] = array[index + offset];
  5664. }
  5665. result._markAsUpdated();
  5666. };
  5667. /**
  5668. * Stores an array into a matrix after having multiplied each component by a given factor
  5669. * @param array defines the source array
  5670. * @param offset defines the offset in the source array
  5671. * @param scale defines the scaling factor
  5672. * @param result defines the target matrix
  5673. */
  5674. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5675. for (var index = 0; index < 16; index++) {
  5676. result.m[index] = array[index + offset] * scale;
  5677. }
  5678. result._markAsUpdated();
  5679. };
  5680. /**
  5681. * Stores a list of values (16) inside a given matrix
  5682. * @param initialM11 defines 1st value of 1st row
  5683. * @param initialM12 defines 2nd value of 1st row
  5684. * @param initialM13 defines 3rd value of 1st row
  5685. * @param initialM14 defines 4th value of 1st row
  5686. * @param initialM21 defines 1st value of 2nd row
  5687. * @param initialM22 defines 2nd value of 2nd row
  5688. * @param initialM23 defines 3rd value of 2nd row
  5689. * @param initialM24 defines 4th value of 2nd row
  5690. * @param initialM31 defines 1st value of 3rd row
  5691. * @param initialM32 defines 2nd value of 3rd row
  5692. * @param initialM33 defines 3rd value of 3rd row
  5693. * @param initialM34 defines 4th value of 3rd row
  5694. * @param initialM41 defines 1st value of 4th row
  5695. * @param initialM42 defines 2nd value of 4th row
  5696. * @param initialM43 defines 3rd value of 4th row
  5697. * @param initialM44 defines 4th value of 4th row
  5698. * @param result defines the target matrix
  5699. */
  5700. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5701. result.m[0] = initialM11;
  5702. result.m[1] = initialM12;
  5703. result.m[2] = initialM13;
  5704. result.m[3] = initialM14;
  5705. result.m[4] = initialM21;
  5706. result.m[5] = initialM22;
  5707. result.m[6] = initialM23;
  5708. result.m[7] = initialM24;
  5709. result.m[8] = initialM31;
  5710. result.m[9] = initialM32;
  5711. result.m[10] = initialM33;
  5712. result.m[11] = initialM34;
  5713. result.m[12] = initialM41;
  5714. result.m[13] = initialM42;
  5715. result.m[14] = initialM43;
  5716. result.m[15] = initialM44;
  5717. result._markAsUpdated();
  5718. };
  5719. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5720. /**
  5721. * Gets an identity matrix that must not be updated
  5722. */
  5723. get: function () {
  5724. return Matrix._identityReadOnly;
  5725. },
  5726. enumerable: true,
  5727. configurable: true
  5728. });
  5729. /**
  5730. * Creates new matrix from a list of values (16)
  5731. * @param initialM11 defines 1st value of 1st row
  5732. * @param initialM12 defines 2nd value of 1st row
  5733. * @param initialM13 defines 3rd value of 1st row
  5734. * @param initialM14 defines 4th value of 1st row
  5735. * @param initialM21 defines 1st value of 2nd row
  5736. * @param initialM22 defines 2nd value of 2nd row
  5737. * @param initialM23 defines 3rd value of 2nd row
  5738. * @param initialM24 defines 4th value of 2nd row
  5739. * @param initialM31 defines 1st value of 3rd row
  5740. * @param initialM32 defines 2nd value of 3rd row
  5741. * @param initialM33 defines 3rd value of 3rd row
  5742. * @param initialM34 defines 4th value of 3rd row
  5743. * @param initialM41 defines 1st value of 4th row
  5744. * @param initialM42 defines 2nd value of 4th row
  5745. * @param initialM43 defines 3rd value of 4th row
  5746. * @param initialM44 defines 4th value of 4th row
  5747. * @returns the new matrix
  5748. */
  5749. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5750. var result = new Matrix();
  5751. result.m[0] = initialM11;
  5752. result.m[1] = initialM12;
  5753. result.m[2] = initialM13;
  5754. result.m[3] = initialM14;
  5755. result.m[4] = initialM21;
  5756. result.m[5] = initialM22;
  5757. result.m[6] = initialM23;
  5758. result.m[7] = initialM24;
  5759. result.m[8] = initialM31;
  5760. result.m[9] = initialM32;
  5761. result.m[10] = initialM33;
  5762. result.m[11] = initialM34;
  5763. result.m[12] = initialM41;
  5764. result.m[13] = initialM42;
  5765. result.m[14] = initialM43;
  5766. result.m[15] = initialM44;
  5767. return result;
  5768. };
  5769. /**
  5770. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5771. * @param scale defines the scale vector3
  5772. * @param rotation defines the rotation quaternion
  5773. * @param translation defines the translation vector3
  5774. * @returns a new matrix
  5775. */
  5776. Matrix.Compose = function (scale, rotation, translation) {
  5777. var result = Matrix.Identity();
  5778. Matrix.ComposeToRef(scale, rotation, translation, result);
  5779. return result;
  5780. };
  5781. /**
  5782. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5783. * @param scale defines the scale vector3
  5784. * @param rotation defines the rotation quaternion
  5785. * @param translation defines the translation vector3
  5786. * @param result defines the target matrix
  5787. */
  5788. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5789. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5790. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5791. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5792. result.setTranslation(translation);
  5793. };
  5794. /**
  5795. * Creates a new identity matrix
  5796. * @returns a new identity matrix
  5797. */
  5798. Matrix.Identity = function () {
  5799. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5800. };
  5801. /**
  5802. * Creates a new identity matrix and stores the result in a given matrix
  5803. * @param result defines the target matrix
  5804. */
  5805. Matrix.IdentityToRef = function (result) {
  5806. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5807. };
  5808. /**
  5809. * Creates a new zero matrix
  5810. * @returns a new zero matrix
  5811. */
  5812. Matrix.Zero = function () {
  5813. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5814. };
  5815. /**
  5816. * Creates a new rotation matrix for "angle" radians around the X axis
  5817. * @param angle defines the angle (in radians) to use
  5818. * @return the new matrix
  5819. */
  5820. Matrix.RotationX = function (angle) {
  5821. var result = new Matrix();
  5822. Matrix.RotationXToRef(angle, result);
  5823. return result;
  5824. };
  5825. /**
  5826. * Creates a new matrix as the invert of a given matrix
  5827. * @param source defines the source matrix
  5828. * @returns the new matrix
  5829. */
  5830. Matrix.Invert = function (source) {
  5831. var result = new Matrix();
  5832. source.invertToRef(result);
  5833. return result;
  5834. };
  5835. /**
  5836. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5837. * @param angle defines the angle (in radians) to use
  5838. * @param result defines the target matrix
  5839. */
  5840. Matrix.RotationXToRef = function (angle, result) {
  5841. var s = Math.sin(angle);
  5842. var c = Math.cos(angle);
  5843. result.m[0] = 1.0;
  5844. result.m[15] = 1.0;
  5845. result.m[5] = c;
  5846. result.m[10] = c;
  5847. result.m[9] = -s;
  5848. result.m[6] = s;
  5849. result.m[1] = 0.0;
  5850. result.m[2] = 0.0;
  5851. result.m[3] = 0.0;
  5852. result.m[4] = 0.0;
  5853. result.m[7] = 0.0;
  5854. result.m[8] = 0.0;
  5855. result.m[11] = 0.0;
  5856. result.m[12] = 0.0;
  5857. result.m[13] = 0.0;
  5858. result.m[14] = 0.0;
  5859. result._markAsUpdated();
  5860. };
  5861. /**
  5862. * Creates a new rotation matrix for "angle" radians around the Y axis
  5863. * @param angle defines the angle (in radians) to use
  5864. * @return the new matrix
  5865. */
  5866. Matrix.RotationY = function (angle) {
  5867. var result = new Matrix();
  5868. Matrix.RotationYToRef(angle, result);
  5869. return result;
  5870. };
  5871. /**
  5872. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5873. * @param angle defines the angle (in radians) to use
  5874. * @param result defines the target matrix
  5875. */
  5876. Matrix.RotationYToRef = function (angle, result) {
  5877. var s = Math.sin(angle);
  5878. var c = Math.cos(angle);
  5879. result.m[5] = 1.0;
  5880. result.m[15] = 1.0;
  5881. result.m[0] = c;
  5882. result.m[2] = -s;
  5883. result.m[8] = s;
  5884. result.m[10] = c;
  5885. result.m[1] = 0.0;
  5886. result.m[3] = 0.0;
  5887. result.m[4] = 0.0;
  5888. result.m[6] = 0.0;
  5889. result.m[7] = 0.0;
  5890. result.m[9] = 0.0;
  5891. result.m[11] = 0.0;
  5892. result.m[12] = 0.0;
  5893. result.m[13] = 0.0;
  5894. result.m[14] = 0.0;
  5895. result._markAsUpdated();
  5896. };
  5897. /**
  5898. * Creates a new rotation matrix for "angle" radians around the Z axis
  5899. * @param angle defines the angle (in radians) to use
  5900. * @return the new matrix
  5901. */
  5902. Matrix.RotationZ = function (angle) {
  5903. var result = new Matrix();
  5904. Matrix.RotationZToRef(angle, result);
  5905. return result;
  5906. };
  5907. /**
  5908. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5909. * @param angle defines the angle (in radians) to use
  5910. * @param result defines the target matrix
  5911. */
  5912. Matrix.RotationZToRef = function (angle, result) {
  5913. var s = Math.sin(angle);
  5914. var c = Math.cos(angle);
  5915. result.m[10] = 1.0;
  5916. result.m[15] = 1.0;
  5917. result.m[0] = c;
  5918. result.m[1] = s;
  5919. result.m[4] = -s;
  5920. result.m[5] = c;
  5921. result.m[2] = 0.0;
  5922. result.m[3] = 0.0;
  5923. result.m[6] = 0.0;
  5924. result.m[7] = 0.0;
  5925. result.m[8] = 0.0;
  5926. result.m[9] = 0.0;
  5927. result.m[11] = 0.0;
  5928. result.m[12] = 0.0;
  5929. result.m[13] = 0.0;
  5930. result.m[14] = 0.0;
  5931. result._markAsUpdated();
  5932. };
  5933. /**
  5934. * Creates a new rotation matrix for "angle" radians around the given axis
  5935. * @param axis defines the axis to use
  5936. * @param angle defines the angle (in radians) to use
  5937. * @return the new matrix
  5938. */
  5939. Matrix.RotationAxis = function (axis, angle) {
  5940. var result = Matrix.Zero();
  5941. Matrix.RotationAxisToRef(axis, angle, result);
  5942. return result;
  5943. };
  5944. /**
  5945. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5946. * @param axis defines the axis to use
  5947. * @param angle defines the angle (in radians) to use
  5948. * @param result defines the target matrix
  5949. */
  5950. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5951. var s = Math.sin(-angle);
  5952. var c = Math.cos(-angle);
  5953. var c1 = 1 - c;
  5954. axis.normalize();
  5955. result.m[0] = (axis.x * axis.x) * c1 + c;
  5956. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5957. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5958. result.m[3] = 0.0;
  5959. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5960. result.m[5] = (axis.y * axis.y) * c1 + c;
  5961. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5962. result.m[7] = 0.0;
  5963. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5964. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5965. result.m[10] = (axis.z * axis.z) * c1 + c;
  5966. result.m[11] = 0.0;
  5967. result.m[15] = 1.0;
  5968. result._markAsUpdated();
  5969. };
  5970. /**
  5971. * Creates a rotation matrix
  5972. * @param yaw defines the yaw angle in radians (Y axis)
  5973. * @param pitch defines the pitch angle in radians (X axis)
  5974. * @param roll defines the roll angle in radians (X axis)
  5975. * @returns the new rotation matrix
  5976. */
  5977. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5978. var result = new Matrix();
  5979. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5980. return result;
  5981. };
  5982. /**
  5983. * Creates a rotation matrix and stores it in a given matrix
  5984. * @param yaw defines the yaw angle in radians (Y axis)
  5985. * @param pitch defines the pitch angle in radians (X axis)
  5986. * @param roll defines the roll angle in radians (X axis)
  5987. * @param result defines the target matrix
  5988. */
  5989. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5990. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5991. this._tempQuaternion.toRotationMatrix(result);
  5992. };
  5993. /**
  5994. * Creates a scaling matrix
  5995. * @param x defines the scale factor on X axis
  5996. * @param y defines the scale factor on Y axis
  5997. * @param z defines the scale factor on Z axis
  5998. * @returns the new matrix
  5999. */
  6000. Matrix.Scaling = function (x, y, z) {
  6001. var result = Matrix.Zero();
  6002. Matrix.ScalingToRef(x, y, z, result);
  6003. return result;
  6004. };
  6005. /**
  6006. * Creates a scaling matrix and stores it in a given matrix
  6007. * @param x defines the scale factor on X axis
  6008. * @param y defines the scale factor on Y axis
  6009. * @param z defines the scale factor on Z axis
  6010. * @param result defines the target matrix
  6011. */
  6012. Matrix.ScalingToRef = function (x, y, z, result) {
  6013. result.m[0] = x;
  6014. result.m[1] = 0.0;
  6015. result.m[2] = 0.0;
  6016. result.m[3] = 0.0;
  6017. result.m[4] = 0.0;
  6018. result.m[5] = y;
  6019. result.m[6] = 0.0;
  6020. result.m[7] = 0.0;
  6021. result.m[8] = 0.0;
  6022. result.m[9] = 0.0;
  6023. result.m[10] = z;
  6024. result.m[11] = 0.0;
  6025. result.m[12] = 0.0;
  6026. result.m[13] = 0.0;
  6027. result.m[14] = 0.0;
  6028. result.m[15] = 1.0;
  6029. result._markAsUpdated();
  6030. };
  6031. /**
  6032. * Creates a translation matrix
  6033. * @param x defines the translation on X axis
  6034. * @param y defines the translation on Y axis
  6035. * @param z defines the translationon Z axis
  6036. * @returns the new matrix
  6037. */
  6038. Matrix.Translation = function (x, y, z) {
  6039. var result = Matrix.Identity();
  6040. Matrix.TranslationToRef(x, y, z, result);
  6041. return result;
  6042. };
  6043. /**
  6044. * Creates a translation matrix and stores it in a given matrix
  6045. * @param x defines the translation on X axis
  6046. * @param y defines the translation on Y axis
  6047. * @param z defines the translationon Z axis
  6048. * @param result defines the target matrix
  6049. */
  6050. Matrix.TranslationToRef = function (x, y, z, result) {
  6051. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  6052. };
  6053. /**
  6054. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6055. * @param startValue defines the start value
  6056. * @param endValue defines the end value
  6057. * @param gradient defines the gradient factor
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.Lerp = function (startValue, endValue, gradient) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6067. * @param startValue defines the start value
  6068. * @param endValue defines the end value
  6069. * @param gradient defines the gradient factor
  6070. * @param result defines the Matrix object where to store data
  6071. */
  6072. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6073. for (var index = 0; index < 16; index++) {
  6074. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6075. }
  6076. result._markAsUpdated();
  6077. };
  6078. /**
  6079. * Builds a new matrix whose values are computed by:
  6080. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6081. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6082. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6083. * @param startValue defines the first matrix
  6084. * @param endValue defines the second matrix
  6085. * @param gradient defines the gradient between the two matrices
  6086. * @returns the new matrix
  6087. */
  6088. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6089. var result = Matrix.Zero();
  6090. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6091. return result;
  6092. };
  6093. /**
  6094. * Update a matrix to values which are computed by:
  6095. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6096. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6097. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6098. * @param startValue defines the first matrix
  6099. * @param endValue defines the second matrix
  6100. * @param gradient defines the gradient between the two matrices
  6101. * @param result defines the target matrix
  6102. */
  6103. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6104. var startScale = MathTmp.Vector3[0];
  6105. var startRotation = MathTmp.Quaternion[0];
  6106. var startTranslation = MathTmp.Vector3[1];
  6107. startValue.decompose(startScale, startRotation, startTranslation);
  6108. var endScale = MathTmp.Vector3[2];
  6109. var endRotation = MathTmp.Quaternion[1];
  6110. var endTranslation = MathTmp.Vector3[3];
  6111. endValue.decompose(endScale, endRotation, endTranslation);
  6112. var resultScale = MathTmp.Vector3[4];
  6113. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6114. var resultRotation = MathTmp.Quaternion[2];
  6115. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6116. var resultTranslation = MathTmp.Vector3[5];
  6117. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6118. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6119. };
  6120. /**
  6121. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6122. * This function works in left handed mode
  6123. * @param eye defines the final position of the entity
  6124. * @param target defines where the entity should look at
  6125. * @param up defines the up vector for the entity
  6126. * @returns the new matrix
  6127. */
  6128. Matrix.LookAtLH = function (eye, target, up) {
  6129. var result = Matrix.Zero();
  6130. Matrix.LookAtLHToRef(eye, target, up, result);
  6131. return result;
  6132. };
  6133. /**
  6134. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6135. * This function works in left handed mode
  6136. * @param eye defines the final position of the entity
  6137. * @param target defines where the entity should look at
  6138. * @param up defines the up vector for the entity
  6139. * @param result defines the target matrix
  6140. */
  6141. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6142. // Z axis
  6143. target.subtractToRef(eye, this._zAxis);
  6144. this._zAxis.normalize();
  6145. // X axis
  6146. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6147. if (this._xAxis.lengthSquared() === 0) {
  6148. this._xAxis.x = 1.0;
  6149. }
  6150. else {
  6151. this._xAxis.normalize();
  6152. }
  6153. // Y axis
  6154. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6155. this._yAxis.normalize();
  6156. // Eye angles
  6157. var ex = -Vector3.Dot(this._xAxis, eye);
  6158. var ey = -Vector3.Dot(this._yAxis, eye);
  6159. var ez = -Vector3.Dot(this._zAxis, eye);
  6160. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6161. };
  6162. /**
  6163. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6164. * This function works in right handed mode
  6165. * @param eye defines the final position of the entity
  6166. * @param target defines where the entity should look at
  6167. * @param up defines the up vector for the entity
  6168. * @returns the new matrix
  6169. */
  6170. Matrix.LookAtRH = function (eye, target, up) {
  6171. var result = Matrix.Zero();
  6172. Matrix.LookAtRHToRef(eye, target, up, result);
  6173. return result;
  6174. };
  6175. /**
  6176. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6177. * This function works in right handed mode
  6178. * @param eye defines the final position of the entity
  6179. * @param target defines where the entity should look at
  6180. * @param up defines the up vector for the entity
  6181. * @param result defines the target matrix
  6182. */
  6183. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6184. // Z axis
  6185. eye.subtractToRef(target, this._zAxis);
  6186. this._zAxis.normalize();
  6187. // X axis
  6188. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6189. if (this._xAxis.lengthSquared() === 0) {
  6190. this._xAxis.x = 1.0;
  6191. }
  6192. else {
  6193. this._xAxis.normalize();
  6194. }
  6195. // Y axis
  6196. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6197. this._yAxis.normalize();
  6198. // Eye angles
  6199. var ex = -Vector3.Dot(this._xAxis, eye);
  6200. var ey = -Vector3.Dot(this._yAxis, eye);
  6201. var ez = -Vector3.Dot(this._zAxis, eye);
  6202. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6203. };
  6204. /**
  6205. * Create a left-handed orthographic projection matrix
  6206. * @param width defines the viewport width
  6207. * @param height defines the viewport height
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a left-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Store a left-handed orthographic projection to a given matrix
  6219. * @param width defines the viewport width
  6220. * @param height defines the viewport height
  6221. * @param znear defines the near clip plane
  6222. * @param zfar defines the far clip plane
  6223. * @param result defines the target matrix
  6224. */
  6225. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6226. var n = znear;
  6227. var f = zfar;
  6228. var a = 2.0 / width;
  6229. var b = 2.0 / height;
  6230. var c = 2.0 / (f - n);
  6231. var d = -(f + n) / (f - n);
  6232. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6233. };
  6234. /**
  6235. * Create a left-handed orthographic projection matrix
  6236. * @param left defines the viewport left coordinate
  6237. * @param right defines the viewport right coordinate
  6238. * @param bottom defines the viewport bottom coordinate
  6239. * @param top defines the viewport top coordinate
  6240. * @param znear defines the near clip plane
  6241. * @param zfar defines the far clip plane
  6242. * @returns a new matrix as a left-handed orthographic projection matrix
  6243. */
  6244. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6245. var matrix = Matrix.Zero();
  6246. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6247. return matrix;
  6248. };
  6249. /**
  6250. * Stores a left-handed orthographic projection into a given matrix
  6251. * @param left defines the viewport left coordinate
  6252. * @param right defines the viewport right coordinate
  6253. * @param bottom defines the viewport bottom coordinate
  6254. * @param top defines the viewport top coordinate
  6255. * @param znear defines the near clip plane
  6256. * @param zfar defines the far clip plane
  6257. * @param result defines the target matrix
  6258. */
  6259. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6260. var n = znear;
  6261. var f = zfar;
  6262. var a = 2.0 / (right - left);
  6263. var b = 2.0 / (top - bottom);
  6264. var c = 2.0 / (f - n);
  6265. var d = -(f + n) / (f - n);
  6266. var i0 = (left + right) / (left - right);
  6267. var i1 = (top + bottom) / (bottom - top);
  6268. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6269. };
  6270. /**
  6271. * Creates a right-handed orthographic projection matrix
  6272. * @param left defines the viewport left coordinate
  6273. * @param right defines the viewport right coordinate
  6274. * @param bottom defines the viewport bottom coordinate
  6275. * @param top defines the viewport top coordinate
  6276. * @param znear defines the near clip plane
  6277. * @param zfar defines the far clip plane
  6278. * @returns a new matrix as a right-handed orthographic projection matrix
  6279. */
  6280. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6281. var matrix = Matrix.Zero();
  6282. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6283. return matrix;
  6284. };
  6285. /**
  6286. * Stores a right-handed orthographic projection into a given matrix
  6287. * @param left defines the viewport left coordinate
  6288. * @param right defines the viewport right coordinate
  6289. * @param bottom defines the viewport bottom coordinate
  6290. * @param top defines the viewport top coordinate
  6291. * @param znear defines the near clip plane
  6292. * @param zfar defines the far clip plane
  6293. * @param result defines the target matrix
  6294. */
  6295. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6296. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6297. result.m[10] *= -1.0;
  6298. };
  6299. /**
  6300. * Creates a left-handed perspective projection matrix
  6301. * @param width defines the viewport width
  6302. * @param height defines the viewport height
  6303. * @param znear defines the near clip plane
  6304. * @param zfar defines the far clip plane
  6305. * @returns a new matrix as a left-handed perspective projection matrix
  6306. */
  6307. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6308. var matrix = Matrix.Zero();
  6309. var n = znear;
  6310. var f = zfar;
  6311. var a = 2.0 * n / width;
  6312. var b = 2.0 * n / height;
  6313. var c = (f + n) / (f - n);
  6314. var d = -2.0 * f * n / (f - n);
  6315. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6316. return matrix;
  6317. };
  6318. /**
  6319. * Creates a left-handed perspective projection matrix
  6320. * @param fov defines the horizontal field of view
  6321. * @param aspect defines the aspect ratio
  6322. * @param znear defines the near clip plane
  6323. * @param zfar defines the far clip plane
  6324. * @returns a new matrix as a left-handed perspective projection matrix
  6325. */
  6326. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6327. var matrix = Matrix.Zero();
  6328. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6329. return matrix;
  6330. };
  6331. /**
  6332. * Stores a left-handed perspective projection into a given matrix
  6333. * @param fov defines the horizontal field of view
  6334. * @param aspect defines the aspect ratio
  6335. * @param znear defines the near clip plane
  6336. * @param zfar defines the far clip plane
  6337. * @param result defines the target matrix
  6338. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6339. */
  6340. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6341. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6342. var n = znear;
  6343. var f = zfar;
  6344. var t = 1.0 / (Math.tan(fov * 0.5));
  6345. var a = isVerticalFovFixed ? (t / aspect) : t;
  6346. var b = isVerticalFovFixed ? t : (t * aspect);
  6347. var c = (f + n) / (f - n);
  6348. var d = -2.0 * f * n / (f - n);
  6349. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6350. };
  6351. /**
  6352. * Creates a right-handed perspective projection matrix
  6353. * @param fov defines the horizontal field of view
  6354. * @param aspect defines the aspect ratio
  6355. * @param znear defines the near clip plane
  6356. * @param zfar defines the far clip plane
  6357. * @returns a new matrix as a right-handed perspective projection matrix
  6358. */
  6359. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6360. var matrix = Matrix.Zero();
  6361. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6362. return matrix;
  6363. };
  6364. /**
  6365. * Stores a right-handed perspective projection into a given matrix
  6366. * @param fov defines the horizontal field of view
  6367. * @param aspect defines the aspect ratio
  6368. * @param znear defines the near clip plane
  6369. * @param zfar defines the far clip plane
  6370. * @param result defines the target matrix
  6371. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6372. */
  6373. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6374. //alternatively this could be expressed as:
  6375. // m = PerspectiveFovLHToRef
  6376. // m[10] *= -1.0;
  6377. // m[11] *= -1.0;
  6378. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6379. var n = znear;
  6380. var f = zfar;
  6381. var t = 1.0 / (Math.tan(fov * 0.5));
  6382. var a = isVerticalFovFixed ? (t / aspect) : t;
  6383. var b = isVerticalFovFixed ? t : (t * aspect);
  6384. var c = -(f + n) / (f - n);
  6385. var d = -2 * f * n / (f - n);
  6386. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6387. };
  6388. /**
  6389. * Stores a perspective projection for WebVR info a given matrix
  6390. * @param fov defines the field of view
  6391. * @param znear defines the near clip plane
  6392. * @param zfar defines the far clip plane
  6393. * @param result defines the target matrix
  6394. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6395. */
  6396. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6397. if (rightHanded === void 0) { rightHanded = false; }
  6398. var rightHandedFactor = rightHanded ? -1 : 1;
  6399. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6400. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6401. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6402. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6403. var xScale = 2.0 / (leftTan + rightTan);
  6404. var yScale = 2.0 / (upTan + downTan);
  6405. result.m[0] = xScale;
  6406. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6407. result.m[5] = yScale;
  6408. result.m[6] = result.m[7] = 0.0;
  6409. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6410. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6411. result.m[10] = -zfar / (znear - zfar);
  6412. result.m[11] = 1.0 * rightHandedFactor;
  6413. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6414. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6415. result._markAsUpdated();
  6416. };
  6417. /**
  6418. * Computes a complete transformation matrix
  6419. * @param viewport defines the viewport to use
  6420. * @param world defines the world matrix
  6421. * @param view defines the view matrix
  6422. * @param projection defines the projection matrix
  6423. * @param zmin defines the near clip plane
  6424. * @param zmax defines the far clip plane
  6425. * @returns the transformation matrix
  6426. */
  6427. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6428. var cw = viewport.width;
  6429. var ch = viewport.height;
  6430. var cx = viewport.x;
  6431. var cy = viewport.y;
  6432. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6433. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6434. };
  6435. /**
  6436. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6437. * @param matrix defines the matrix to use
  6438. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6439. */
  6440. Matrix.GetAsMatrix2x2 = function (matrix) {
  6441. return new Float32Array([
  6442. matrix.m[0], matrix.m[1],
  6443. matrix.m[4], matrix.m[5]
  6444. ]);
  6445. };
  6446. /**
  6447. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6448. * @param matrix defines the matrix to use
  6449. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6450. */
  6451. Matrix.GetAsMatrix3x3 = function (matrix) {
  6452. return new Float32Array([
  6453. matrix.m[0], matrix.m[1], matrix.m[2],
  6454. matrix.m[4], matrix.m[5], matrix.m[6],
  6455. matrix.m[8], matrix.m[9], matrix.m[10]
  6456. ]);
  6457. };
  6458. /**
  6459. * Compute the transpose of a given matrix
  6460. * @param matrix defines the matrix to transpose
  6461. * @returns the new matrix
  6462. */
  6463. Matrix.Transpose = function (matrix) {
  6464. var result = new Matrix();
  6465. Matrix.TransposeToRef(matrix, result);
  6466. return result;
  6467. };
  6468. /**
  6469. * Compute the transpose of a matrix and store it in a target matrix
  6470. * @param matrix defines the matrix to transpose
  6471. * @param result defines the target matrix
  6472. */
  6473. Matrix.TransposeToRef = function (matrix, result) {
  6474. result.m[0] = matrix.m[0];
  6475. result.m[1] = matrix.m[4];
  6476. result.m[2] = matrix.m[8];
  6477. result.m[3] = matrix.m[12];
  6478. result.m[4] = matrix.m[1];
  6479. result.m[5] = matrix.m[5];
  6480. result.m[6] = matrix.m[9];
  6481. result.m[7] = matrix.m[13];
  6482. result.m[8] = matrix.m[2];
  6483. result.m[9] = matrix.m[6];
  6484. result.m[10] = matrix.m[10];
  6485. result.m[11] = matrix.m[14];
  6486. result.m[12] = matrix.m[3];
  6487. result.m[13] = matrix.m[7];
  6488. result.m[14] = matrix.m[11];
  6489. result.m[15] = matrix.m[15];
  6490. };
  6491. /**
  6492. * Computes a reflection matrix from a plane
  6493. * @param plane defines the reflection plane
  6494. * @returns a new matrix
  6495. */
  6496. Matrix.Reflection = function (plane) {
  6497. var matrix = new Matrix();
  6498. Matrix.ReflectionToRef(plane, matrix);
  6499. return matrix;
  6500. };
  6501. /**
  6502. * Computes a reflection matrix from a plane
  6503. * @param plane defines the reflection plane
  6504. * @param result defines the target matrix
  6505. */
  6506. Matrix.ReflectionToRef = function (plane, result) {
  6507. plane.normalize();
  6508. var x = plane.normal.x;
  6509. var y = plane.normal.y;
  6510. var z = plane.normal.z;
  6511. var temp = -2 * x;
  6512. var temp2 = -2 * y;
  6513. var temp3 = -2 * z;
  6514. result.m[0] = (temp * x) + 1;
  6515. result.m[1] = temp2 * x;
  6516. result.m[2] = temp3 * x;
  6517. result.m[3] = 0.0;
  6518. result.m[4] = temp * y;
  6519. result.m[5] = (temp2 * y) + 1;
  6520. result.m[6] = temp3 * y;
  6521. result.m[7] = 0.0;
  6522. result.m[8] = temp * z;
  6523. result.m[9] = temp2 * z;
  6524. result.m[10] = (temp3 * z) + 1;
  6525. result.m[11] = 0.0;
  6526. result.m[12] = temp * plane.d;
  6527. result.m[13] = temp2 * plane.d;
  6528. result.m[14] = temp3 * plane.d;
  6529. result.m[15] = 1.0;
  6530. result._markAsUpdated();
  6531. };
  6532. /**
  6533. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6534. * @param xaxis defines the value of the 1st axis
  6535. * @param yaxis defines the value of the 2nd axis
  6536. * @param zaxis defines the value of the 3rd axis
  6537. * @param result defines the target matrix
  6538. */
  6539. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6540. result.m[0] = xaxis.x;
  6541. result.m[1] = xaxis.y;
  6542. result.m[2] = xaxis.z;
  6543. result.m[3] = 0.0;
  6544. result.m[4] = yaxis.x;
  6545. result.m[5] = yaxis.y;
  6546. result.m[6] = yaxis.z;
  6547. result.m[7] = 0.0;
  6548. result.m[8] = zaxis.x;
  6549. result.m[9] = zaxis.y;
  6550. result.m[10] = zaxis.z;
  6551. result.m[11] = 0.0;
  6552. result.m[12] = 0.0;
  6553. result.m[13] = 0.0;
  6554. result.m[14] = 0.0;
  6555. result.m[15] = 1.0;
  6556. result._markAsUpdated();
  6557. };
  6558. /**
  6559. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6560. * @param quat defines the quaternion to use
  6561. * @param result defines the target matrix
  6562. */
  6563. Matrix.FromQuaternionToRef = function (quat, result) {
  6564. var xx = quat.x * quat.x;
  6565. var yy = quat.y * quat.y;
  6566. var zz = quat.z * quat.z;
  6567. var xy = quat.x * quat.y;
  6568. var zw = quat.z * quat.w;
  6569. var zx = quat.z * quat.x;
  6570. var yw = quat.y * quat.w;
  6571. var yz = quat.y * quat.z;
  6572. var xw = quat.x * quat.w;
  6573. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6574. result.m[1] = 2.0 * (xy + zw);
  6575. result.m[2] = 2.0 * (zx - yw);
  6576. result.m[3] = 0.0;
  6577. result.m[4] = 2.0 * (xy - zw);
  6578. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6579. result.m[6] = 2.0 * (yz + xw);
  6580. result.m[7] = 0.0;
  6581. result.m[8] = 2.0 * (zx + yw);
  6582. result.m[9] = 2.0 * (yz - xw);
  6583. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6584. result.m[11] = 0.0;
  6585. result.m[12] = 0.0;
  6586. result.m[13] = 0.0;
  6587. result.m[14] = 0.0;
  6588. result.m[15] = 1.0;
  6589. result._markAsUpdated();
  6590. };
  6591. Matrix._tempQuaternion = new Quaternion();
  6592. Matrix._xAxis = Vector3.Zero();
  6593. Matrix._yAxis = Vector3.Zero();
  6594. Matrix._zAxis = Vector3.Zero();
  6595. Matrix._updateFlagSeed = 0;
  6596. Matrix._identityReadOnly = Matrix.Identity();
  6597. return Matrix;
  6598. }());
  6599. BABYLON.Matrix = Matrix;
  6600. var Plane = /** @class */ (function () {
  6601. /**
  6602. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6603. */
  6604. function Plane(a, b, c, d) {
  6605. this.normal = new Vector3(a, b, c);
  6606. this.d = d;
  6607. }
  6608. /**
  6609. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6610. */
  6611. Plane.prototype.asArray = function () {
  6612. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6613. };
  6614. // Methods
  6615. /**
  6616. * Returns a new plane copied from the current Plane.
  6617. */
  6618. Plane.prototype.clone = function () {
  6619. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6620. };
  6621. /**
  6622. * Returns the string "Plane".
  6623. */
  6624. Plane.prototype.getClassName = function () {
  6625. return "Plane";
  6626. };
  6627. /**
  6628. * Returns the Plane hash code.
  6629. */
  6630. Plane.prototype.getHashCode = function () {
  6631. var hash = this.normal.getHashCode();
  6632. hash = (hash * 397) ^ (this.d || 0);
  6633. return hash;
  6634. };
  6635. /**
  6636. * Normalize the current Plane in place.
  6637. * Returns the updated Plane.
  6638. */
  6639. Plane.prototype.normalize = function () {
  6640. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6641. var magnitude = 0.0;
  6642. if (norm !== 0) {
  6643. magnitude = 1.0 / norm;
  6644. }
  6645. this.normal.x *= magnitude;
  6646. this.normal.y *= magnitude;
  6647. this.normal.z *= magnitude;
  6648. this.d *= magnitude;
  6649. return this;
  6650. };
  6651. /**
  6652. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6653. */
  6654. Plane.prototype.transform = function (transformation) {
  6655. var transposedMatrix = Matrix.Transpose(transformation);
  6656. var x = this.normal.x;
  6657. var y = this.normal.y;
  6658. var z = this.normal.z;
  6659. var d = this.d;
  6660. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6661. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6662. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6663. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6664. return new Plane(normalX, normalY, normalZ, finalD);
  6665. };
  6666. /**
  6667. * Returns the dot product (float) of the point coordinates and the plane normal.
  6668. */
  6669. Plane.prototype.dotCoordinate = function (point) {
  6670. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6671. };
  6672. /**
  6673. * Updates the current Plane from the plane defined by the three given points.
  6674. * Returns the updated Plane.
  6675. */
  6676. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6677. var x1 = point2.x - point1.x;
  6678. var y1 = point2.y - point1.y;
  6679. var z1 = point2.z - point1.z;
  6680. var x2 = point3.x - point1.x;
  6681. var y2 = point3.y - point1.y;
  6682. var z2 = point3.z - point1.z;
  6683. var yz = (y1 * z2) - (z1 * y2);
  6684. var xz = (z1 * x2) - (x1 * z2);
  6685. var xy = (x1 * y2) - (y1 * x2);
  6686. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6687. var invPyth;
  6688. if (pyth !== 0) {
  6689. invPyth = 1.0 / pyth;
  6690. }
  6691. else {
  6692. invPyth = 0.0;
  6693. }
  6694. this.normal.x = yz * invPyth;
  6695. this.normal.y = xz * invPyth;
  6696. this.normal.z = xy * invPyth;
  6697. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6698. return this;
  6699. };
  6700. /**
  6701. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6702. */
  6703. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6704. var dot = Vector3.Dot(this.normal, direction);
  6705. return (dot <= epsilon);
  6706. };
  6707. /**
  6708. * Returns the signed distance (float) from the given point to the Plane.
  6709. */
  6710. Plane.prototype.signedDistanceTo = function (point) {
  6711. return Vector3.Dot(point, this.normal) + this.d;
  6712. };
  6713. // Statics
  6714. /**
  6715. * Returns a new Plane from the given array.
  6716. */
  6717. Plane.FromArray = function (array) {
  6718. return new Plane(array[0], array[1], array[2], array[3]);
  6719. };
  6720. /**
  6721. * Returns a new Plane defined by the three given points.
  6722. */
  6723. Plane.FromPoints = function (point1, point2, point3) {
  6724. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6725. result.copyFromPoints(point1, point2, point3);
  6726. return result;
  6727. };
  6728. /**
  6729. * Returns a new Plane the normal vector to this plane at the given origin point.
  6730. * Note : the vector "normal" is updated because normalized.
  6731. */
  6732. Plane.FromPositionAndNormal = function (origin, normal) {
  6733. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6734. normal.normalize();
  6735. result.normal = normal;
  6736. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6737. return result;
  6738. };
  6739. /**
  6740. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6741. */
  6742. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6743. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6744. return Vector3.Dot(point, normal) + d;
  6745. };
  6746. return Plane;
  6747. }());
  6748. BABYLON.Plane = Plane;
  6749. var Viewport = /** @class */ (function () {
  6750. /**
  6751. * Creates a Viewport object located at (x, y) and sized (width, height).
  6752. */
  6753. function Viewport(x, y, width, height) {
  6754. this.x = x;
  6755. this.y = y;
  6756. this.width = width;
  6757. this.height = height;
  6758. }
  6759. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6760. if (renderWidthOrEngine.getRenderWidth) {
  6761. var engine = renderWidthOrEngine;
  6762. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6763. }
  6764. var renderWidth = renderWidthOrEngine;
  6765. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6766. };
  6767. /**
  6768. * Returns a new Viewport copied from the current one.
  6769. */
  6770. Viewport.prototype.clone = function () {
  6771. return new Viewport(this.x, this.y, this.width, this.height);
  6772. };
  6773. return Viewport;
  6774. }());
  6775. BABYLON.Viewport = Viewport;
  6776. var Frustum = /** @class */ (function () {
  6777. function Frustum() {
  6778. }
  6779. /**
  6780. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6781. */
  6782. Frustum.GetPlanes = function (transform) {
  6783. var frustumPlanes = [];
  6784. for (var index = 0; index < 6; index++) {
  6785. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6786. }
  6787. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6788. return frustumPlanes;
  6789. };
  6790. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6791. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6792. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6793. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6794. frustumPlane.d = transform.m[15] + transform.m[14];
  6795. frustumPlane.normalize();
  6796. };
  6797. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6798. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6799. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6800. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6801. frustumPlane.d = transform.m[15] - transform.m[14];
  6802. frustumPlane.normalize();
  6803. };
  6804. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6805. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6806. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6807. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6808. frustumPlane.d = transform.m[15] + transform.m[12];
  6809. frustumPlane.normalize();
  6810. };
  6811. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6812. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6813. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6814. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6815. frustumPlane.d = transform.m[15] - transform.m[12];
  6816. frustumPlane.normalize();
  6817. };
  6818. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6819. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6820. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6821. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6822. frustumPlane.d = transform.m[15] - transform.m[13];
  6823. frustumPlane.normalize();
  6824. };
  6825. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6826. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6827. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6828. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6829. frustumPlane.d = transform.m[15] + transform.m[13];
  6830. frustumPlane.normalize();
  6831. };
  6832. /**
  6833. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6834. */
  6835. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6836. // Near
  6837. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6838. // Far
  6839. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6840. // Left
  6841. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6842. // Right
  6843. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6844. // Top
  6845. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6846. // Bottom
  6847. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6848. };
  6849. return Frustum;
  6850. }());
  6851. BABYLON.Frustum = Frustum;
  6852. /** Defines supported spaces */
  6853. var Space;
  6854. (function (Space) {
  6855. /** Local (object) space */
  6856. Space[Space["LOCAL"] = 0] = "LOCAL";
  6857. /** World space */
  6858. Space[Space["WORLD"] = 1] = "WORLD";
  6859. /** Bone space */
  6860. Space[Space["BONE"] = 2] = "BONE";
  6861. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6862. /** Defines the 3 main axes */
  6863. var Axis = /** @class */ (function () {
  6864. function Axis() {
  6865. }
  6866. /** X axis */
  6867. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6868. /** Y axis */
  6869. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6870. /** Z axis */
  6871. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6872. return Axis;
  6873. }());
  6874. BABYLON.Axis = Axis;
  6875. ;
  6876. var BezierCurve = /** @class */ (function () {
  6877. function BezierCurve() {
  6878. }
  6879. /**
  6880. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6881. */
  6882. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6883. // Extract X (which is equal to time here)
  6884. var f0 = 1 - 3 * x2 + 3 * x1;
  6885. var f1 = 3 * x2 - 6 * x1;
  6886. var f2 = 3 * x1;
  6887. var refinedT = t;
  6888. for (var i = 0; i < 5; i++) {
  6889. var refinedT2 = refinedT * refinedT;
  6890. var refinedT3 = refinedT2 * refinedT;
  6891. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6892. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6893. refinedT -= (x - t) * slope;
  6894. refinedT = Math.min(1, Math.max(0, refinedT));
  6895. }
  6896. // Resolve cubic bezier for the given x
  6897. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6898. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6899. Math.pow(refinedT, 3);
  6900. };
  6901. return BezierCurve;
  6902. }());
  6903. BABYLON.BezierCurve = BezierCurve;
  6904. /**
  6905. * Defines potential orientation for back face culling
  6906. */
  6907. var Orientation;
  6908. (function (Orientation) {
  6909. /**
  6910. * Clockwise
  6911. */
  6912. Orientation[Orientation["CW"] = 0] = "CW";
  6913. /** Counter clockwise */
  6914. Orientation[Orientation["CCW"] = 1] = "CCW";
  6915. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6916. /**
  6917. * Defines angle representation
  6918. */
  6919. var Angle = /** @class */ (function () {
  6920. /**
  6921. * Creates an Angle object of "radians" radians (float).
  6922. */
  6923. function Angle(radians) {
  6924. this._radians = radians;
  6925. if (this._radians < 0.0)
  6926. this._radians += (2.0 * Math.PI);
  6927. }
  6928. /**
  6929. * Get value in degrees
  6930. * @returns the Angle value in degrees (float)
  6931. */
  6932. Angle.prototype.degrees = function () {
  6933. return this._radians * 180.0 / Math.PI;
  6934. };
  6935. /**
  6936. * Get value in radians
  6937. * @returns the Angle value in radians (float)
  6938. */
  6939. Angle.prototype.radians = function () {
  6940. return this._radians;
  6941. };
  6942. /**
  6943. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6944. * @param a defines first vector
  6945. * @param b defines second vector
  6946. * @returns a new Angle
  6947. */
  6948. Angle.BetweenTwoPoints = function (a, b) {
  6949. var delta = b.subtract(a);
  6950. var theta = Math.atan2(delta.y, delta.x);
  6951. return new Angle(theta);
  6952. };
  6953. /**
  6954. * Gets a new Angle object from the given float in radians
  6955. * @param radians defines the angle value in radians
  6956. * @returns a new Angle
  6957. */
  6958. Angle.FromRadians = function (radians) {
  6959. return new Angle(radians);
  6960. };
  6961. /**
  6962. * Gets a new Angle object from the given float in degrees
  6963. * @param degrees defines the angle value in degrees
  6964. * @returns a new Angle
  6965. */
  6966. Angle.FromDegrees = function (degrees) {
  6967. return new Angle(degrees * Math.PI / 180.0);
  6968. };
  6969. return Angle;
  6970. }());
  6971. BABYLON.Angle = Angle;
  6972. var Arc2 = /** @class */ (function () {
  6973. /**
  6974. * Creates an Arc object from the three given points : start, middle and end.
  6975. */
  6976. function Arc2(startPoint, midPoint, endPoint) {
  6977. this.startPoint = startPoint;
  6978. this.midPoint = midPoint;
  6979. this.endPoint = endPoint;
  6980. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6981. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6982. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6983. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6984. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6985. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6986. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6987. var a1 = this.startAngle.degrees();
  6988. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6989. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6990. // angles correction
  6991. if (a2 - a1 > +180.0)
  6992. a2 -= 360.0;
  6993. if (a2 - a1 < -180.0)
  6994. a2 += 360.0;
  6995. if (a3 - a2 > +180.0)
  6996. a3 -= 360.0;
  6997. if (a3 - a2 < -180.0)
  6998. a3 += 360.0;
  6999. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7000. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7001. }
  7002. return Arc2;
  7003. }());
  7004. BABYLON.Arc2 = Arc2;
  7005. var Path2 = /** @class */ (function () {
  7006. /**
  7007. * Creates a Path2 object from the starting 2D coordinates x and y.
  7008. */
  7009. function Path2(x, y) {
  7010. this._points = new Array();
  7011. this._length = 0.0;
  7012. this.closed = false;
  7013. this._points.push(new Vector2(x, y));
  7014. }
  7015. /**
  7016. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7017. * Returns the updated Path2.
  7018. */
  7019. Path2.prototype.addLineTo = function (x, y) {
  7020. if (this.closed) {
  7021. return this;
  7022. }
  7023. var newPoint = new Vector2(x, y);
  7024. var previousPoint = this._points[this._points.length - 1];
  7025. this._points.push(newPoint);
  7026. this._length += newPoint.subtract(previousPoint).length();
  7027. return this;
  7028. };
  7029. /**
  7030. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  7031. * Returns the updated Path2.
  7032. */
  7033. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7034. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7035. if (this.closed) {
  7036. return this;
  7037. }
  7038. var startPoint = this._points[this._points.length - 1];
  7039. var midPoint = new Vector2(midX, midY);
  7040. var endPoint = new Vector2(endX, endY);
  7041. var arc = new Arc2(startPoint, midPoint, endPoint);
  7042. var increment = arc.angle.radians() / numberOfSegments;
  7043. if (arc.orientation === Orientation.CW)
  7044. increment *= -1;
  7045. var currentAngle = arc.startAngle.radians() + increment;
  7046. for (var i = 0; i < numberOfSegments; i++) {
  7047. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7048. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7049. this.addLineTo(x, y);
  7050. currentAngle += increment;
  7051. }
  7052. return this;
  7053. };
  7054. /**
  7055. * Closes the Path2.
  7056. * Returns the Path2.
  7057. */
  7058. Path2.prototype.close = function () {
  7059. this.closed = true;
  7060. return this;
  7061. };
  7062. /**
  7063. * Returns the Path2 total length (float).
  7064. */
  7065. Path2.prototype.length = function () {
  7066. var result = this._length;
  7067. if (!this.closed) {
  7068. var lastPoint = this._points[this._points.length - 1];
  7069. var firstPoint = this._points[0];
  7070. result += (firstPoint.subtract(lastPoint).length());
  7071. }
  7072. return result;
  7073. };
  7074. /**
  7075. * Returns the Path2 internal array of points.
  7076. */
  7077. Path2.prototype.getPoints = function () {
  7078. return this._points;
  7079. };
  7080. /**
  7081. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7082. */
  7083. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7084. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7085. return Vector2.Zero();
  7086. }
  7087. var lengthPosition = normalizedLengthPosition * this.length();
  7088. var previousOffset = 0;
  7089. for (var i = 0; i < this._points.length; i++) {
  7090. var j = (i + 1) % this._points.length;
  7091. var a = this._points[i];
  7092. var b = this._points[j];
  7093. var bToA = b.subtract(a);
  7094. var nextOffset = (bToA.length() + previousOffset);
  7095. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7096. var dir = bToA.normalize();
  7097. var localOffset = lengthPosition - previousOffset;
  7098. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7099. }
  7100. previousOffset = nextOffset;
  7101. }
  7102. return Vector2.Zero();
  7103. };
  7104. /**
  7105. * Returns a new Path2 starting at the coordinates (x, y).
  7106. */
  7107. Path2.StartingAt = function (x, y) {
  7108. return new Path2(x, y);
  7109. };
  7110. return Path2;
  7111. }());
  7112. BABYLON.Path2 = Path2;
  7113. var Path3D = /** @class */ (function () {
  7114. /**
  7115. * new Path3D(path, normal, raw)
  7116. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7117. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7118. * path : an array of Vector3, the curve axis of the Path3D
  7119. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7120. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7121. */
  7122. function Path3D(path, firstNormal, raw) {
  7123. if (firstNormal === void 0) { firstNormal = null; }
  7124. this.path = path;
  7125. this._curve = new Array();
  7126. this._distances = new Array();
  7127. this._tangents = new Array();
  7128. this._normals = new Array();
  7129. this._binormals = new Array();
  7130. for (var p = 0; p < path.length; p++) {
  7131. this._curve[p] = path[p].clone(); // hard copy
  7132. }
  7133. this._raw = raw || false;
  7134. this._compute(firstNormal);
  7135. }
  7136. /**
  7137. * Returns the Path3D array of successive Vector3 designing its curve.
  7138. */
  7139. Path3D.prototype.getCurve = function () {
  7140. return this._curve;
  7141. };
  7142. /**
  7143. * Returns an array populated with tangent vectors on each Path3D curve point.
  7144. */
  7145. Path3D.prototype.getTangents = function () {
  7146. return this._tangents;
  7147. };
  7148. /**
  7149. * Returns an array populated with normal vectors on each Path3D curve point.
  7150. */
  7151. Path3D.prototype.getNormals = function () {
  7152. return this._normals;
  7153. };
  7154. /**
  7155. * Returns an array populated with binormal vectors on each Path3D curve point.
  7156. */
  7157. Path3D.prototype.getBinormals = function () {
  7158. return this._binormals;
  7159. };
  7160. /**
  7161. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7162. */
  7163. Path3D.prototype.getDistances = function () {
  7164. return this._distances;
  7165. };
  7166. /**
  7167. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7168. * Returns the same object updated.
  7169. */
  7170. Path3D.prototype.update = function (path, firstNormal) {
  7171. if (firstNormal === void 0) { firstNormal = null; }
  7172. for (var p = 0; p < path.length; p++) {
  7173. this._curve[p].x = path[p].x;
  7174. this._curve[p].y = path[p].y;
  7175. this._curve[p].z = path[p].z;
  7176. }
  7177. this._compute(firstNormal);
  7178. return this;
  7179. };
  7180. // private function compute() : computes tangents, normals and binormals
  7181. Path3D.prototype._compute = function (firstNormal) {
  7182. var l = this._curve.length;
  7183. // first and last tangents
  7184. this._tangents[0] = this._getFirstNonNullVector(0);
  7185. if (!this._raw) {
  7186. this._tangents[0].normalize();
  7187. }
  7188. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7189. if (!this._raw) {
  7190. this._tangents[l - 1].normalize();
  7191. }
  7192. // normals and binormals at first point : arbitrary vector with _normalVector()
  7193. var tg0 = this._tangents[0];
  7194. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7195. this._normals[0] = pp0;
  7196. if (!this._raw) {
  7197. this._normals[0].normalize();
  7198. }
  7199. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7200. if (!this._raw) {
  7201. this._binormals[0].normalize();
  7202. }
  7203. this._distances[0] = 0.0;
  7204. // normals and binormals : next points
  7205. var prev; // previous vector (segment)
  7206. var cur; // current vector (segment)
  7207. var curTang; // current tangent
  7208. // previous normal
  7209. var prevBinor; // previous binormal
  7210. for (var i = 1; i < l; i++) {
  7211. // tangents
  7212. prev = this._getLastNonNullVector(i);
  7213. if (i < l - 1) {
  7214. cur = this._getFirstNonNullVector(i);
  7215. this._tangents[i] = prev.add(cur);
  7216. this._tangents[i].normalize();
  7217. }
  7218. this._distances[i] = this._distances[i - 1] + prev.length();
  7219. // normals and binormals
  7220. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7221. curTang = this._tangents[i];
  7222. prevBinor = this._binormals[i - 1];
  7223. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7224. if (!this._raw) {
  7225. this._normals[i].normalize();
  7226. }
  7227. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7228. if (!this._raw) {
  7229. this._binormals[i].normalize();
  7230. }
  7231. }
  7232. };
  7233. // private function getFirstNonNullVector(index)
  7234. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7235. Path3D.prototype._getFirstNonNullVector = function (index) {
  7236. var i = 1;
  7237. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7238. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7239. i++;
  7240. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7241. }
  7242. return nNVector;
  7243. };
  7244. // private function getLastNonNullVector(index)
  7245. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7246. Path3D.prototype._getLastNonNullVector = function (index) {
  7247. var i = 1;
  7248. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7249. while (nLVector.length() === 0 && index > i + 1) {
  7250. i++;
  7251. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7252. }
  7253. return nLVector;
  7254. };
  7255. // private function normalVector(v0, vt, va) :
  7256. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7257. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7258. Path3D.prototype._normalVector = function (v0, vt, va) {
  7259. var normal0;
  7260. var tgl = vt.length();
  7261. if (tgl === 0.0) {
  7262. tgl = 1.0;
  7263. }
  7264. if (va === undefined || va === null) {
  7265. var point;
  7266. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7267. point = new Vector3(0.0, -1.0, 0.0);
  7268. }
  7269. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7270. point = new Vector3(1.0, 0.0, 0.0);
  7271. }
  7272. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7273. point = new Vector3(0.0, 0.0, 1.0);
  7274. }
  7275. else {
  7276. point = Vector3.Zero();
  7277. }
  7278. normal0 = Vector3.Cross(vt, point);
  7279. }
  7280. else {
  7281. normal0 = Vector3.Cross(vt, va);
  7282. Vector3.CrossToRef(normal0, vt, normal0);
  7283. }
  7284. normal0.normalize();
  7285. return normal0;
  7286. };
  7287. return Path3D;
  7288. }());
  7289. BABYLON.Path3D = Path3D;
  7290. var Curve3 = /** @class */ (function () {
  7291. /**
  7292. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7293. * A Curve3 is designed from a series of successive Vector3.
  7294. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7295. */
  7296. function Curve3(points) {
  7297. this._length = 0.0;
  7298. this._points = points;
  7299. this._length = this._computeLength(points);
  7300. }
  7301. /**
  7302. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7303. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7304. * @param v1 (Vector3) the control point
  7305. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7306. * @param nbPoints (integer) the wanted number of points in the curve
  7307. */
  7308. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7309. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7310. var bez = new Array();
  7311. var equation = function (t, val0, val1, val2) {
  7312. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7313. return res;
  7314. };
  7315. for (var i = 0; i <= nbPoints; i++) {
  7316. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7317. }
  7318. return new Curve3(bez);
  7319. };
  7320. /**
  7321. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7322. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7323. * @param v1 (Vector3) the first control point
  7324. * @param v2 (Vector3) the second control point
  7325. * @param v3 (Vector3) the end point of the Cubic Bezier
  7326. * @param nbPoints (integer) the wanted number of points in the curve
  7327. */
  7328. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7329. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7330. var bez = new Array();
  7331. var equation = function (t, val0, val1, val2, val3) {
  7332. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7333. return res;
  7334. };
  7335. for (var i = 0; i <= nbPoints; i++) {
  7336. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7337. }
  7338. return new Curve3(bez);
  7339. };
  7340. /**
  7341. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7342. * @param p1 (Vector3) the origin point of the Hermite Spline
  7343. * @param t1 (Vector3) the tangent vector at the origin point
  7344. * @param p2 (Vector3) the end point of the Hermite Spline
  7345. * @param t2 (Vector3) the tangent vector at the end point
  7346. * @param nbPoints (integer) the wanted number of points in the curve
  7347. */
  7348. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7349. var hermite = new Array();
  7350. var step = 1.0 / nbPoints;
  7351. for (var i = 0; i <= nbPoints; i++) {
  7352. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7353. }
  7354. return new Curve3(hermite);
  7355. };
  7356. /**
  7357. * Returns a Curve3 object along a CatmullRom Spline curve :
  7358. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7359. * @param nbPoints (integer) the wanted number of points between each curve control points
  7360. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7361. */
  7362. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7363. var catmullRom = new Array();
  7364. var step = 1.0 / nbPoints;
  7365. var amount = 0.0;
  7366. if (closed) {
  7367. var pointsCount = points.length;
  7368. for (var i = 0; i < pointsCount; i++) {
  7369. amount = 0;
  7370. for (var c = 0; c < nbPoints; c++) {
  7371. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7372. amount += step;
  7373. }
  7374. }
  7375. catmullRom.push(catmullRom[0]);
  7376. }
  7377. else {
  7378. var totalPoints = new Array();
  7379. totalPoints.push(points[0].clone());
  7380. Array.prototype.push.apply(totalPoints, points);
  7381. totalPoints.push(points[points.length - 1].clone());
  7382. for (var i = 0; i < totalPoints.length - 3; i++) {
  7383. amount = 0;
  7384. for (var c = 0; c < nbPoints; c++) {
  7385. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7386. amount += step;
  7387. }
  7388. }
  7389. i--;
  7390. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7391. }
  7392. return new Curve3(catmullRom);
  7393. };
  7394. /**
  7395. * Returns the Curve3 stored array of successive Vector3
  7396. */
  7397. Curve3.prototype.getPoints = function () {
  7398. return this._points;
  7399. };
  7400. /**
  7401. * Returns the computed length (float) of the curve.
  7402. */
  7403. Curve3.prototype.length = function () {
  7404. return this._length;
  7405. };
  7406. /**
  7407. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7408. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7409. * curveA and curveB keep unchanged.
  7410. */
  7411. Curve3.prototype.continue = function (curve) {
  7412. var lastPoint = this._points[this._points.length - 1];
  7413. var continuedPoints = this._points.slice();
  7414. var curvePoints = curve.getPoints();
  7415. for (var i = 1; i < curvePoints.length; i++) {
  7416. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7417. }
  7418. var continuedCurve = new Curve3(continuedPoints);
  7419. return continuedCurve;
  7420. };
  7421. Curve3.prototype._computeLength = function (path) {
  7422. var l = 0;
  7423. for (var i = 1; i < path.length; i++) {
  7424. l += (path[i].subtract(path[i - 1])).length();
  7425. }
  7426. return l;
  7427. };
  7428. return Curve3;
  7429. }());
  7430. BABYLON.Curve3 = Curve3;
  7431. // Vertex formats
  7432. var PositionNormalVertex = /** @class */ (function () {
  7433. function PositionNormalVertex(position, normal) {
  7434. if (position === void 0) { position = Vector3.Zero(); }
  7435. if (normal === void 0) { normal = Vector3.Up(); }
  7436. this.position = position;
  7437. this.normal = normal;
  7438. }
  7439. PositionNormalVertex.prototype.clone = function () {
  7440. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7441. };
  7442. return PositionNormalVertex;
  7443. }());
  7444. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7445. var PositionNormalTextureVertex = /** @class */ (function () {
  7446. function PositionNormalTextureVertex(position, normal, uv) {
  7447. if (position === void 0) { position = Vector3.Zero(); }
  7448. if (normal === void 0) { normal = Vector3.Up(); }
  7449. if (uv === void 0) { uv = Vector2.Zero(); }
  7450. this.position = position;
  7451. this.normal = normal;
  7452. this.uv = uv;
  7453. }
  7454. PositionNormalTextureVertex.prototype.clone = function () {
  7455. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7456. };
  7457. return PositionNormalTextureVertex;
  7458. }());
  7459. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7460. // Temporary pre-allocated objects for engine internal use
  7461. // usage in any internal function :
  7462. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7463. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7464. var Tmp = /** @class */ (function () {
  7465. function Tmp() {
  7466. }
  7467. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7468. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7469. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7470. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7471. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7472. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7473. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7474. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7475. Matrix.Zero(), Matrix.Zero(),
  7476. Matrix.Zero(), Matrix.Zero(),
  7477. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7478. return Tmp;
  7479. }());
  7480. BABYLON.Tmp = Tmp;
  7481. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7482. var MathTmp = /** @class */ (function () {
  7483. function MathTmp() {
  7484. }
  7485. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7486. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7487. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7488. return MathTmp;
  7489. }());
  7490. })(BABYLON || (BABYLON = {}));
  7491. //# sourceMappingURL=babylon.math.js.map
  7492. var BABYLON;
  7493. (function (BABYLON) {
  7494. var Scalar = /** @class */ (function () {
  7495. function Scalar() {
  7496. }
  7497. /**
  7498. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7499. */
  7500. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7501. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7502. var num = a - b;
  7503. return -epsilon <= num && num <= epsilon;
  7504. };
  7505. /**
  7506. * Returns a string : the upper case translation of the number i to hexadecimal.
  7507. */
  7508. Scalar.ToHex = function (i) {
  7509. var str = i.toString(16);
  7510. if (i <= 15) {
  7511. return ("0" + str).toUpperCase();
  7512. }
  7513. return str.toUpperCase();
  7514. };
  7515. /**
  7516. * Returns -1 if value is negative and +1 is value is positive.
  7517. * Returns the value itself if it's equal to zero.
  7518. */
  7519. Scalar.Sign = function (value) {
  7520. value = +value; // convert to a number
  7521. if (value === 0 || isNaN(value))
  7522. return value;
  7523. return value > 0 ? 1 : -1;
  7524. };
  7525. /**
  7526. * Returns the value itself if it's between min and max.
  7527. * Returns min if the value is lower than min.
  7528. * Returns max if the value is greater than max.
  7529. */
  7530. Scalar.Clamp = function (value, min, max) {
  7531. if (min === void 0) { min = 0; }
  7532. if (max === void 0) { max = 1; }
  7533. return Math.min(max, Math.max(min, value));
  7534. };
  7535. /**
  7536. * Returns the log2 of value.
  7537. */
  7538. Scalar.Log2 = function (value) {
  7539. return Math.log(value) * Math.LOG2E;
  7540. };
  7541. /**
  7542. * Loops the value, so that it is never larger than length and never smaller than 0.
  7543. *
  7544. * This is similar to the modulo operator but it works with floating point numbers.
  7545. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7546. * With t = 5 and length = 2.5, the result would be 0.0.
  7547. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7548. */
  7549. Scalar.Repeat = function (value, length) {
  7550. return value - Math.floor(value / length) * length;
  7551. };
  7552. /**
  7553. * Normalize the value between 0.0 and 1.0 using min and max values
  7554. */
  7555. Scalar.Normalize = function (value, min, max) {
  7556. return (value - min) / (max - min);
  7557. };
  7558. /**
  7559. * Denormalize the value from 0.0 and 1.0 using min and max values
  7560. */
  7561. Scalar.Denormalize = function (normalized, min, max) {
  7562. return (normalized * (max - min) + min);
  7563. };
  7564. /**
  7565. * Calculates the shortest difference between two given angles given in degrees.
  7566. */
  7567. Scalar.DeltaAngle = function (current, target) {
  7568. var num = Scalar.Repeat(target - current, 360.0);
  7569. if (num > 180.0) {
  7570. num -= 360.0;
  7571. }
  7572. return num;
  7573. };
  7574. /**
  7575. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7576. *
  7577. * The returned value will move back and forth between 0 and length
  7578. */
  7579. Scalar.PingPong = function (tx, length) {
  7580. var t = Scalar.Repeat(tx, length * 2.0);
  7581. return length - Math.abs(t - length);
  7582. };
  7583. /**
  7584. * Interpolates between min and max with smoothing at the limits.
  7585. *
  7586. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7587. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7588. */
  7589. Scalar.SmoothStep = function (from, to, tx) {
  7590. var t = Scalar.Clamp(tx);
  7591. t = -2.0 * t * t * t + 3.0 * t * t;
  7592. return to * t + from * (1.0 - t);
  7593. };
  7594. /**
  7595. * Moves a value current towards target.
  7596. *
  7597. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7598. * Negative values of maxDelta pushes the value away from target.
  7599. */
  7600. Scalar.MoveTowards = function (current, target, maxDelta) {
  7601. var result = 0;
  7602. if (Math.abs(target - current) <= maxDelta) {
  7603. result = target;
  7604. }
  7605. else {
  7606. result = current + Scalar.Sign(target - current) * maxDelta;
  7607. }
  7608. return result;
  7609. };
  7610. /**
  7611. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7612. *
  7613. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7614. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7615. */
  7616. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7617. var num = Scalar.DeltaAngle(current, target);
  7618. var result = 0;
  7619. if (-maxDelta < num && num < maxDelta) {
  7620. result = target;
  7621. }
  7622. else {
  7623. target = current + num;
  7624. result = Scalar.MoveTowards(current, target, maxDelta);
  7625. }
  7626. return result;
  7627. };
  7628. /**
  7629. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7630. */
  7631. Scalar.Lerp = function (start, end, amount) {
  7632. return start + ((end - start) * amount);
  7633. };
  7634. /**
  7635. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7636. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7637. */
  7638. Scalar.LerpAngle = function (start, end, amount) {
  7639. var num = Scalar.Repeat(end - start, 360.0);
  7640. if (num > 180.0) {
  7641. num -= 360.0;
  7642. }
  7643. return start + num * Scalar.Clamp(amount);
  7644. };
  7645. /**
  7646. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7647. */
  7648. Scalar.InverseLerp = function (a, b, value) {
  7649. var result = 0;
  7650. if (a != b) {
  7651. result = Scalar.Clamp((value - a) / (b - a));
  7652. }
  7653. else {
  7654. result = 0.0;
  7655. }
  7656. return result;
  7657. };
  7658. /**
  7659. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7660. */
  7661. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7662. var squared = amount * amount;
  7663. var cubed = amount * squared;
  7664. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7665. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7666. var part3 = (cubed - (2.0 * squared)) + amount;
  7667. var part4 = cubed - squared;
  7668. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7669. };
  7670. /**
  7671. * Returns a random float number between and min and max values
  7672. */
  7673. Scalar.RandomRange = function (min, max) {
  7674. if (min === max)
  7675. return min;
  7676. return ((Math.random() * (max - min)) + min);
  7677. };
  7678. /**
  7679. * This function returns percentage of a number in a given range.
  7680. *
  7681. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7682. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7683. */
  7684. Scalar.RangeToPercent = function (number, min, max) {
  7685. return ((number - min) / (max - min));
  7686. };
  7687. /**
  7688. * This function returns number that corresponds to the percentage in a given range.
  7689. *
  7690. * PercentToRange(0.34,0,100) will return 34.
  7691. */
  7692. Scalar.PercentToRange = function (percent, min, max) {
  7693. return ((max - min) * percent + min);
  7694. };
  7695. /**
  7696. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7697. * @param angle The angle to normalize in radian.
  7698. * @return The converted angle.
  7699. */
  7700. Scalar.NormalizeRadians = function (angle) {
  7701. // More precise but slower version kept for reference.
  7702. // angle = angle % Tools.TwoPi;
  7703. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7704. //if (angle > Math.PI) {
  7705. // angle -= Tools.TwoPi;
  7706. //}
  7707. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7708. return angle;
  7709. };
  7710. /**
  7711. * Two pi constants convenient for computation.
  7712. */
  7713. Scalar.TwoPi = Math.PI * 2;
  7714. return Scalar;
  7715. }());
  7716. BABYLON.Scalar = Scalar;
  7717. })(BABYLON || (BABYLON = {}));
  7718. //# sourceMappingURL=babylon.math.scalar.js.map
  7719. //# sourceMappingURL=babylon.mixins.js.map
  7720. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7721. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7722. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7723. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7724. //# sourceMappingURL=babylon.webgl2.js.map
  7725. var BABYLON;
  7726. (function (BABYLON) {
  7727. var __decoratorInitialStore = {};
  7728. var __mergedStore = {};
  7729. var _copySource = function (creationFunction, source, instanciate) {
  7730. var destination = creationFunction();
  7731. // Tags
  7732. if (BABYLON.Tags) {
  7733. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7734. }
  7735. var classStore = getMergedStore(destination);
  7736. // Properties
  7737. for (var property in classStore) {
  7738. var propertyDescriptor = classStore[property];
  7739. var sourceProperty = source[property];
  7740. var propertyType = propertyDescriptor.type;
  7741. if (sourceProperty !== undefined && sourceProperty !== null) {
  7742. switch (propertyType) {
  7743. case 0: // Value
  7744. case 6: // Mesh reference
  7745. case 11: // Camera reference
  7746. destination[property] = sourceProperty;
  7747. break;
  7748. case 1: // Texture
  7749. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7750. break;
  7751. case 2: // Color3
  7752. case 3: // FresnelParameters
  7753. case 4: // Vector2
  7754. case 5: // Vector3
  7755. case 7: // Color Curves
  7756. case 10: // Quaternion
  7757. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7758. break;
  7759. }
  7760. }
  7761. }
  7762. return destination;
  7763. };
  7764. function getDirectStore(target) {
  7765. var classKey = target.getClassName();
  7766. if (!__decoratorInitialStore[classKey]) {
  7767. __decoratorInitialStore[classKey] = {};
  7768. }
  7769. return __decoratorInitialStore[classKey];
  7770. }
  7771. /**
  7772. * Return the list of properties flagged as serializable
  7773. * @param target: host object
  7774. */
  7775. function getMergedStore(target) {
  7776. var classKey = target.getClassName();
  7777. if (__mergedStore[classKey]) {
  7778. return __mergedStore[classKey];
  7779. }
  7780. __mergedStore[classKey] = {};
  7781. var store = __mergedStore[classKey];
  7782. var currentTarget = target;
  7783. var currentKey = classKey;
  7784. while (currentKey) {
  7785. var initialStore = __decoratorInitialStore[currentKey];
  7786. for (var property in initialStore) {
  7787. store[property] = initialStore[property];
  7788. }
  7789. var parent_1 = void 0;
  7790. var done = false;
  7791. do {
  7792. parent_1 = Object.getPrototypeOf(currentTarget);
  7793. if (!parent_1.getClassName) {
  7794. done = true;
  7795. break;
  7796. }
  7797. if (parent_1.getClassName() !== currentKey) {
  7798. break;
  7799. }
  7800. currentTarget = parent_1;
  7801. } while (parent_1);
  7802. if (done) {
  7803. break;
  7804. }
  7805. currentKey = parent_1.getClassName();
  7806. currentTarget = parent_1;
  7807. }
  7808. return store;
  7809. }
  7810. function generateSerializableMember(type, sourceName) {
  7811. return function (target, propertyKey) {
  7812. var classStore = getDirectStore(target);
  7813. if (!classStore[propertyKey]) {
  7814. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7815. }
  7816. };
  7817. }
  7818. function generateExpandMember(setCallback, targetKey) {
  7819. if (targetKey === void 0) { targetKey = null; }
  7820. return function (target, propertyKey) {
  7821. var key = targetKey || ("_" + propertyKey);
  7822. Object.defineProperty(target, propertyKey, {
  7823. get: function () {
  7824. return this[key];
  7825. },
  7826. set: function (value) {
  7827. if (this[key] === value) {
  7828. return;
  7829. }
  7830. this[key] = value;
  7831. target[setCallback].apply(this);
  7832. },
  7833. enumerable: true,
  7834. configurable: true
  7835. });
  7836. };
  7837. }
  7838. function expandToProperty(callback, targetKey) {
  7839. if (targetKey === void 0) { targetKey = null; }
  7840. return generateExpandMember(callback, targetKey);
  7841. }
  7842. BABYLON.expandToProperty = expandToProperty;
  7843. function serialize(sourceName) {
  7844. return generateSerializableMember(0, sourceName); // value member
  7845. }
  7846. BABYLON.serialize = serialize;
  7847. function serializeAsTexture(sourceName) {
  7848. return generateSerializableMember(1, sourceName); // texture member
  7849. }
  7850. BABYLON.serializeAsTexture = serializeAsTexture;
  7851. function serializeAsColor3(sourceName) {
  7852. return generateSerializableMember(2, sourceName); // color3 member
  7853. }
  7854. BABYLON.serializeAsColor3 = serializeAsColor3;
  7855. function serializeAsFresnelParameters(sourceName) {
  7856. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7857. }
  7858. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7859. function serializeAsVector2(sourceName) {
  7860. return generateSerializableMember(4, sourceName); // vector2 member
  7861. }
  7862. BABYLON.serializeAsVector2 = serializeAsVector2;
  7863. function serializeAsVector3(sourceName) {
  7864. return generateSerializableMember(5, sourceName); // vector3 member
  7865. }
  7866. BABYLON.serializeAsVector3 = serializeAsVector3;
  7867. function serializeAsMeshReference(sourceName) {
  7868. return generateSerializableMember(6, sourceName); // mesh reference member
  7869. }
  7870. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7871. function serializeAsColorCurves(sourceName) {
  7872. return generateSerializableMember(7, sourceName); // color curves
  7873. }
  7874. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7875. function serializeAsColor4(sourceName) {
  7876. return generateSerializableMember(8, sourceName); // color 4
  7877. }
  7878. BABYLON.serializeAsColor4 = serializeAsColor4;
  7879. function serializeAsImageProcessingConfiguration(sourceName) {
  7880. return generateSerializableMember(9, sourceName); // image processing
  7881. }
  7882. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7883. function serializeAsQuaternion(sourceName) {
  7884. return generateSerializableMember(10, sourceName); // quaternion member
  7885. }
  7886. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7887. /**
  7888. * Decorator used to define property that can be serialized as reference to a camera
  7889. * @param sourceName defines the name of the property to decorate
  7890. */
  7891. function serializeAsCameraReference(sourceName) {
  7892. return generateSerializableMember(11, sourceName); // camera reference member
  7893. }
  7894. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7895. var SerializationHelper = /** @class */ (function () {
  7896. function SerializationHelper() {
  7897. }
  7898. SerializationHelper.Serialize = function (entity, serializationObject) {
  7899. if (!serializationObject) {
  7900. serializationObject = {};
  7901. }
  7902. // Tags
  7903. if (BABYLON.Tags) {
  7904. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7905. }
  7906. var serializedProperties = getMergedStore(entity);
  7907. // Properties
  7908. for (var property in serializedProperties) {
  7909. var propertyDescriptor = serializedProperties[property];
  7910. var targetPropertyName = propertyDescriptor.sourceName || property;
  7911. var propertyType = propertyDescriptor.type;
  7912. var sourceProperty = entity[property];
  7913. if (sourceProperty !== undefined && sourceProperty !== null) {
  7914. switch (propertyType) {
  7915. case 0: // Value
  7916. serializationObject[targetPropertyName] = sourceProperty;
  7917. break;
  7918. case 1: // Texture
  7919. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7920. break;
  7921. case 2: // Color3
  7922. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7923. break;
  7924. case 3: // FresnelParameters
  7925. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7926. break;
  7927. case 4: // Vector2
  7928. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7929. break;
  7930. case 5: // Vector3
  7931. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7932. break;
  7933. case 6: // Mesh reference
  7934. serializationObject[targetPropertyName] = sourceProperty.id;
  7935. break;
  7936. case 7: // Color Curves
  7937. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7938. break;
  7939. case 8: // Color 4
  7940. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7941. break;
  7942. case 9: // Image Processing
  7943. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7944. break;
  7945. case 10: // Quaternion
  7946. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7947. break;
  7948. case 11: // Camera reference
  7949. serializationObject[targetPropertyName] = sourceProperty.id;
  7950. break;
  7951. }
  7952. }
  7953. }
  7954. return serializationObject;
  7955. };
  7956. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7957. if (rootUrl === void 0) { rootUrl = null; }
  7958. var destination = creationFunction();
  7959. if (!rootUrl) {
  7960. rootUrl = "";
  7961. }
  7962. // Tags
  7963. if (BABYLON.Tags) {
  7964. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7965. }
  7966. var classStore = getMergedStore(destination);
  7967. // Properties
  7968. for (var property in classStore) {
  7969. var propertyDescriptor = classStore[property];
  7970. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7971. var propertyType = propertyDescriptor.type;
  7972. if (sourceProperty !== undefined && sourceProperty !== null) {
  7973. var dest = destination;
  7974. switch (propertyType) {
  7975. case 0: // Value
  7976. dest[property] = sourceProperty;
  7977. break;
  7978. case 1: // Texture
  7979. if (scene) {
  7980. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7981. }
  7982. break;
  7983. case 2: // Color3
  7984. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7985. break;
  7986. case 3: // FresnelParameters
  7987. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7988. break;
  7989. case 4: // Vector2
  7990. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7991. break;
  7992. case 5: // Vector3
  7993. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7994. break;
  7995. case 6: // Mesh reference
  7996. if (scene) {
  7997. dest[property] = scene.getLastMeshByID(sourceProperty);
  7998. }
  7999. break;
  8000. case 7: // Color Curves
  8001. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8002. break;
  8003. case 8: // Color 4
  8004. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8005. break;
  8006. case 9: // Image Processing
  8007. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8008. break;
  8009. case 10: // Quaternion
  8010. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8011. break;
  8012. case 11: // Camera reference
  8013. if (scene) {
  8014. dest[property] = scene.getCameraByID(sourceProperty);
  8015. }
  8016. break;
  8017. }
  8018. }
  8019. }
  8020. return destination;
  8021. };
  8022. SerializationHelper.Clone = function (creationFunction, source) {
  8023. return _copySource(creationFunction, source, false);
  8024. };
  8025. SerializationHelper.Instanciate = function (creationFunction, source) {
  8026. return _copySource(creationFunction, source, true);
  8027. };
  8028. return SerializationHelper;
  8029. }());
  8030. BABYLON.SerializationHelper = SerializationHelper;
  8031. })(BABYLON || (BABYLON = {}));
  8032. //# sourceMappingURL=babylon.decorators.js.map
  8033. var BABYLON;
  8034. (function (BABYLON) {
  8035. /**
  8036. * Wrapper class for promise with external resolve and reject.
  8037. */
  8038. var Deferred = /** @class */ (function () {
  8039. /**
  8040. * Constructor for this deferred object.
  8041. */
  8042. function Deferred() {
  8043. var _this = this;
  8044. this.promise = new Promise(function (resolve, reject) {
  8045. _this._resolve = resolve;
  8046. _this._reject = reject;
  8047. });
  8048. }
  8049. Object.defineProperty(Deferred.prototype, "resolve", {
  8050. /**
  8051. * The resolve method of the promise associated with this deferred object.
  8052. */
  8053. get: function () {
  8054. return this._resolve;
  8055. },
  8056. enumerable: true,
  8057. configurable: true
  8058. });
  8059. Object.defineProperty(Deferred.prototype, "reject", {
  8060. /**
  8061. * The reject method of the promise associated with this deferred object.
  8062. */
  8063. get: function () {
  8064. return this._reject;
  8065. },
  8066. enumerable: true,
  8067. configurable: true
  8068. });
  8069. return Deferred;
  8070. }());
  8071. BABYLON.Deferred = Deferred;
  8072. })(BABYLON || (BABYLON = {}));
  8073. //# sourceMappingURL=babylon.deferred.js.map
  8074. var BABYLON;
  8075. (function (BABYLON) {
  8076. /**
  8077. * A class serves as a medium between the observable and its observers
  8078. */
  8079. var EventState = /** @class */ (function () {
  8080. /**
  8081. * Create a new EventState
  8082. * @param mask defines the mask associated with this state
  8083. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8084. * @param target defines the original target of the state
  8085. * @param currentTarget defines the current target of the state
  8086. */
  8087. function EventState(mask, skipNextObservers, target, currentTarget) {
  8088. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8089. this.initalize(mask, skipNextObservers, target, currentTarget);
  8090. }
  8091. /**
  8092. * Initialize the current event state
  8093. * @param mask defines the mask associated with this state
  8094. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8095. * @param target defines the original target of the state
  8096. * @param currentTarget defines the current target of the state
  8097. * @returns the current event state
  8098. */
  8099. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8100. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8101. this.mask = mask;
  8102. this.skipNextObservers = skipNextObservers;
  8103. this.target = target;
  8104. this.currentTarget = currentTarget;
  8105. return this;
  8106. };
  8107. return EventState;
  8108. }());
  8109. BABYLON.EventState = EventState;
  8110. /**
  8111. * Represent an Observer registered to a given Observable object.
  8112. */
  8113. var Observer = /** @class */ (function () {
  8114. /**
  8115. * Creates a new observer
  8116. * @param callback defines the callback to call when the observer is notified
  8117. * @param mask defines the mask of the observer (used to filter notifications)
  8118. * @param scope defines the current scope used to restore the JS context
  8119. */
  8120. function Observer(
  8121. /**
  8122. * Defines the callback to call when the observer is notified
  8123. */
  8124. callback,
  8125. /**
  8126. * Defines the mask of the observer (used to filter notifications)
  8127. */
  8128. mask,
  8129. /**
  8130. * Defines the current scope used to restore the JS context
  8131. */
  8132. scope) {
  8133. if (scope === void 0) { scope = null; }
  8134. this.callback = callback;
  8135. this.mask = mask;
  8136. this.scope = scope;
  8137. /** @hidden */
  8138. this._willBeUnregistered = false;
  8139. /**
  8140. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8141. */
  8142. this.unregisterOnNextCall = false;
  8143. }
  8144. return Observer;
  8145. }());
  8146. BABYLON.Observer = Observer;
  8147. /**
  8148. * Represent a list of observers registered to multiple Observables object.
  8149. */
  8150. var MultiObserver = /** @class */ (function () {
  8151. function MultiObserver() {
  8152. }
  8153. /**
  8154. * Release associated resources
  8155. */
  8156. MultiObserver.prototype.dispose = function () {
  8157. if (this._observers && this._observables) {
  8158. for (var index = 0; index < this._observers.length; index++) {
  8159. this._observables[index].remove(this._observers[index]);
  8160. }
  8161. }
  8162. this._observers = null;
  8163. this._observables = null;
  8164. };
  8165. /**
  8166. * Raise a callback when one of the observable will notify
  8167. * @param observables defines a list of observables to watch
  8168. * @param callback defines the callback to call on notification
  8169. * @param mask defines the mask used to filter notifications
  8170. * @param scope defines the current scope used to restore the JS context
  8171. * @returns the new MultiObserver
  8172. */
  8173. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8174. if (mask === void 0) { mask = -1; }
  8175. if (scope === void 0) { scope = null; }
  8176. var result = new MultiObserver();
  8177. result._observers = new Array();
  8178. result._observables = observables;
  8179. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8180. var observable = observables_1[_i];
  8181. var observer = observable.add(callback, mask, false, scope);
  8182. if (observer) {
  8183. result._observers.push(observer);
  8184. }
  8185. }
  8186. return result;
  8187. };
  8188. return MultiObserver;
  8189. }());
  8190. BABYLON.MultiObserver = MultiObserver;
  8191. /**
  8192. * The Observable class is a simple implementation of the Observable pattern.
  8193. *
  8194. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8195. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8196. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8197. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8198. */
  8199. var Observable = /** @class */ (function () {
  8200. /**
  8201. * Creates a new observable
  8202. * @param onObserverAdded defines a callback to call when a new observer is added
  8203. */
  8204. function Observable(onObserverAdded) {
  8205. this._observers = new Array();
  8206. this._eventState = new EventState(0);
  8207. if (onObserverAdded) {
  8208. this._onObserverAdded = onObserverAdded;
  8209. }
  8210. }
  8211. /**
  8212. * Create a new Observer with the specified callback
  8213. * @param callback the callback that will be executed for that Observer
  8214. * @param mask the mask used to filter observers
  8215. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8216. * @param scope optional scope for the callback to be called from
  8217. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8218. * @returns the new observer created for the callback
  8219. */
  8220. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8221. if (mask === void 0) { mask = -1; }
  8222. if (insertFirst === void 0) { insertFirst = false; }
  8223. if (scope === void 0) { scope = null; }
  8224. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8225. if (!callback) {
  8226. return null;
  8227. }
  8228. var observer = new Observer(callback, mask, scope);
  8229. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8230. if (insertFirst) {
  8231. this._observers.unshift(observer);
  8232. }
  8233. else {
  8234. this._observers.push(observer);
  8235. }
  8236. if (this._onObserverAdded) {
  8237. this._onObserverAdded(observer);
  8238. }
  8239. return observer;
  8240. };
  8241. /**
  8242. * Create a new Observer with the specified callback and unregisters after the next notification
  8243. * @param callback the callback that will be executed for that Observer
  8244. * @returns the new observer created for the callback
  8245. */
  8246. Observable.prototype.addOnce = function (callback) {
  8247. return this.add(callback, undefined, undefined, undefined, true);
  8248. };
  8249. /**
  8250. * Remove an Observer from the Observable object
  8251. * @param observer the instance of the Observer to remove
  8252. * @returns false if it doesn't belong to this Observable
  8253. */
  8254. Observable.prototype.remove = function (observer) {
  8255. if (!observer) {
  8256. return false;
  8257. }
  8258. var index = this._observers.indexOf(observer);
  8259. if (index !== -1) {
  8260. this._deferUnregister(observer);
  8261. return true;
  8262. }
  8263. return false;
  8264. };
  8265. /**
  8266. * Remove a callback from the Observable object
  8267. * @param callback the callback to remove
  8268. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8269. * @returns false if it doesn't belong to this Observable
  8270. */
  8271. Observable.prototype.removeCallback = function (callback, scope) {
  8272. for (var index = 0; index < this._observers.length; index++) {
  8273. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8274. this._deferUnregister(this._observers[index]);
  8275. return true;
  8276. }
  8277. }
  8278. return false;
  8279. };
  8280. Observable.prototype._deferUnregister = function (observer) {
  8281. var _this = this;
  8282. observer.unregisterOnNextCall = false;
  8283. observer._willBeUnregistered = true;
  8284. BABYLON.Tools.SetImmediate(function () {
  8285. _this._remove(observer);
  8286. });
  8287. };
  8288. // This should only be called when not iterating over _observers to avoid callback skipping.
  8289. // Removes an observer from the _observer Array.
  8290. Observable.prototype._remove = function (observer) {
  8291. if (!observer) {
  8292. return false;
  8293. }
  8294. var index = this._observers.indexOf(observer);
  8295. if (index !== -1) {
  8296. this._observers.splice(index, 1);
  8297. return true;
  8298. }
  8299. return false;
  8300. };
  8301. /**
  8302. * Notify all Observers by calling their respective callback with the given data
  8303. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8304. * @param eventData defines the data to send to all observers
  8305. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8306. * @param target defines the original target of the state
  8307. * @param currentTarget defines the current target of the state
  8308. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8309. */
  8310. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8311. if (mask === void 0) { mask = -1; }
  8312. if (!this._observers.length) {
  8313. return true;
  8314. }
  8315. var state = this._eventState;
  8316. state.mask = mask;
  8317. state.target = target;
  8318. state.currentTarget = currentTarget;
  8319. state.skipNextObservers = false;
  8320. state.lastReturnValue = eventData;
  8321. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8322. var obs = _a[_i];
  8323. if (obs._willBeUnregistered) {
  8324. continue;
  8325. }
  8326. if (obs.mask & mask) {
  8327. if (obs.scope) {
  8328. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8329. }
  8330. else {
  8331. state.lastReturnValue = obs.callback(eventData, state);
  8332. }
  8333. if (obs.unregisterOnNextCall) {
  8334. this._deferUnregister(obs);
  8335. }
  8336. }
  8337. if (state.skipNextObservers) {
  8338. return false;
  8339. }
  8340. }
  8341. return true;
  8342. };
  8343. /**
  8344. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8345. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8346. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8347. * and it is crucial that all callbacks will be executed.
  8348. * The order of the callbacks is kept, callbacks are not executed parallel.
  8349. *
  8350. * @param eventData The data to be sent to each callback
  8351. * @param mask is used to filter observers defaults to -1
  8352. * @param target defines the callback target (see EventState)
  8353. * @param currentTarget defines he current object in the bubbling phase
  8354. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8355. */
  8356. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8357. var _this = this;
  8358. if (mask === void 0) { mask = -1; }
  8359. // create an empty promise
  8360. var p = Promise.resolve(eventData);
  8361. // no observers? return this promise.
  8362. if (!this._observers.length) {
  8363. return p;
  8364. }
  8365. var state = this._eventState;
  8366. state.mask = mask;
  8367. state.target = target;
  8368. state.currentTarget = currentTarget;
  8369. state.skipNextObservers = false;
  8370. // execute one callback after another (not using Promise.all, the order is important)
  8371. this._observers.forEach(function (obs) {
  8372. if (state.skipNextObservers) {
  8373. return;
  8374. }
  8375. if (obs._willBeUnregistered) {
  8376. return;
  8377. }
  8378. if (obs.mask & mask) {
  8379. if (obs.scope) {
  8380. p = p.then(function (lastReturnedValue) {
  8381. state.lastReturnValue = lastReturnedValue;
  8382. return obs.callback.apply(obs.scope, [eventData, state]);
  8383. });
  8384. }
  8385. else {
  8386. p = p.then(function (lastReturnedValue) {
  8387. state.lastReturnValue = lastReturnedValue;
  8388. return obs.callback(eventData, state);
  8389. });
  8390. }
  8391. if (obs.unregisterOnNextCall) {
  8392. _this._deferUnregister(obs);
  8393. }
  8394. }
  8395. });
  8396. // return the eventData
  8397. return p.then(function () { return eventData; });
  8398. };
  8399. /**
  8400. * Notify a specific observer
  8401. * @param observer defines the observer to notify
  8402. * @param eventData defines the data to be sent to each callback
  8403. * @param mask is used to filter observers defaults to -1
  8404. */
  8405. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8406. if (mask === void 0) { mask = -1; }
  8407. var state = this._eventState;
  8408. state.mask = mask;
  8409. state.skipNextObservers = false;
  8410. observer.callback(eventData, state);
  8411. };
  8412. /**
  8413. * Gets a boolean indicating if the observable has at least one observer
  8414. * @returns true is the Observable has at least one Observer registered
  8415. */
  8416. Observable.prototype.hasObservers = function () {
  8417. return this._observers.length > 0;
  8418. };
  8419. /**
  8420. * Clear the list of observers
  8421. */
  8422. Observable.prototype.clear = function () {
  8423. this._observers = new Array();
  8424. this._onObserverAdded = null;
  8425. };
  8426. /**
  8427. * Clone the current observable
  8428. * @returns a new observable
  8429. */
  8430. Observable.prototype.clone = function () {
  8431. var result = new Observable();
  8432. result._observers = this._observers.slice(0);
  8433. return result;
  8434. };
  8435. /**
  8436. * Does this observable handles observer registered with a given mask
  8437. * @param mask defines the mask to be tested
  8438. * @return whether or not one observer registered with the given mask is handeled
  8439. **/
  8440. Observable.prototype.hasSpecificMask = function (mask) {
  8441. if (mask === void 0) { mask = -1; }
  8442. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8443. var obs = _a[_i];
  8444. if (obs.mask & mask || obs.mask === mask) {
  8445. return true;
  8446. }
  8447. }
  8448. return false;
  8449. };
  8450. return Observable;
  8451. }());
  8452. BABYLON.Observable = Observable;
  8453. })(BABYLON || (BABYLON = {}));
  8454. //# sourceMappingURL=babylon.observable.js.map
  8455. var BABYLON;
  8456. (function (BABYLON) {
  8457. var SmartArray = /** @class */ (function () {
  8458. function SmartArray(capacity) {
  8459. this.length = 0;
  8460. this.data = new Array(capacity);
  8461. this._id = SmartArray._GlobalId++;
  8462. }
  8463. SmartArray.prototype.push = function (value) {
  8464. this.data[this.length++] = value;
  8465. if (this.length > this.data.length) {
  8466. this.data.length *= 2;
  8467. }
  8468. };
  8469. SmartArray.prototype.forEach = function (func) {
  8470. for (var index = 0; index < this.length; index++) {
  8471. func(this.data[index]);
  8472. }
  8473. };
  8474. SmartArray.prototype.sort = function (compareFn) {
  8475. this.data.sort(compareFn);
  8476. };
  8477. SmartArray.prototype.reset = function () {
  8478. this.length = 0;
  8479. };
  8480. SmartArray.prototype.dispose = function () {
  8481. this.reset();
  8482. if (this.data) {
  8483. this.data.length = 0;
  8484. this.data = [];
  8485. }
  8486. };
  8487. SmartArray.prototype.concat = function (array) {
  8488. if (array.length === 0) {
  8489. return;
  8490. }
  8491. if (this.length + array.length > this.data.length) {
  8492. this.data.length = (this.length + array.length) * 2;
  8493. }
  8494. for (var index = 0; index < array.length; index++) {
  8495. this.data[this.length++] = (array.data || array)[index];
  8496. }
  8497. };
  8498. SmartArray.prototype.indexOf = function (value) {
  8499. var position = this.data.indexOf(value);
  8500. if (position >= this.length) {
  8501. return -1;
  8502. }
  8503. return position;
  8504. };
  8505. SmartArray.prototype.contains = function (value) {
  8506. return this.data.indexOf(value) !== -1;
  8507. };
  8508. // Statics
  8509. SmartArray._GlobalId = 0;
  8510. return SmartArray;
  8511. }());
  8512. BABYLON.SmartArray = SmartArray;
  8513. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8514. __extends(SmartArrayNoDuplicate, _super);
  8515. function SmartArrayNoDuplicate() {
  8516. var _this = _super !== null && _super.apply(this, arguments) || this;
  8517. _this._duplicateId = 0;
  8518. return _this;
  8519. }
  8520. SmartArrayNoDuplicate.prototype.push = function (value) {
  8521. _super.prototype.push.call(this, value);
  8522. if (!value.__smartArrayFlags) {
  8523. value.__smartArrayFlags = {};
  8524. }
  8525. value.__smartArrayFlags[this._id] = this._duplicateId;
  8526. };
  8527. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8528. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8529. return false;
  8530. }
  8531. this.push(value);
  8532. return true;
  8533. };
  8534. SmartArrayNoDuplicate.prototype.reset = function () {
  8535. _super.prototype.reset.call(this);
  8536. this._duplicateId++;
  8537. };
  8538. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8539. if (array.length === 0) {
  8540. return;
  8541. }
  8542. if (this.length + array.length > this.data.length) {
  8543. this.data.length = (this.length + array.length) * 2;
  8544. }
  8545. for (var index = 0; index < array.length; index++) {
  8546. var item = (array.data || array)[index];
  8547. this.pushNoDuplicate(item);
  8548. }
  8549. };
  8550. return SmartArrayNoDuplicate;
  8551. }(SmartArray));
  8552. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8553. })(BABYLON || (BABYLON = {}));
  8554. //# sourceMappingURL=babylon.smartArray.js.map
  8555. var BABYLON;
  8556. (function (BABYLON) {
  8557. /** Class used to store color gradient */
  8558. var ColorGradient = /** @class */ (function () {
  8559. function ColorGradient() {
  8560. }
  8561. /**
  8562. * Will get a color picked randomly between color1 and color2.
  8563. * If color2 is undefined then color1 will be used
  8564. * @param result defines the target Color4 to store the result in
  8565. */
  8566. ColorGradient.prototype.getColorToRef = function (result) {
  8567. if (!this.color2) {
  8568. result.copyFrom(this.color1);
  8569. return;
  8570. }
  8571. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8572. };
  8573. return ColorGradient;
  8574. }());
  8575. BABYLON.ColorGradient = ColorGradient;
  8576. /** Class used to store factor gradient */
  8577. var FactorGradient = /** @class */ (function () {
  8578. function FactorGradient() {
  8579. }
  8580. /**
  8581. * Will get a number picked randomly between factor1 and factor2.
  8582. * If factor2 is undefined then factor1 will be used
  8583. * @returns the picked number
  8584. */
  8585. FactorGradient.prototype.getFactor = function () {
  8586. if (this.factor2 === undefined) {
  8587. return this.factor1;
  8588. }
  8589. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8590. };
  8591. return FactorGradient;
  8592. }());
  8593. BABYLON.FactorGradient = FactorGradient;
  8594. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8595. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8596. var LoadFileError = /** @class */ (function (_super) {
  8597. __extends(LoadFileError, _super);
  8598. function LoadFileError(message, request) {
  8599. var _this = _super.call(this, message) || this;
  8600. _this.request = request;
  8601. _this.name = "LoadFileError";
  8602. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8603. return _this;
  8604. }
  8605. // Polyfill for Object.setPrototypeOf if necessary.
  8606. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8607. return LoadFileError;
  8608. }(Error));
  8609. BABYLON.LoadFileError = LoadFileError;
  8610. var RetryStrategy = /** @class */ (function () {
  8611. function RetryStrategy() {
  8612. }
  8613. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8614. if (maxRetries === void 0) { maxRetries = 3; }
  8615. if (baseInterval === void 0) { baseInterval = 500; }
  8616. return function (url, request, retryIndex) {
  8617. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8618. return -1;
  8619. }
  8620. return Math.pow(2, retryIndex) * baseInterval;
  8621. };
  8622. };
  8623. return RetryStrategy;
  8624. }());
  8625. BABYLON.RetryStrategy = RetryStrategy;
  8626. // Screenshots
  8627. var screenshotCanvas;
  8628. var cloneValue = function (source, destinationObject) {
  8629. if (!source)
  8630. return null;
  8631. if (source instanceof BABYLON.Mesh) {
  8632. return null;
  8633. }
  8634. if (source instanceof BABYLON.SubMesh) {
  8635. return source.clone(destinationObject);
  8636. }
  8637. else if (source.clone) {
  8638. return source.clone();
  8639. }
  8640. return null;
  8641. };
  8642. var Tools = /** @class */ (function () {
  8643. function Tools() {
  8644. }
  8645. /**
  8646. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8647. * @param u defines the coordinate on X axis
  8648. * @param v defines the coordinate on Y axis
  8649. * @param width defines the width of the source data
  8650. * @param height defines the height of the source data
  8651. * @param pixels defines the source byte array
  8652. * @param color defines the output color
  8653. */
  8654. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8655. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8656. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8657. var position = (wrappedU + wrappedV * width) * 4;
  8658. color.r = pixels[position] / 255;
  8659. color.g = pixels[position + 1] / 255;
  8660. color.b = pixels[position + 2] / 255;
  8661. color.a = pixels[position + 3] / 255;
  8662. };
  8663. /**
  8664. * Interpolates between a and b via alpha
  8665. * @param a The lower value (returned when alpha = 0)
  8666. * @param b The upper value (returned when alpha = 1)
  8667. * @param alpha The interpolation-factor
  8668. * @return The mixed value
  8669. */
  8670. Tools.Mix = function (a, b, alpha) {
  8671. return a * (1 - alpha) + b * alpha;
  8672. };
  8673. Tools.Instantiate = function (className) {
  8674. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8675. return Tools.RegisteredExternalClasses[className];
  8676. }
  8677. var arr = className.split(".");
  8678. var fn = (window || this);
  8679. for (var i = 0, len = arr.length; i < len; i++) {
  8680. fn = fn[arr[i]];
  8681. }
  8682. if (typeof fn !== "function") {
  8683. return null;
  8684. }
  8685. return fn;
  8686. };
  8687. /**
  8688. * Provides a slice function that will work even on IE
  8689. * @param data defines the array to slice
  8690. * @param start defines the start of the data (optional)
  8691. * @param end defines the end of the data (optional)
  8692. * @returns the new sliced array
  8693. */
  8694. Tools.Slice = function (data, start, end) {
  8695. if (data.slice) {
  8696. return data.slice(start, end);
  8697. }
  8698. return Array.prototype.slice.call(data, start, end);
  8699. };
  8700. Tools.SetImmediate = function (action) {
  8701. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8702. window.setImmediate(action);
  8703. }
  8704. else {
  8705. setTimeout(action, 1);
  8706. }
  8707. };
  8708. Tools.IsExponentOfTwo = function (value) {
  8709. var count = 1;
  8710. do {
  8711. count *= 2;
  8712. } while (count < value);
  8713. return count === value;
  8714. };
  8715. /**
  8716. * Returns the nearest 32-bit single precision float representation of a Number
  8717. * @param value A Number. If the parameter is of a different type, it will get converted
  8718. * to a number or to NaN if it cannot be converted
  8719. * @returns number
  8720. */
  8721. Tools.FloatRound = function (value) {
  8722. if (Math.fround) {
  8723. return Math.fround(value);
  8724. }
  8725. return (Tools._tmpFloatArray[0] = value);
  8726. };
  8727. /**
  8728. * Find the next highest power of two.
  8729. * @param x Number to start search from.
  8730. * @return Next highest power of two.
  8731. */
  8732. Tools.CeilingPOT = function (x) {
  8733. x--;
  8734. x |= x >> 1;
  8735. x |= x >> 2;
  8736. x |= x >> 4;
  8737. x |= x >> 8;
  8738. x |= x >> 16;
  8739. x++;
  8740. return x;
  8741. };
  8742. /**
  8743. * Find the next lowest power of two.
  8744. * @param x Number to start search from.
  8745. * @return Next lowest power of two.
  8746. */
  8747. Tools.FloorPOT = function (x) {
  8748. x = x | (x >> 1);
  8749. x = x | (x >> 2);
  8750. x = x | (x >> 4);
  8751. x = x | (x >> 8);
  8752. x = x | (x >> 16);
  8753. return x - (x >> 1);
  8754. };
  8755. /**
  8756. * Find the nearest power of two.
  8757. * @param x Number to start search from.
  8758. * @return Next nearest power of two.
  8759. */
  8760. Tools.NearestPOT = function (x) {
  8761. var c = Tools.CeilingPOT(x);
  8762. var f = Tools.FloorPOT(x);
  8763. return (c - x) > (x - f) ? f : c;
  8764. };
  8765. Tools.GetExponentOfTwo = function (value, max, mode) {
  8766. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8767. var pot;
  8768. switch (mode) {
  8769. case BABYLON.Engine.SCALEMODE_FLOOR:
  8770. pot = Tools.FloorPOT(value);
  8771. break;
  8772. case BABYLON.Engine.SCALEMODE_NEAREST:
  8773. pot = Tools.NearestPOT(value);
  8774. break;
  8775. case BABYLON.Engine.SCALEMODE_CEILING:
  8776. default:
  8777. pot = Tools.CeilingPOT(value);
  8778. break;
  8779. }
  8780. return Math.min(pot, max);
  8781. };
  8782. Tools.GetFilename = function (path) {
  8783. var index = path.lastIndexOf("/");
  8784. if (index < 0)
  8785. return path;
  8786. return path.substring(index + 1);
  8787. };
  8788. /**
  8789. * Extracts the "folder" part of a path (everything before the filename).
  8790. * @param uri The URI to extract the info from
  8791. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8792. * @returns The "folder" part of the path
  8793. */
  8794. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8795. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8796. var index = uri.lastIndexOf("/");
  8797. if (index < 0) {
  8798. if (returnUnchangedIfNoSlash) {
  8799. return uri;
  8800. }
  8801. return "";
  8802. }
  8803. return uri.substring(0, index + 1);
  8804. };
  8805. Tools.GetDOMTextContent = function (element) {
  8806. var result = "";
  8807. var child = element.firstChild;
  8808. while (child) {
  8809. if (child.nodeType === 3) {
  8810. result += child.textContent;
  8811. }
  8812. child = child.nextSibling;
  8813. }
  8814. return result;
  8815. };
  8816. Tools.ToDegrees = function (angle) {
  8817. return angle * 180 / Math.PI;
  8818. };
  8819. Tools.ToRadians = function (angle) {
  8820. return angle * Math.PI / 180;
  8821. };
  8822. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8823. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8824. var output = "";
  8825. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8826. var i = 0;
  8827. var bytes = new Uint8Array(buffer);
  8828. while (i < bytes.length) {
  8829. chr1 = bytes[i++];
  8830. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8831. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8832. enc1 = chr1 >> 2;
  8833. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8834. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8835. enc4 = chr3 & 63;
  8836. if (isNaN(chr2)) {
  8837. enc3 = enc4 = 64;
  8838. }
  8839. else if (isNaN(chr3)) {
  8840. enc4 = 64;
  8841. }
  8842. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8843. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8844. }
  8845. return "data:image/png;base64," + output;
  8846. };
  8847. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8848. if (bias === void 0) { bias = null; }
  8849. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8850. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8851. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8852. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8853. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8854. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8855. }
  8856. if (bias) {
  8857. minimum.x -= minimum.x * bias.x + bias.y;
  8858. minimum.y -= minimum.y * bias.x + bias.y;
  8859. minimum.z -= minimum.z * bias.x + bias.y;
  8860. maximum.x += maximum.x * bias.x + bias.y;
  8861. maximum.y += maximum.y * bias.x + bias.y;
  8862. maximum.z += maximum.z * bias.x + bias.y;
  8863. }
  8864. return {
  8865. minimum: minimum,
  8866. maximum: maximum
  8867. };
  8868. };
  8869. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8870. if (bias === void 0) { bias = null; }
  8871. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8872. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8873. if (!stride) {
  8874. stride = 3;
  8875. }
  8876. for (var index = start; index < start + count; index++) {
  8877. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8878. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8879. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8880. }
  8881. if (bias) {
  8882. minimum.x -= minimum.x * bias.x + bias.y;
  8883. minimum.y -= minimum.y * bias.x + bias.y;
  8884. minimum.z -= minimum.z * bias.x + bias.y;
  8885. maximum.x += maximum.x * bias.x + bias.y;
  8886. maximum.y += maximum.y * bias.x + bias.y;
  8887. maximum.z += maximum.z * bias.x + bias.y;
  8888. }
  8889. return {
  8890. minimum: minimum,
  8891. maximum: maximum
  8892. };
  8893. };
  8894. Tools.Vector2ArrayFeeder = function (array) {
  8895. return function (index) {
  8896. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8897. var length = isFloatArray ? array.length / 2 : array.length;
  8898. if (index >= length) {
  8899. return null;
  8900. }
  8901. if (isFloatArray) {
  8902. var fa = array;
  8903. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8904. }
  8905. var a = array;
  8906. return a[index];
  8907. };
  8908. };
  8909. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8910. if (bias === void 0) { bias = null; }
  8911. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8912. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8913. var i = 0;
  8914. var cur = feeder(i++);
  8915. while (cur) {
  8916. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8917. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8918. cur = feeder(i++);
  8919. }
  8920. if (bias) {
  8921. minimum.x -= minimum.x * bias.x + bias.y;
  8922. minimum.y -= minimum.y * bias.x + bias.y;
  8923. maximum.x += maximum.x * bias.x + bias.y;
  8924. maximum.y += maximum.y * bias.x + bias.y;
  8925. }
  8926. return {
  8927. minimum: minimum,
  8928. maximum: maximum
  8929. };
  8930. };
  8931. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8932. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8933. return null;
  8934. return Array.isArray(obj) ? obj : [obj];
  8935. };
  8936. // Misc.
  8937. Tools.GetPointerPrefix = function () {
  8938. var eventPrefix = "pointer";
  8939. // Check if pointer events are supported
  8940. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8941. eventPrefix = "mouse";
  8942. }
  8943. return eventPrefix;
  8944. };
  8945. /**
  8946. * @param func - the function to be called
  8947. * @param requester - the object that will request the next frame. Falls back to window.
  8948. */
  8949. Tools.QueueNewFrame = function (func, requester) {
  8950. if (!Tools.IsWindowObjectExist()) {
  8951. return setTimeout(func, 16);
  8952. }
  8953. if (!requester) {
  8954. requester = window;
  8955. }
  8956. if (requester.requestAnimationFrame) {
  8957. return requester.requestAnimationFrame(func);
  8958. }
  8959. else if (requester.msRequestAnimationFrame) {
  8960. return requester.msRequestAnimationFrame(func);
  8961. }
  8962. else if (requester.webkitRequestAnimationFrame) {
  8963. return requester.webkitRequestAnimationFrame(func);
  8964. }
  8965. else if (requester.mozRequestAnimationFrame) {
  8966. return requester.mozRequestAnimationFrame(func);
  8967. }
  8968. else if (requester.oRequestAnimationFrame) {
  8969. return requester.oRequestAnimationFrame(func);
  8970. }
  8971. else {
  8972. return window.setTimeout(func, 16);
  8973. }
  8974. };
  8975. Tools.RequestFullscreen = function (element) {
  8976. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8977. if (!requestFunction)
  8978. return;
  8979. requestFunction.call(element);
  8980. };
  8981. Tools.ExitFullscreen = function () {
  8982. if (document.exitFullscreen) {
  8983. document.exitFullscreen();
  8984. }
  8985. else if (document.mozCancelFullScreen) {
  8986. document.mozCancelFullScreen();
  8987. }
  8988. else if (document.webkitCancelFullScreen) {
  8989. document.webkitCancelFullScreen();
  8990. }
  8991. else if (document.msCancelFullScreen) {
  8992. document.msCancelFullScreen();
  8993. }
  8994. };
  8995. Tools.SetCorsBehavior = function (url, element) {
  8996. if (url && url.indexOf("data:") === 0) {
  8997. return;
  8998. }
  8999. if (Tools.CorsBehavior) {
  9000. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9001. element.crossOrigin = Tools.CorsBehavior;
  9002. }
  9003. else {
  9004. var result = Tools.CorsBehavior(url);
  9005. if (result) {
  9006. element.crossOrigin = result;
  9007. }
  9008. }
  9009. }
  9010. };
  9011. // External files
  9012. Tools.CleanUrl = function (url) {
  9013. url = url.replace(/#/mg, "%23");
  9014. return url;
  9015. };
  9016. /**
  9017. * Loads an image as an HTMLImageElement.
  9018. * @param input url string, ArrayBuffer, or Blob to load
  9019. * @param onLoad callback called when the image successfully loads
  9020. * @param onError callback called when the image fails to load
  9021. * @param database database for caching
  9022. * @returns the HTMLImageElement of the loaded image
  9023. */
  9024. Tools.LoadImage = function (input, onLoad, onError, database) {
  9025. var url;
  9026. var usingObjectURL = false;
  9027. if (input instanceof ArrayBuffer) {
  9028. url = URL.createObjectURL(new Blob([input]));
  9029. usingObjectURL = true;
  9030. }
  9031. else if (input instanceof Blob) {
  9032. url = URL.createObjectURL(input);
  9033. usingObjectURL = true;
  9034. }
  9035. else {
  9036. url = Tools.CleanUrl(input);
  9037. url = Tools.PreprocessUrl(input);
  9038. }
  9039. var img = new Image();
  9040. Tools.SetCorsBehavior(url, img);
  9041. var loadHandler = function () {
  9042. if (usingObjectURL && img.src) {
  9043. URL.revokeObjectURL(img.src);
  9044. }
  9045. img.removeEventListener("load", loadHandler);
  9046. img.removeEventListener("error", errorHandler);
  9047. onLoad(img);
  9048. };
  9049. var errorHandler = function (err) {
  9050. if (usingObjectURL && img.src) {
  9051. URL.revokeObjectURL(img.src);
  9052. }
  9053. img.removeEventListener("load", loadHandler);
  9054. img.removeEventListener("error", errorHandler);
  9055. Tools.Error("Error while trying to load image: " + input);
  9056. if (onError) {
  9057. onError("Error while trying to load image: " + input, err);
  9058. }
  9059. };
  9060. img.addEventListener("load", loadHandler);
  9061. img.addEventListener("error", errorHandler);
  9062. var noIndexedDB = function () {
  9063. img.src = url;
  9064. };
  9065. var loadFromIndexedDB = function () {
  9066. if (database) {
  9067. database.loadImageFromDB(url, img);
  9068. }
  9069. };
  9070. //ANY database to do!
  9071. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9072. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9073. }
  9074. else {
  9075. if (url.indexOf("file:") !== -1) {
  9076. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9077. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9078. try {
  9079. var blobURL;
  9080. try {
  9081. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9082. }
  9083. catch (ex) {
  9084. // Chrome doesn't support oneTimeOnly parameter
  9085. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9086. }
  9087. img.src = blobURL;
  9088. usingObjectURL = true;
  9089. }
  9090. catch (e) {
  9091. img.src = "";
  9092. }
  9093. return img;
  9094. }
  9095. }
  9096. noIndexedDB();
  9097. }
  9098. return img;
  9099. };
  9100. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9101. url = Tools.CleanUrl(url);
  9102. url = Tools.PreprocessUrl(url);
  9103. // If file and file input are set
  9104. if (url.indexOf("file:") !== -1) {
  9105. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9106. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9107. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9108. }
  9109. }
  9110. var loadUrl = Tools.BaseUrl + url;
  9111. var aborted = false;
  9112. var fileRequest = {
  9113. onCompleteObservable: new BABYLON.Observable(),
  9114. abort: function () { return aborted = true; },
  9115. };
  9116. var requestFile = function () {
  9117. var request = new XMLHttpRequest();
  9118. var retryHandle = null;
  9119. fileRequest.abort = function () {
  9120. aborted = true;
  9121. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9122. request.abort();
  9123. }
  9124. if (retryHandle !== null) {
  9125. clearTimeout(retryHandle);
  9126. retryHandle = null;
  9127. }
  9128. };
  9129. var retryLoop = function (retryIndex) {
  9130. request.open('GET', loadUrl, true);
  9131. if (useArrayBuffer) {
  9132. request.responseType = "arraybuffer";
  9133. }
  9134. if (onProgress) {
  9135. request.addEventListener("progress", onProgress);
  9136. }
  9137. var onLoadEnd = function () {
  9138. request.removeEventListener("loadend", onLoadEnd);
  9139. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9140. fileRequest.onCompleteObservable.clear();
  9141. };
  9142. request.addEventListener("loadend", onLoadEnd);
  9143. var onReadyStateChange = function () {
  9144. if (aborted) {
  9145. return;
  9146. }
  9147. // In case of undefined state in some browsers.
  9148. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9149. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9150. request.removeEventListener("readystatechange", onReadyStateChange);
  9151. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9152. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9153. return;
  9154. }
  9155. var retryStrategy = Tools.DefaultRetryStrategy;
  9156. if (retryStrategy) {
  9157. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9158. if (waitTime !== -1) {
  9159. // Prevent the request from completing for retry.
  9160. request.removeEventListener("loadend", onLoadEnd);
  9161. request = new XMLHttpRequest();
  9162. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9163. return;
  9164. }
  9165. }
  9166. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9167. if (onError) {
  9168. onError(request, e);
  9169. }
  9170. else {
  9171. throw e;
  9172. }
  9173. }
  9174. };
  9175. request.addEventListener("readystatechange", onReadyStateChange);
  9176. request.send();
  9177. };
  9178. retryLoop(0);
  9179. };
  9180. // Caching all files
  9181. if (database && database.enableSceneOffline) {
  9182. var noIndexedDB_1 = function (request) {
  9183. if (request && request.status > 400) {
  9184. if (onError) {
  9185. onError(request);
  9186. }
  9187. }
  9188. else {
  9189. if (!aborted) {
  9190. requestFile();
  9191. }
  9192. }
  9193. };
  9194. var loadFromIndexedDB = function () {
  9195. // TODO: database needs to support aborting and should return a IFileRequest
  9196. if (aborted) {
  9197. return;
  9198. }
  9199. if (database) {
  9200. database.loadFileFromDB(url, function (data) {
  9201. if (!aborted) {
  9202. onSuccess(data);
  9203. }
  9204. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9205. }, onProgress ? function (event) {
  9206. if (!aborted) {
  9207. onProgress(event);
  9208. }
  9209. } : undefined, noIndexedDB_1, useArrayBuffer);
  9210. }
  9211. };
  9212. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9213. }
  9214. else {
  9215. requestFile();
  9216. }
  9217. return fileRequest;
  9218. };
  9219. /**
  9220. * Load a script (identified by an url). When the url returns, the
  9221. * content of this file is added into a new script element, attached to the DOM (body element)
  9222. */
  9223. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9224. var head = document.getElementsByTagName('head')[0];
  9225. var script = document.createElement('script');
  9226. script.type = 'text/javascript';
  9227. script.src = scriptUrl;
  9228. script.onload = function () {
  9229. if (onSuccess) {
  9230. onSuccess();
  9231. }
  9232. };
  9233. script.onerror = function (e) {
  9234. if (onError) {
  9235. onError("Unable to load script '" + scriptUrl + "'", e);
  9236. }
  9237. };
  9238. head.appendChild(script);
  9239. };
  9240. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9241. var reader = new FileReader();
  9242. var request = {
  9243. onCompleteObservable: new BABYLON.Observable(),
  9244. abort: function () { return reader.abort(); },
  9245. };
  9246. reader.onloadend = function (e) {
  9247. request.onCompleteObservable.notifyObservers(request);
  9248. };
  9249. reader.onload = function (e) {
  9250. //target doesn't have result from ts 1.3
  9251. callback(e.target['result']);
  9252. };
  9253. reader.onprogress = progressCallback;
  9254. reader.readAsDataURL(fileToLoad);
  9255. return request;
  9256. };
  9257. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9258. var reader = new FileReader();
  9259. var request = {
  9260. onCompleteObservable: new BABYLON.Observable(),
  9261. abort: function () { return reader.abort(); },
  9262. };
  9263. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9264. reader.onerror = function (e) {
  9265. Tools.Log("Error while reading file: " + fileToLoad.name);
  9266. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9267. };
  9268. reader.onload = function (e) {
  9269. //target doesn't have result from ts 1.3
  9270. callback(e.target['result']);
  9271. };
  9272. if (progressCallBack) {
  9273. reader.onprogress = progressCallBack;
  9274. }
  9275. if (!useArrayBuffer) {
  9276. // Asynchronous read
  9277. reader.readAsText(fileToLoad);
  9278. }
  9279. else {
  9280. reader.readAsArrayBuffer(fileToLoad);
  9281. }
  9282. return request;
  9283. };
  9284. //returns a downloadable url to a file content.
  9285. Tools.FileAsURL = function (content) {
  9286. var fileBlob = new Blob([content]);
  9287. var url = window.URL || window.webkitURL;
  9288. var link = url.createObjectURL(fileBlob);
  9289. return link;
  9290. };
  9291. // Misc.
  9292. Tools.Format = function (value, decimals) {
  9293. if (decimals === void 0) { decimals = 2; }
  9294. return value.toFixed(decimals);
  9295. };
  9296. Tools.CheckExtends = function (v, min, max) {
  9297. if (v.x < min.x)
  9298. min.x = v.x;
  9299. if (v.y < min.y)
  9300. min.y = v.y;
  9301. if (v.z < min.z)
  9302. min.z = v.z;
  9303. if (v.x > max.x)
  9304. max.x = v.x;
  9305. if (v.y > max.y)
  9306. max.y = v.y;
  9307. if (v.z > max.z)
  9308. max.z = v.z;
  9309. };
  9310. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9311. for (var prop in source) {
  9312. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9313. continue;
  9314. }
  9315. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9316. continue;
  9317. }
  9318. var sourceValue = source[prop];
  9319. var typeOfSourceValue = typeof sourceValue;
  9320. if (typeOfSourceValue === "function") {
  9321. continue;
  9322. }
  9323. try {
  9324. if (typeOfSourceValue === "object") {
  9325. if (sourceValue instanceof Array) {
  9326. destination[prop] = [];
  9327. if (sourceValue.length > 0) {
  9328. if (typeof sourceValue[0] == "object") {
  9329. for (var index = 0; index < sourceValue.length; index++) {
  9330. var clonedValue = cloneValue(sourceValue[index], destination);
  9331. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9332. destination[prop].push(clonedValue);
  9333. }
  9334. }
  9335. }
  9336. else {
  9337. destination[prop] = sourceValue.slice(0);
  9338. }
  9339. }
  9340. }
  9341. else {
  9342. destination[prop] = cloneValue(sourceValue, destination);
  9343. }
  9344. }
  9345. else {
  9346. destination[prop] = sourceValue;
  9347. }
  9348. }
  9349. catch (e) {
  9350. // Just ignore error (it could be because of a read-only property)
  9351. }
  9352. }
  9353. };
  9354. Tools.IsEmpty = function (obj) {
  9355. for (var i in obj) {
  9356. if (obj.hasOwnProperty(i)) {
  9357. return false;
  9358. }
  9359. }
  9360. return true;
  9361. };
  9362. Tools.RegisterTopRootEvents = function (events) {
  9363. for (var index = 0; index < events.length; index++) {
  9364. var event = events[index];
  9365. window.addEventListener(event.name, event.handler, false);
  9366. try {
  9367. if (window.parent) {
  9368. window.parent.addEventListener(event.name, event.handler, false);
  9369. }
  9370. }
  9371. catch (e) {
  9372. // Silently fails...
  9373. }
  9374. }
  9375. };
  9376. Tools.UnregisterTopRootEvents = function (events) {
  9377. for (var index = 0; index < events.length; index++) {
  9378. var event = events[index];
  9379. window.removeEventListener(event.name, event.handler);
  9380. try {
  9381. if (window.parent) {
  9382. window.parent.removeEventListener(event.name, event.handler);
  9383. }
  9384. }
  9385. catch (e) {
  9386. // Silently fails...
  9387. }
  9388. }
  9389. };
  9390. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9391. if (mimeType === void 0) { mimeType = "image/png"; }
  9392. // Read the contents of the framebuffer
  9393. var numberOfChannelsByLine = width * 4;
  9394. var halfHeight = height / 2;
  9395. //Reading datas from WebGL
  9396. var data = engine.readPixels(0, 0, width, height);
  9397. //To flip image on Y axis.
  9398. for (var i = 0; i < halfHeight; i++) {
  9399. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9400. var currentCell = j + i * numberOfChannelsByLine;
  9401. var targetLine = height - i - 1;
  9402. var targetCell = j + targetLine * numberOfChannelsByLine;
  9403. var temp = data[currentCell];
  9404. data[currentCell] = data[targetCell];
  9405. data[targetCell] = temp;
  9406. }
  9407. }
  9408. // Create a 2D canvas to store the result
  9409. if (!screenshotCanvas) {
  9410. screenshotCanvas = document.createElement('canvas');
  9411. }
  9412. screenshotCanvas.width = width;
  9413. screenshotCanvas.height = height;
  9414. var context = screenshotCanvas.getContext('2d');
  9415. if (context) {
  9416. // Copy the pixels to a 2D canvas
  9417. var imageData = context.createImageData(width, height);
  9418. var castData = (imageData.data);
  9419. castData.set(data);
  9420. context.putImageData(imageData, 0, 0);
  9421. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9422. }
  9423. };
  9424. /**
  9425. * Converts the canvas data to blob.
  9426. * This acts as a polyfill for browsers not supporting the to blob function.
  9427. * @param canvas Defines the canvas to extract the data from
  9428. * @param successCallback Defines the callback triggered once the data are available
  9429. * @param mimeType Defines the mime type of the result
  9430. */
  9431. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9432. if (mimeType === void 0) { mimeType = "image/png"; }
  9433. // We need HTMLCanvasElement.toBlob for HD screenshots
  9434. if (!canvas.toBlob) {
  9435. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9436. canvas.toBlob = function (callback, type, quality) {
  9437. var _this = this;
  9438. setTimeout(function () {
  9439. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9440. for (var i = 0; i < len; i++) {
  9441. arr[i] = binStr.charCodeAt(i);
  9442. }
  9443. callback(new Blob([arr]));
  9444. });
  9445. };
  9446. }
  9447. canvas.toBlob(function (blob) {
  9448. successCallback(blob);
  9449. }, mimeType);
  9450. };
  9451. /**
  9452. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9453. * @param successCallback Defines the callback triggered once the data are available
  9454. * @param mimeType Defines the mime type of the result
  9455. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9456. */
  9457. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9458. if (mimeType === void 0) { mimeType = "image/png"; }
  9459. if (successCallback) {
  9460. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9461. successCallback(base64Image);
  9462. }
  9463. else {
  9464. this.ToBlob(screenshotCanvas, function (blob) {
  9465. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9466. if (("download" in document.createElement("a"))) {
  9467. if (!fileName) {
  9468. var date = new Date();
  9469. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9470. fileName = "screenshot_" + stringDate + ".png";
  9471. }
  9472. Tools.Download(blob, fileName);
  9473. }
  9474. else {
  9475. var url = URL.createObjectURL(blob);
  9476. var newWindow = window.open("");
  9477. if (!newWindow)
  9478. return;
  9479. var img = newWindow.document.createElement("img");
  9480. img.onload = function () {
  9481. // no longer need to read the blob so it's revoked
  9482. URL.revokeObjectURL(url);
  9483. };
  9484. img.src = url;
  9485. newWindow.document.body.appendChild(img);
  9486. }
  9487. }, mimeType);
  9488. }
  9489. };
  9490. /**
  9491. * Downloads a blob in the browser
  9492. * @param blob defines the blob to download
  9493. * @param fileName defines the name of the downloaded file
  9494. */
  9495. Tools.Download = function (blob, fileName) {
  9496. if (navigator && navigator.msSaveBlob) {
  9497. navigator.msSaveBlob(blob, fileName);
  9498. return;
  9499. }
  9500. var url = window.URL.createObjectURL(blob);
  9501. var a = document.createElement("a");
  9502. document.body.appendChild(a);
  9503. a.style.display = "none";
  9504. a.href = url;
  9505. a.download = fileName;
  9506. a.addEventListener("click", function () {
  9507. if (a.parentElement) {
  9508. a.parentElement.removeChild(a);
  9509. }
  9510. });
  9511. a.click();
  9512. window.URL.revokeObjectURL(url);
  9513. };
  9514. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9515. if (mimeType === void 0) { mimeType = "image/png"; }
  9516. var width;
  9517. var height;
  9518. // If a precision value is specified
  9519. if (size.precision) {
  9520. width = Math.round(engine.getRenderWidth() * size.precision);
  9521. height = Math.round(width / engine.getAspectRatio(camera));
  9522. }
  9523. else if (size.width && size.height) {
  9524. width = size.width;
  9525. height = size.height;
  9526. }
  9527. //If passing only width, computing height to keep display canvas ratio.
  9528. else if (size.width && !size.height) {
  9529. width = size.width;
  9530. height = Math.round(width / engine.getAspectRatio(camera));
  9531. }
  9532. //If passing only height, computing width to keep display canvas ratio.
  9533. else if (size.height && !size.width) {
  9534. height = size.height;
  9535. width = Math.round(height * engine.getAspectRatio(camera));
  9536. }
  9537. //Assuming here that "size" parameter is a number
  9538. else if (!isNaN(size)) {
  9539. height = size;
  9540. width = size;
  9541. }
  9542. else {
  9543. Tools.Error("Invalid 'size' parameter !");
  9544. return;
  9545. }
  9546. if (!screenshotCanvas) {
  9547. screenshotCanvas = document.createElement('canvas');
  9548. }
  9549. screenshotCanvas.width = width;
  9550. screenshotCanvas.height = height;
  9551. var renderContext = screenshotCanvas.getContext("2d");
  9552. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9553. var newWidth = width;
  9554. var newHeight = newWidth / ratio;
  9555. if (newHeight > height) {
  9556. newHeight = height;
  9557. newWidth = newHeight * ratio;
  9558. }
  9559. var offsetX = Math.max(0, width - newWidth) / 2;
  9560. var offsetY = Math.max(0, height - newHeight) / 2;
  9561. var renderingCanvas = engine.getRenderingCanvas();
  9562. if (renderContext && renderingCanvas) {
  9563. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9564. }
  9565. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9566. };
  9567. /**
  9568. * Generates an image screenshot from the specified camera.
  9569. *
  9570. * @param engine The engine to use for rendering
  9571. * @param camera The camera to use for rendering
  9572. * @param size This parameter can be set to a single number or to an object with the
  9573. * following (optional) properties: precision, width, height. If a single number is passed,
  9574. * it will be used for both width and height. If an object is passed, the screenshot size
  9575. * will be derived from the parameters. The precision property is a multiplier allowing
  9576. * rendering at a higher or lower resolution.
  9577. * @param successCallback The callback receives a single parameter which contains the
  9578. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9579. * src parameter of an <img> to display it.
  9580. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9581. * Check your browser for supported MIME types.
  9582. * @param samples Texture samples (default: 1)
  9583. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9584. * @param fileName A name for for the downloaded file.
  9585. * @constructor
  9586. */
  9587. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9588. if (mimeType === void 0) { mimeType = "image/png"; }
  9589. if (samples === void 0) { samples = 1; }
  9590. if (antialiasing === void 0) { antialiasing = false; }
  9591. var width;
  9592. var height;
  9593. //If a precision value is specified
  9594. if (size.precision) {
  9595. width = Math.round(engine.getRenderWidth() * size.precision);
  9596. height = Math.round(width / engine.getAspectRatio(camera));
  9597. size = { width: width, height: height };
  9598. }
  9599. else if (size.width && size.height) {
  9600. width = size.width;
  9601. height = size.height;
  9602. }
  9603. //If passing only width, computing height to keep display canvas ratio.
  9604. else if (size.width && !size.height) {
  9605. width = size.width;
  9606. height = Math.round(width / engine.getAspectRatio(camera));
  9607. size = { width: width, height: height };
  9608. }
  9609. //If passing only height, computing width to keep display canvas ratio.
  9610. else if (size.height && !size.width) {
  9611. height = size.height;
  9612. width = Math.round(height * engine.getAspectRatio(camera));
  9613. size = { width: width, height: height };
  9614. }
  9615. //Assuming here that "size" parameter is a number
  9616. else if (!isNaN(size)) {
  9617. height = size;
  9618. width = size;
  9619. }
  9620. else {
  9621. Tools.Error("Invalid 'size' parameter !");
  9622. return;
  9623. }
  9624. var scene = camera.getScene();
  9625. var previousCamera = null;
  9626. if (scene.activeCamera !== camera) {
  9627. previousCamera = scene.activeCamera;
  9628. scene.activeCamera = camera;
  9629. }
  9630. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9631. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9632. texture.renderList = null;
  9633. texture.samples = samples;
  9634. if (antialiasing) {
  9635. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9636. }
  9637. texture.onAfterRenderObservable.add(function () {
  9638. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9639. });
  9640. scene.incrementRenderId();
  9641. scene.resetCachedMaterial();
  9642. texture.render(true);
  9643. texture.dispose();
  9644. if (previousCamera) {
  9645. scene.activeCamera = previousCamera;
  9646. }
  9647. camera.getProjectionMatrix(true); // Force cache refresh;
  9648. };
  9649. // XHR response validator for local file scenario
  9650. Tools.ValidateXHRData = function (xhr, dataType) {
  9651. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9652. if (dataType === void 0) { dataType = 7; }
  9653. try {
  9654. if (dataType & 1) {
  9655. if (xhr.responseText && xhr.responseText.length > 0) {
  9656. return true;
  9657. }
  9658. else if (dataType === 1) {
  9659. return false;
  9660. }
  9661. }
  9662. if (dataType & 2) {
  9663. // Check header width and height since there is no "TGA" magic number
  9664. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9665. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9666. return true;
  9667. }
  9668. else if (dataType === 2) {
  9669. return false;
  9670. }
  9671. }
  9672. if (dataType & 4) {
  9673. // Check for the "DDS" magic number
  9674. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9675. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9676. return true;
  9677. }
  9678. else {
  9679. return false;
  9680. }
  9681. }
  9682. }
  9683. catch (e) {
  9684. // Global protection
  9685. }
  9686. return false;
  9687. };
  9688. /**
  9689. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9690. * Be aware Math.random() could cause collisions, but:
  9691. * "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"
  9692. */
  9693. Tools.RandomId = function () {
  9694. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9695. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9696. return v.toString(16);
  9697. });
  9698. };
  9699. /**
  9700. * Test if the given uri is a base64 string.
  9701. * @param uri The uri to test
  9702. * @return True if the uri is a base64 string or false otherwise.
  9703. */
  9704. Tools.IsBase64 = function (uri) {
  9705. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9706. };
  9707. /**
  9708. * Decode the given base64 uri.
  9709. * @param uri The uri to decode
  9710. * @return The decoded base64 data.
  9711. */
  9712. Tools.DecodeBase64 = function (uri) {
  9713. var decodedString = atob(uri.split(",")[1]);
  9714. var bufferLength = decodedString.length;
  9715. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9716. for (var i = 0; i < bufferLength; i++) {
  9717. bufferView[i] = decodedString.charCodeAt(i);
  9718. }
  9719. return bufferView.buffer;
  9720. };
  9721. Object.defineProperty(Tools, "NoneLogLevel", {
  9722. get: function () {
  9723. return Tools._NoneLogLevel;
  9724. },
  9725. enumerable: true,
  9726. configurable: true
  9727. });
  9728. Object.defineProperty(Tools, "MessageLogLevel", {
  9729. get: function () {
  9730. return Tools._MessageLogLevel;
  9731. },
  9732. enumerable: true,
  9733. configurable: true
  9734. });
  9735. Object.defineProperty(Tools, "WarningLogLevel", {
  9736. get: function () {
  9737. return Tools._WarningLogLevel;
  9738. },
  9739. enumerable: true,
  9740. configurable: true
  9741. });
  9742. Object.defineProperty(Tools, "ErrorLogLevel", {
  9743. get: function () {
  9744. return Tools._ErrorLogLevel;
  9745. },
  9746. enumerable: true,
  9747. configurable: true
  9748. });
  9749. Object.defineProperty(Tools, "AllLogLevel", {
  9750. get: function () {
  9751. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9752. },
  9753. enumerable: true,
  9754. configurable: true
  9755. });
  9756. Tools._AddLogEntry = function (entry) {
  9757. Tools._LogCache = entry + Tools._LogCache;
  9758. if (Tools.OnNewCacheEntry) {
  9759. Tools.OnNewCacheEntry(entry);
  9760. }
  9761. };
  9762. Tools._FormatMessage = function (message) {
  9763. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9764. var date = new Date();
  9765. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9766. };
  9767. Tools._LogDisabled = function (message) {
  9768. // nothing to do
  9769. };
  9770. Tools._LogEnabled = function (message) {
  9771. var formattedMessage = Tools._FormatMessage(message);
  9772. console.log("BJS - " + formattedMessage);
  9773. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9774. Tools._AddLogEntry(entry);
  9775. };
  9776. Tools._WarnDisabled = function (message) {
  9777. // nothing to do
  9778. };
  9779. Tools._WarnEnabled = function (message) {
  9780. var formattedMessage = Tools._FormatMessage(message);
  9781. console.warn("BJS - " + formattedMessage);
  9782. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9783. Tools._AddLogEntry(entry);
  9784. };
  9785. Tools._ErrorDisabled = function (message) {
  9786. // nothing to do
  9787. };
  9788. Tools._ErrorEnabled = function (message) {
  9789. Tools.errorsCount++;
  9790. var formattedMessage = Tools._FormatMessage(message);
  9791. console.error("BJS - " + formattedMessage);
  9792. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9793. Tools._AddLogEntry(entry);
  9794. };
  9795. Object.defineProperty(Tools, "LogCache", {
  9796. get: function () {
  9797. return Tools._LogCache;
  9798. },
  9799. enumerable: true,
  9800. configurable: true
  9801. });
  9802. Tools.ClearLogCache = function () {
  9803. Tools._LogCache = "";
  9804. Tools.errorsCount = 0;
  9805. };
  9806. Object.defineProperty(Tools, "LogLevels", {
  9807. set: function (level) {
  9808. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9809. Tools.Log = Tools._LogEnabled;
  9810. }
  9811. else {
  9812. Tools.Log = Tools._LogDisabled;
  9813. }
  9814. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9815. Tools.Warn = Tools._WarnEnabled;
  9816. }
  9817. else {
  9818. Tools.Warn = Tools._WarnDisabled;
  9819. }
  9820. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9821. Tools.Error = Tools._ErrorEnabled;
  9822. }
  9823. else {
  9824. Tools.Error = Tools._ErrorDisabled;
  9825. }
  9826. },
  9827. enumerable: true,
  9828. configurable: true
  9829. });
  9830. /**
  9831. * Check if the loaded document was accessed via `file:`-Protocol.
  9832. * @returns boolean
  9833. */
  9834. Tools.IsFileURL = function () {
  9835. return location.protocol === "file:";
  9836. };
  9837. Tools.IsWindowObjectExist = function () {
  9838. return (typeof window) !== "undefined";
  9839. };
  9840. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9841. get: function () {
  9842. return Tools._PerformanceNoneLogLevel;
  9843. },
  9844. enumerable: true,
  9845. configurable: true
  9846. });
  9847. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9848. get: function () {
  9849. return Tools._PerformanceUserMarkLogLevel;
  9850. },
  9851. enumerable: true,
  9852. configurable: true
  9853. });
  9854. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9855. get: function () {
  9856. return Tools._PerformanceConsoleLogLevel;
  9857. },
  9858. enumerable: true,
  9859. configurable: true
  9860. });
  9861. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9862. set: function (level) {
  9863. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9864. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9865. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9866. return;
  9867. }
  9868. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9869. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9870. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9871. return;
  9872. }
  9873. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9874. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9875. },
  9876. enumerable: true,
  9877. configurable: true
  9878. });
  9879. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9880. };
  9881. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9882. };
  9883. Tools._StartUserMark = function (counterName, condition) {
  9884. if (condition === void 0) { condition = true; }
  9885. if (!Tools._performance) {
  9886. if (!Tools.IsWindowObjectExist()) {
  9887. return;
  9888. }
  9889. Tools._performance = window.performance;
  9890. }
  9891. if (!condition || !Tools._performance.mark) {
  9892. return;
  9893. }
  9894. Tools._performance.mark(counterName + "-Begin");
  9895. };
  9896. Tools._EndUserMark = function (counterName, condition) {
  9897. if (condition === void 0) { condition = true; }
  9898. if (!condition || !Tools._performance.mark) {
  9899. return;
  9900. }
  9901. Tools._performance.mark(counterName + "-End");
  9902. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9903. };
  9904. Tools._StartPerformanceConsole = function (counterName, condition) {
  9905. if (condition === void 0) { condition = true; }
  9906. if (!condition) {
  9907. return;
  9908. }
  9909. Tools._StartUserMark(counterName, condition);
  9910. if (console.time) {
  9911. console.time(counterName);
  9912. }
  9913. };
  9914. Tools._EndPerformanceConsole = function (counterName, condition) {
  9915. if (condition === void 0) { condition = true; }
  9916. if (!condition) {
  9917. return;
  9918. }
  9919. Tools._EndUserMark(counterName, condition);
  9920. if (console.time) {
  9921. console.timeEnd(counterName);
  9922. }
  9923. };
  9924. Object.defineProperty(Tools, "Now", {
  9925. get: function () {
  9926. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9927. return window.performance.now();
  9928. }
  9929. return Date.now();
  9930. },
  9931. enumerable: true,
  9932. configurable: true
  9933. });
  9934. /**
  9935. * This method will return the name of the class used to create the instance of the given object.
  9936. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9937. * @param object the object to get the class name from
  9938. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9939. */
  9940. Tools.GetClassName = function (object, isType) {
  9941. if (isType === void 0) { isType = false; }
  9942. var name = null;
  9943. if (!isType && object.getClassName) {
  9944. name = object.getClassName();
  9945. }
  9946. else {
  9947. if (object instanceof Object) {
  9948. var classObj = isType ? object : Object.getPrototypeOf(object);
  9949. name = classObj.constructor["__bjsclassName__"];
  9950. }
  9951. if (!name) {
  9952. name = typeof object;
  9953. }
  9954. }
  9955. return name;
  9956. };
  9957. Tools.First = function (array, predicate) {
  9958. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9959. var el = array_1[_i];
  9960. if (predicate(el)) {
  9961. return el;
  9962. }
  9963. }
  9964. return null;
  9965. };
  9966. /**
  9967. * This method will return the name of the full name of the class, including its owning module (if any).
  9968. * 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).
  9969. * @param object the object to get the class name from
  9970. * @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.
  9971. */
  9972. Tools.getFullClassName = function (object, isType) {
  9973. if (isType === void 0) { isType = false; }
  9974. var className = null;
  9975. var moduleName = null;
  9976. if (!isType && object.getClassName) {
  9977. className = object.getClassName();
  9978. }
  9979. else {
  9980. if (object instanceof Object) {
  9981. var classObj = isType ? object : Object.getPrototypeOf(object);
  9982. className = classObj.constructor["__bjsclassName__"];
  9983. moduleName = classObj.constructor["__bjsmoduleName__"];
  9984. }
  9985. if (!className) {
  9986. className = typeof object;
  9987. }
  9988. }
  9989. if (!className) {
  9990. return null;
  9991. }
  9992. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9993. };
  9994. /**
  9995. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9996. * @param array
  9997. */
  9998. Tools.arrayOrStringFeeder = function (array) {
  9999. return function (index) {
  10000. if (index >= array.length) {
  10001. return null;
  10002. }
  10003. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10004. if (val && val.getHashCode) {
  10005. val = val.getHashCode();
  10006. }
  10007. if (typeof val === "string") {
  10008. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10009. }
  10010. return val;
  10011. };
  10012. };
  10013. /**
  10014. * Compute the hashCode of a stream of number
  10015. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10016. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10017. * @return the hash code computed
  10018. */
  10019. Tools.hashCodeFromStream = function (feeder) {
  10020. // Based from here: http://stackoverflow.com/a/7616484/802124
  10021. var hash = 0;
  10022. var index = 0;
  10023. var chr = feeder(index++);
  10024. while (chr != null) {
  10025. hash = ((hash << 5) - hash) + chr;
  10026. hash |= 0; // Convert to 32bit integer
  10027. chr = feeder(index++);
  10028. }
  10029. return hash;
  10030. };
  10031. /**
  10032. * Returns a promise that resolves after the given amount of time.
  10033. * @param delay Number of milliseconds to delay
  10034. * @returns Promise that resolves after the given amount of time
  10035. */
  10036. Tools.DelayAsync = function (delay) {
  10037. return new Promise(function (resolve) {
  10038. setTimeout(function () {
  10039. resolve();
  10040. }, delay);
  10041. });
  10042. };
  10043. /**
  10044. * Gets the current gradient from an array of IValueGradient
  10045. * @param ratio defines the current ratio to get
  10046. * @param gradients defines the array of IValueGradient
  10047. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10048. */
  10049. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10050. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10051. var currentGradient = gradients[gradientIndex];
  10052. var nextGradient = gradients[gradientIndex + 1];
  10053. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10054. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10055. updateFunc(currentGradient, nextGradient, scale);
  10056. }
  10057. }
  10058. };
  10059. Tools.BaseUrl = "";
  10060. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10061. /**
  10062. * Default behaviour for cors in the application.
  10063. * It can be a string if the expected behavior is identical in the entire app.
  10064. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10065. */
  10066. Tools.CorsBehavior = "anonymous";
  10067. Tools.UseFallbackTexture = true;
  10068. /**
  10069. * Use this object to register external classes like custom textures or material
  10070. * to allow the laoders to instantiate them
  10071. */
  10072. Tools.RegisteredExternalClasses = {};
  10073. // Used in case of a texture loading problem
  10074. 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";
  10075. Tools._tmpFloatArray = new Float32Array(1);
  10076. Tools.PreprocessUrl = function (url) {
  10077. return url;
  10078. };
  10079. // Logs
  10080. Tools._NoneLogLevel = 0;
  10081. Tools._MessageLogLevel = 1;
  10082. Tools._WarningLogLevel = 2;
  10083. Tools._ErrorLogLevel = 4;
  10084. Tools._LogCache = "";
  10085. Tools.errorsCount = 0;
  10086. Tools.Log = Tools._LogEnabled;
  10087. Tools.Warn = Tools._WarnEnabled;
  10088. Tools.Error = Tools._ErrorEnabled;
  10089. // Performances
  10090. Tools._PerformanceNoneLogLevel = 0;
  10091. Tools._PerformanceUserMarkLogLevel = 1;
  10092. Tools._PerformanceConsoleLogLevel = 2;
  10093. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10094. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10095. return Tools;
  10096. }());
  10097. BABYLON.Tools = Tools;
  10098. /**
  10099. * This class is used to track a performance counter which is number based.
  10100. * The user has access to many properties which give statistics of different nature
  10101. *
  10102. * The implementer can track two kinds of Performance Counter: time and count
  10103. * 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.
  10104. * 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.
  10105. */
  10106. var PerfCounter = /** @class */ (function () {
  10107. function PerfCounter() {
  10108. this._startMonitoringTime = 0;
  10109. this._min = 0;
  10110. this._max = 0;
  10111. this._average = 0;
  10112. this._lastSecAverage = 0;
  10113. this._current = 0;
  10114. this._totalValueCount = 0;
  10115. this._totalAccumulated = 0;
  10116. this._lastSecAccumulated = 0;
  10117. this._lastSecTime = 0;
  10118. this._lastSecValueCount = 0;
  10119. }
  10120. Object.defineProperty(PerfCounter.prototype, "min", {
  10121. /**
  10122. * Returns the smallest value ever
  10123. */
  10124. get: function () {
  10125. return this._min;
  10126. },
  10127. enumerable: true,
  10128. configurable: true
  10129. });
  10130. Object.defineProperty(PerfCounter.prototype, "max", {
  10131. /**
  10132. * Returns the biggest value ever
  10133. */
  10134. get: function () {
  10135. return this._max;
  10136. },
  10137. enumerable: true,
  10138. configurable: true
  10139. });
  10140. Object.defineProperty(PerfCounter.prototype, "average", {
  10141. /**
  10142. * Returns the average value since the performance counter is running
  10143. */
  10144. get: function () {
  10145. return this._average;
  10146. },
  10147. enumerable: true,
  10148. configurable: true
  10149. });
  10150. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10151. /**
  10152. * Returns the average value of the last second the counter was monitored
  10153. */
  10154. get: function () {
  10155. return this._lastSecAverage;
  10156. },
  10157. enumerable: true,
  10158. configurable: true
  10159. });
  10160. Object.defineProperty(PerfCounter.prototype, "current", {
  10161. /**
  10162. * Returns the current value
  10163. */
  10164. get: function () {
  10165. return this._current;
  10166. },
  10167. enumerable: true,
  10168. configurable: true
  10169. });
  10170. Object.defineProperty(PerfCounter.prototype, "total", {
  10171. get: function () {
  10172. return this._totalAccumulated;
  10173. },
  10174. enumerable: true,
  10175. configurable: true
  10176. });
  10177. Object.defineProperty(PerfCounter.prototype, "count", {
  10178. get: function () {
  10179. return this._totalValueCount;
  10180. },
  10181. enumerable: true,
  10182. configurable: true
  10183. });
  10184. /**
  10185. * Call this method to start monitoring a new frame.
  10186. * 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.
  10187. */
  10188. PerfCounter.prototype.fetchNewFrame = function () {
  10189. this._totalValueCount++;
  10190. this._current = 0;
  10191. this._lastSecValueCount++;
  10192. };
  10193. /**
  10194. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10195. * @param newCount the count value to add to the monitored count
  10196. * @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.
  10197. */
  10198. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10199. if (!PerfCounter.Enabled) {
  10200. return;
  10201. }
  10202. this._current += newCount;
  10203. if (fetchResult) {
  10204. this._fetchResult();
  10205. }
  10206. };
  10207. /**
  10208. * Start monitoring this performance counter
  10209. */
  10210. PerfCounter.prototype.beginMonitoring = function () {
  10211. if (!PerfCounter.Enabled) {
  10212. return;
  10213. }
  10214. this._startMonitoringTime = Tools.Now;
  10215. };
  10216. /**
  10217. * Compute the time lapsed since the previous beginMonitoring() call.
  10218. * @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
  10219. */
  10220. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10221. if (newFrame === void 0) { newFrame = true; }
  10222. if (!PerfCounter.Enabled) {
  10223. return;
  10224. }
  10225. if (newFrame) {
  10226. this.fetchNewFrame();
  10227. }
  10228. var currentTime = Tools.Now;
  10229. this._current = currentTime - this._startMonitoringTime;
  10230. if (newFrame) {
  10231. this._fetchResult();
  10232. }
  10233. };
  10234. PerfCounter.prototype._fetchResult = function () {
  10235. this._totalAccumulated += this._current;
  10236. this._lastSecAccumulated += this._current;
  10237. // Min/Max update
  10238. this._min = Math.min(this._min, this._current);
  10239. this._max = Math.max(this._max, this._current);
  10240. this._average = this._totalAccumulated / this._totalValueCount;
  10241. // Reset last sec?
  10242. var now = Tools.Now;
  10243. if ((now - this._lastSecTime) > 1000) {
  10244. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10245. this._lastSecTime = now;
  10246. this._lastSecAccumulated = 0;
  10247. this._lastSecValueCount = 0;
  10248. }
  10249. };
  10250. PerfCounter.Enabled = true;
  10251. return PerfCounter;
  10252. }());
  10253. BABYLON.PerfCounter = PerfCounter;
  10254. /**
  10255. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10256. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10257. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10258. * @param name The name of the class, case should be preserved
  10259. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10260. */
  10261. function className(name, module) {
  10262. return function (target) {
  10263. target["__bjsclassName__"] = name;
  10264. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10265. };
  10266. }
  10267. BABYLON.className = className;
  10268. /**
  10269. * An implementation of a loop for asynchronous functions.
  10270. */
  10271. var AsyncLoop = /** @class */ (function () {
  10272. /**
  10273. * Constroctor.
  10274. * @param iterations the number of iterations.
  10275. * @param _fn the function to run each iteration
  10276. * @param _successCallback the callback that will be called upon succesful execution
  10277. * @param offset starting offset.
  10278. */
  10279. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10280. if (offset === void 0) { offset = 0; }
  10281. this.iterations = iterations;
  10282. this._fn = _fn;
  10283. this._successCallback = _successCallback;
  10284. this.index = offset - 1;
  10285. this._done = false;
  10286. }
  10287. /**
  10288. * Execute the next iteration. Must be called after the last iteration was finished.
  10289. */
  10290. AsyncLoop.prototype.executeNext = function () {
  10291. if (!this._done) {
  10292. if (this.index + 1 < this.iterations) {
  10293. ++this.index;
  10294. this._fn(this);
  10295. }
  10296. else {
  10297. this.breakLoop();
  10298. }
  10299. }
  10300. };
  10301. /**
  10302. * Break the loop and run the success callback.
  10303. */
  10304. AsyncLoop.prototype.breakLoop = function () {
  10305. this._done = true;
  10306. this._successCallback();
  10307. };
  10308. /**
  10309. * Helper function
  10310. */
  10311. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10312. if (offset === void 0) { offset = 0; }
  10313. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10314. loop.executeNext();
  10315. return loop;
  10316. };
  10317. /**
  10318. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10319. * @param iterations total number of iterations
  10320. * @param syncedIterations number of synchronous iterations in each async iteration.
  10321. * @param fn the function to call each iteration.
  10322. * @param callback a success call back that will be called when iterating stops.
  10323. * @param breakFunction a break condition (optional)
  10324. * @param timeout timeout settings for the setTimeout function. default - 0.
  10325. * @constructor
  10326. */
  10327. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10328. if (timeout === void 0) { timeout = 0; }
  10329. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10330. if (breakFunction && breakFunction())
  10331. loop.breakLoop();
  10332. else {
  10333. setTimeout(function () {
  10334. for (var i = 0; i < syncedIterations; ++i) {
  10335. var iteration = (loop.index * syncedIterations) + i;
  10336. if (iteration >= iterations)
  10337. break;
  10338. fn(iteration);
  10339. if (breakFunction && breakFunction()) {
  10340. loop.breakLoop();
  10341. break;
  10342. }
  10343. }
  10344. loop.executeNext();
  10345. }, timeout);
  10346. }
  10347. }, callback);
  10348. };
  10349. return AsyncLoop;
  10350. }());
  10351. BABYLON.AsyncLoop = AsyncLoop;
  10352. })(BABYLON || (BABYLON = {}));
  10353. //# sourceMappingURL=babylon.tools.js.map
  10354. var BABYLON;
  10355. (function (BABYLON) {
  10356. var PromiseStates;
  10357. (function (PromiseStates) {
  10358. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10359. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10360. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10361. })(PromiseStates || (PromiseStates = {}));
  10362. var FulFillmentAgregator = /** @class */ (function () {
  10363. function FulFillmentAgregator() {
  10364. this.count = 0;
  10365. this.target = 0;
  10366. this.results = [];
  10367. }
  10368. return FulFillmentAgregator;
  10369. }());
  10370. var InternalPromise = /** @class */ (function () {
  10371. function InternalPromise(resolver) {
  10372. var _this = this;
  10373. this._state = PromiseStates.Pending;
  10374. this._children = new Array();
  10375. this._rejectWasConsumed = false;
  10376. if (!resolver) {
  10377. return;
  10378. }
  10379. try {
  10380. resolver(function (value) {
  10381. _this._resolve(value);
  10382. }, function (reason) {
  10383. _this._reject(reason);
  10384. });
  10385. }
  10386. catch (e) {
  10387. this._reject(e);
  10388. }
  10389. }
  10390. Object.defineProperty(InternalPromise.prototype, "_result", {
  10391. get: function () {
  10392. return this._resultValue;
  10393. },
  10394. set: function (value) {
  10395. this._resultValue = value;
  10396. if (this._parent && this._parent._result === undefined) {
  10397. this._parent._result = value;
  10398. }
  10399. },
  10400. enumerable: true,
  10401. configurable: true
  10402. });
  10403. InternalPromise.prototype.catch = function (onRejected) {
  10404. return this.then(undefined, onRejected);
  10405. };
  10406. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10407. var _this = this;
  10408. var newPromise = new InternalPromise();
  10409. newPromise._onFulfilled = onFulfilled;
  10410. newPromise._onRejected = onRejected;
  10411. // Composition
  10412. this._children.push(newPromise);
  10413. newPromise._parent = this;
  10414. if (this._state !== PromiseStates.Pending) {
  10415. BABYLON.Tools.SetImmediate(function () {
  10416. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10417. var returnedValue = newPromise._resolve(_this._result);
  10418. if (returnedValue !== undefined && returnedValue !== null) {
  10419. if (returnedValue._state !== undefined) {
  10420. var returnedPromise = returnedValue;
  10421. newPromise._children.push(returnedPromise);
  10422. returnedPromise._parent = newPromise;
  10423. newPromise = returnedPromise;
  10424. }
  10425. else {
  10426. newPromise._result = returnedValue;
  10427. }
  10428. }
  10429. }
  10430. else {
  10431. newPromise._reject(_this._reason);
  10432. }
  10433. });
  10434. }
  10435. return newPromise;
  10436. };
  10437. InternalPromise.prototype._moveChildren = function (children) {
  10438. var _this = this;
  10439. var _a;
  10440. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10441. this._children.forEach(function (child) {
  10442. child._parent = _this;
  10443. });
  10444. if (this._state === PromiseStates.Fulfilled) {
  10445. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10446. var child = _b[_i];
  10447. child._resolve(this._result);
  10448. }
  10449. }
  10450. else if (this._state === PromiseStates.Rejected) {
  10451. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10452. var child = _d[_c];
  10453. child._reject(this._reason);
  10454. }
  10455. }
  10456. };
  10457. InternalPromise.prototype._resolve = function (value) {
  10458. try {
  10459. this._state = PromiseStates.Fulfilled;
  10460. var returnedValue = null;
  10461. if (this._onFulfilled) {
  10462. returnedValue = this._onFulfilled(value);
  10463. }
  10464. if (returnedValue !== undefined && returnedValue !== null) {
  10465. if (returnedValue._state !== undefined) {
  10466. // Transmit children
  10467. var returnedPromise = returnedValue;
  10468. returnedPromise._parent = this;
  10469. returnedPromise._moveChildren(this._children);
  10470. value = returnedPromise._result;
  10471. }
  10472. else {
  10473. value = returnedValue;
  10474. }
  10475. }
  10476. this._result = value;
  10477. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10478. var child = _a[_i];
  10479. child._resolve(value);
  10480. }
  10481. this._children.length = 0;
  10482. delete this._onFulfilled;
  10483. delete this._onRejected;
  10484. }
  10485. catch (e) {
  10486. this._reject(e, true);
  10487. }
  10488. };
  10489. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10490. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10491. this._state = PromiseStates.Rejected;
  10492. this._reason = reason;
  10493. if (this._onRejected && !onLocalThrow) {
  10494. try {
  10495. this._onRejected(reason);
  10496. this._rejectWasConsumed = true;
  10497. }
  10498. catch (e) {
  10499. reason = e;
  10500. }
  10501. }
  10502. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10503. var child = _a[_i];
  10504. if (this._rejectWasConsumed) {
  10505. child._resolve(null);
  10506. }
  10507. else {
  10508. child._reject(reason);
  10509. }
  10510. }
  10511. this._children.length = 0;
  10512. delete this._onFulfilled;
  10513. delete this._onRejected;
  10514. };
  10515. InternalPromise.resolve = function (value) {
  10516. var newPromise = new InternalPromise();
  10517. newPromise._resolve(value);
  10518. return newPromise;
  10519. };
  10520. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10521. promise.then(function (value) {
  10522. agregator.results[index] = value;
  10523. agregator.count++;
  10524. if (agregator.count === agregator.target) {
  10525. agregator.rootPromise._resolve(agregator.results);
  10526. }
  10527. return null;
  10528. }, function (reason) {
  10529. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10530. agregator.rootPromise._reject(reason);
  10531. }
  10532. });
  10533. };
  10534. InternalPromise.all = function (promises) {
  10535. var newPromise = new InternalPromise();
  10536. var agregator = new FulFillmentAgregator();
  10537. agregator.target = promises.length;
  10538. agregator.rootPromise = newPromise;
  10539. if (promises.length) {
  10540. for (var index = 0; index < promises.length; index++) {
  10541. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10542. }
  10543. }
  10544. else {
  10545. newPromise._resolve([]);
  10546. }
  10547. return newPromise;
  10548. };
  10549. InternalPromise.race = function (promises) {
  10550. var newPromise = new InternalPromise();
  10551. if (promises.length) {
  10552. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10553. var promise = promises_1[_i];
  10554. promise.then(function (value) {
  10555. if (newPromise) {
  10556. newPromise._resolve(value);
  10557. newPromise = null;
  10558. }
  10559. return null;
  10560. }, function (reason) {
  10561. if (newPromise) {
  10562. newPromise._reject(reason);
  10563. newPromise = null;
  10564. }
  10565. });
  10566. }
  10567. }
  10568. return newPromise;
  10569. };
  10570. return InternalPromise;
  10571. }());
  10572. /**
  10573. * Helper class that provides a small promise polyfill
  10574. */
  10575. var PromisePolyfill = /** @class */ (function () {
  10576. function PromisePolyfill() {
  10577. }
  10578. /**
  10579. * Static function used to check if the polyfill is required
  10580. * If this is the case then the function will inject the polyfill to window.Promise
  10581. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10582. */
  10583. PromisePolyfill.Apply = function (force) {
  10584. if (force === void 0) { force = false; }
  10585. if (force || typeof Promise === 'undefined') {
  10586. var root = window;
  10587. root.Promise = InternalPromise;
  10588. }
  10589. };
  10590. return PromisePolyfill;
  10591. }());
  10592. BABYLON.PromisePolyfill = PromisePolyfill;
  10593. })(BABYLON || (BABYLON = {}));
  10594. //# sourceMappingURL=babylon.promise.js.map
  10595. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10596. var BABYLON;
  10597. (function (BABYLON) {
  10598. /**
  10599. * Helper class to push actions to a pool of workers.
  10600. */
  10601. var WorkerPool = /** @class */ (function () {
  10602. /**
  10603. * Constructor
  10604. * @param workers Array of workers to use for actions
  10605. */
  10606. function WorkerPool(workers) {
  10607. this._pendingActions = new Array();
  10608. this._workerInfos = workers.map(function (worker) { return ({
  10609. worker: worker,
  10610. active: false
  10611. }); });
  10612. }
  10613. /**
  10614. * Terminates all workers and clears any pending actions.
  10615. */
  10616. WorkerPool.prototype.dispose = function () {
  10617. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10618. var workerInfo = _a[_i];
  10619. workerInfo.worker.terminate();
  10620. }
  10621. delete this._workerInfos;
  10622. delete this._pendingActions;
  10623. };
  10624. /**
  10625. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10626. * pended until a worker has completed its action.
  10627. * @param action The action to perform. Call onComplete when the action is complete.
  10628. */
  10629. WorkerPool.prototype.push = function (action) {
  10630. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10631. var workerInfo = _a[_i];
  10632. if (!workerInfo.active) {
  10633. this._execute(workerInfo, action);
  10634. return;
  10635. }
  10636. }
  10637. this._pendingActions.push(action);
  10638. };
  10639. WorkerPool.prototype._execute = function (workerInfo, action) {
  10640. var _this = this;
  10641. workerInfo.active = true;
  10642. action(workerInfo.worker, function () {
  10643. workerInfo.active = false;
  10644. var nextAction = _this._pendingActions.shift();
  10645. if (nextAction) {
  10646. _this._execute(workerInfo, nextAction);
  10647. }
  10648. });
  10649. };
  10650. return WorkerPool;
  10651. }());
  10652. BABYLON.WorkerPool = WorkerPool;
  10653. })(BABYLON || (BABYLON = {}));
  10654. //# sourceMappingURL=babylon.workerPool.js.map
  10655. var BABYLON;
  10656. (function (BABYLON) {
  10657. /**
  10658. * @hidden
  10659. **/
  10660. var _AlphaState = /** @class */ (function () {
  10661. /**
  10662. * Initializes the state.
  10663. */
  10664. function _AlphaState() {
  10665. this._isAlphaBlendDirty = false;
  10666. this._isBlendFunctionParametersDirty = false;
  10667. this._isBlendEquationParametersDirty = false;
  10668. this._isBlendConstantsDirty = false;
  10669. this._alphaBlend = false;
  10670. this._blendFunctionParameters = new Array(4);
  10671. this._blendEquationParameters = new Array(2);
  10672. this._blendConstants = new Array(4);
  10673. this.reset();
  10674. }
  10675. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10676. get: function () {
  10677. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10678. },
  10679. enumerable: true,
  10680. configurable: true
  10681. });
  10682. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10683. get: function () {
  10684. return this._alphaBlend;
  10685. },
  10686. set: function (value) {
  10687. if (this._alphaBlend === value) {
  10688. return;
  10689. }
  10690. this._alphaBlend = value;
  10691. this._isAlphaBlendDirty = true;
  10692. },
  10693. enumerable: true,
  10694. configurable: true
  10695. });
  10696. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10697. if (this._blendConstants[0] === r &&
  10698. this._blendConstants[1] === g &&
  10699. this._blendConstants[2] === b &&
  10700. this._blendConstants[3] === a) {
  10701. return;
  10702. }
  10703. this._blendConstants[0] = r;
  10704. this._blendConstants[1] = g;
  10705. this._blendConstants[2] = b;
  10706. this._blendConstants[3] = a;
  10707. this._isBlendConstantsDirty = true;
  10708. };
  10709. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10710. if (this._blendFunctionParameters[0] === value0 &&
  10711. this._blendFunctionParameters[1] === value1 &&
  10712. this._blendFunctionParameters[2] === value2 &&
  10713. this._blendFunctionParameters[3] === value3) {
  10714. return;
  10715. }
  10716. this._blendFunctionParameters[0] = value0;
  10717. this._blendFunctionParameters[1] = value1;
  10718. this._blendFunctionParameters[2] = value2;
  10719. this._blendFunctionParameters[3] = value3;
  10720. this._isBlendFunctionParametersDirty = true;
  10721. };
  10722. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10723. if (this._blendEquationParameters[0] === rgb &&
  10724. this._blendEquationParameters[1] === alpha) {
  10725. return;
  10726. }
  10727. this._blendEquationParameters[0] = rgb;
  10728. this._blendEquationParameters[1] = alpha;
  10729. this._isBlendEquationParametersDirty = true;
  10730. };
  10731. _AlphaState.prototype.reset = function () {
  10732. this._alphaBlend = false;
  10733. this._blendFunctionParameters[0] = null;
  10734. this._blendFunctionParameters[1] = null;
  10735. this._blendFunctionParameters[2] = null;
  10736. this._blendFunctionParameters[3] = null;
  10737. this._blendEquationParameters[0] = null;
  10738. this._blendEquationParameters[1] = null;
  10739. this._blendConstants[0] = null;
  10740. this._blendConstants[1] = null;
  10741. this._blendConstants[2] = null;
  10742. this._blendConstants[3] = null;
  10743. this._isAlphaBlendDirty = true;
  10744. this._isBlendFunctionParametersDirty = false;
  10745. this._isBlendEquationParametersDirty = false;
  10746. this._isBlendConstantsDirty = false;
  10747. };
  10748. _AlphaState.prototype.apply = function (gl) {
  10749. if (!this.isDirty) {
  10750. return;
  10751. }
  10752. // Alpha blend
  10753. if (this._isAlphaBlendDirty) {
  10754. if (this._alphaBlend) {
  10755. gl.enable(gl.BLEND);
  10756. }
  10757. else {
  10758. gl.disable(gl.BLEND);
  10759. }
  10760. this._isAlphaBlendDirty = false;
  10761. }
  10762. // Alpha function
  10763. if (this._isBlendFunctionParametersDirty) {
  10764. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10765. this._isBlendFunctionParametersDirty = false;
  10766. }
  10767. // Alpha equation
  10768. if (this._isBlendEquationParametersDirty) {
  10769. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10770. this._isBlendEquationParametersDirty = false;
  10771. }
  10772. // Constants
  10773. if (this._isBlendConstantsDirty) {
  10774. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10775. this._isBlendConstantsDirty = false;
  10776. }
  10777. };
  10778. return _AlphaState;
  10779. }());
  10780. BABYLON._AlphaState = _AlphaState;
  10781. })(BABYLON || (BABYLON = {}));
  10782. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10783. var BABYLON;
  10784. (function (BABYLON) {
  10785. /**
  10786. * @hidden
  10787. **/
  10788. var _DepthCullingState = /** @class */ (function () {
  10789. /**
  10790. * Initializes the state.
  10791. */
  10792. function _DepthCullingState() {
  10793. this._isDepthTestDirty = false;
  10794. this._isDepthMaskDirty = false;
  10795. this._isDepthFuncDirty = false;
  10796. this._isCullFaceDirty = false;
  10797. this._isCullDirty = false;
  10798. this._isZOffsetDirty = false;
  10799. this._isFrontFaceDirty = false;
  10800. this.reset();
  10801. }
  10802. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10803. get: function () {
  10804. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10810. get: function () {
  10811. return this._zOffset;
  10812. },
  10813. set: function (value) {
  10814. if (this._zOffset === value) {
  10815. return;
  10816. }
  10817. this._zOffset = value;
  10818. this._isZOffsetDirty = true;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10824. get: function () {
  10825. return this._cullFace;
  10826. },
  10827. set: function (value) {
  10828. if (this._cullFace === value) {
  10829. return;
  10830. }
  10831. this._cullFace = value;
  10832. this._isCullFaceDirty = true;
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10838. get: function () {
  10839. return this._cull;
  10840. },
  10841. set: function (value) {
  10842. if (this._cull === value) {
  10843. return;
  10844. }
  10845. this._cull = value;
  10846. this._isCullDirty = true;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10852. get: function () {
  10853. return this._depthFunc;
  10854. },
  10855. set: function (value) {
  10856. if (this._depthFunc === value) {
  10857. return;
  10858. }
  10859. this._depthFunc = value;
  10860. this._isDepthFuncDirty = true;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10866. get: function () {
  10867. return this._depthMask;
  10868. },
  10869. set: function (value) {
  10870. if (this._depthMask === value) {
  10871. return;
  10872. }
  10873. this._depthMask = value;
  10874. this._isDepthMaskDirty = true;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10880. get: function () {
  10881. return this._depthTest;
  10882. },
  10883. set: function (value) {
  10884. if (this._depthTest === value) {
  10885. return;
  10886. }
  10887. this._depthTest = value;
  10888. this._isDepthTestDirty = true;
  10889. },
  10890. enumerable: true,
  10891. configurable: true
  10892. });
  10893. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10894. get: function () {
  10895. return this._frontFace;
  10896. },
  10897. set: function (value) {
  10898. if (this._frontFace === value) {
  10899. return;
  10900. }
  10901. this._frontFace = value;
  10902. this._isFrontFaceDirty = true;
  10903. },
  10904. enumerable: true,
  10905. configurable: true
  10906. });
  10907. _DepthCullingState.prototype.reset = function () {
  10908. this._depthMask = true;
  10909. this._depthTest = true;
  10910. this._depthFunc = null;
  10911. this._cullFace = null;
  10912. this._cull = null;
  10913. this._zOffset = 0;
  10914. this._frontFace = null;
  10915. this._isDepthTestDirty = true;
  10916. this._isDepthMaskDirty = true;
  10917. this._isDepthFuncDirty = false;
  10918. this._isCullFaceDirty = false;
  10919. this._isCullDirty = false;
  10920. this._isZOffsetDirty = false;
  10921. this._isFrontFaceDirty = false;
  10922. };
  10923. _DepthCullingState.prototype.apply = function (gl) {
  10924. if (!this.isDirty) {
  10925. return;
  10926. }
  10927. // Cull
  10928. if (this._isCullDirty) {
  10929. if (this.cull) {
  10930. gl.enable(gl.CULL_FACE);
  10931. }
  10932. else {
  10933. gl.disable(gl.CULL_FACE);
  10934. }
  10935. this._isCullDirty = false;
  10936. }
  10937. // Cull face
  10938. if (this._isCullFaceDirty) {
  10939. gl.cullFace(this.cullFace);
  10940. this._isCullFaceDirty = false;
  10941. }
  10942. // Depth mask
  10943. if (this._isDepthMaskDirty) {
  10944. gl.depthMask(this.depthMask);
  10945. this._isDepthMaskDirty = false;
  10946. }
  10947. // Depth test
  10948. if (this._isDepthTestDirty) {
  10949. if (this.depthTest) {
  10950. gl.enable(gl.DEPTH_TEST);
  10951. }
  10952. else {
  10953. gl.disable(gl.DEPTH_TEST);
  10954. }
  10955. this._isDepthTestDirty = false;
  10956. }
  10957. // Depth func
  10958. if (this._isDepthFuncDirty) {
  10959. gl.depthFunc(this.depthFunc);
  10960. this._isDepthFuncDirty = false;
  10961. }
  10962. // zOffset
  10963. if (this._isZOffsetDirty) {
  10964. if (this.zOffset) {
  10965. gl.enable(gl.POLYGON_OFFSET_FILL);
  10966. gl.polygonOffset(this.zOffset, 0);
  10967. }
  10968. else {
  10969. gl.disable(gl.POLYGON_OFFSET_FILL);
  10970. }
  10971. this._isZOffsetDirty = false;
  10972. }
  10973. // Front face
  10974. if (this._isFrontFaceDirty) {
  10975. gl.frontFace(this.frontFace);
  10976. this._isFrontFaceDirty = false;
  10977. }
  10978. };
  10979. return _DepthCullingState;
  10980. }());
  10981. BABYLON._DepthCullingState = _DepthCullingState;
  10982. })(BABYLON || (BABYLON = {}));
  10983. //# sourceMappingURL=babylon.depthCullingState.js.map
  10984. var BABYLON;
  10985. (function (BABYLON) {
  10986. /**
  10987. * @hidden
  10988. **/
  10989. var _StencilState = /** @class */ (function () {
  10990. function _StencilState() {
  10991. this._isStencilTestDirty = false;
  10992. this._isStencilMaskDirty = false;
  10993. this._isStencilFuncDirty = false;
  10994. this._isStencilOpDirty = false;
  10995. this.reset();
  10996. }
  10997. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10998. get: function () {
  10999. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11000. },
  11001. enumerable: true,
  11002. configurable: true
  11003. });
  11004. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11005. get: function () {
  11006. return this._stencilFunc;
  11007. },
  11008. set: function (value) {
  11009. if (this._stencilFunc === value) {
  11010. return;
  11011. }
  11012. this._stencilFunc = value;
  11013. this._isStencilFuncDirty = true;
  11014. },
  11015. enumerable: true,
  11016. configurable: true
  11017. });
  11018. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11019. get: function () {
  11020. return this._stencilFuncRef;
  11021. },
  11022. set: function (value) {
  11023. if (this._stencilFuncRef === value) {
  11024. return;
  11025. }
  11026. this._stencilFuncRef = value;
  11027. this._isStencilFuncDirty = true;
  11028. },
  11029. enumerable: true,
  11030. configurable: true
  11031. });
  11032. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11033. get: function () {
  11034. return this._stencilFuncMask;
  11035. },
  11036. set: function (value) {
  11037. if (this._stencilFuncMask === value) {
  11038. return;
  11039. }
  11040. this._stencilFuncMask = value;
  11041. this._isStencilFuncDirty = true;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11047. get: function () {
  11048. return this._stencilOpStencilFail;
  11049. },
  11050. set: function (value) {
  11051. if (this._stencilOpStencilFail === value) {
  11052. return;
  11053. }
  11054. this._stencilOpStencilFail = value;
  11055. this._isStencilOpDirty = true;
  11056. },
  11057. enumerable: true,
  11058. configurable: true
  11059. });
  11060. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11061. get: function () {
  11062. return this._stencilOpDepthFail;
  11063. },
  11064. set: function (value) {
  11065. if (this._stencilOpDepthFail === value) {
  11066. return;
  11067. }
  11068. this._stencilOpDepthFail = value;
  11069. this._isStencilOpDirty = true;
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11075. get: function () {
  11076. return this._stencilOpStencilDepthPass;
  11077. },
  11078. set: function (value) {
  11079. if (this._stencilOpStencilDepthPass === value) {
  11080. return;
  11081. }
  11082. this._stencilOpStencilDepthPass = value;
  11083. this._isStencilOpDirty = true;
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11089. get: function () {
  11090. return this._stencilMask;
  11091. },
  11092. set: function (value) {
  11093. if (this._stencilMask === value) {
  11094. return;
  11095. }
  11096. this._stencilMask = value;
  11097. this._isStencilMaskDirty = true;
  11098. },
  11099. enumerable: true,
  11100. configurable: true
  11101. });
  11102. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11103. get: function () {
  11104. return this._stencilTest;
  11105. },
  11106. set: function (value) {
  11107. if (this._stencilTest === value) {
  11108. return;
  11109. }
  11110. this._stencilTest = value;
  11111. this._isStencilTestDirty = true;
  11112. },
  11113. enumerable: true,
  11114. configurable: true
  11115. });
  11116. _StencilState.prototype.reset = function () {
  11117. this._stencilTest = false;
  11118. this._stencilMask = 0xFF;
  11119. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11120. this._stencilFuncRef = 1;
  11121. this._stencilFuncMask = 0xFF;
  11122. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11123. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11124. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11125. this._isStencilTestDirty = true;
  11126. this._isStencilMaskDirty = true;
  11127. this._isStencilFuncDirty = true;
  11128. this._isStencilOpDirty = true;
  11129. };
  11130. _StencilState.prototype.apply = function (gl) {
  11131. if (!this.isDirty) {
  11132. return;
  11133. }
  11134. // Stencil test
  11135. if (this._isStencilTestDirty) {
  11136. if (this.stencilTest) {
  11137. gl.enable(gl.STENCIL_TEST);
  11138. }
  11139. else {
  11140. gl.disable(gl.STENCIL_TEST);
  11141. }
  11142. this._isStencilTestDirty = false;
  11143. }
  11144. // Stencil mask
  11145. if (this._isStencilMaskDirty) {
  11146. gl.stencilMask(this.stencilMask);
  11147. this._isStencilMaskDirty = false;
  11148. }
  11149. // Stencil func
  11150. if (this._isStencilFuncDirty) {
  11151. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11152. this._isStencilFuncDirty = false;
  11153. }
  11154. // Stencil op
  11155. if (this._isStencilOpDirty) {
  11156. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11157. this._isStencilOpDirty = false;
  11158. }
  11159. };
  11160. return _StencilState;
  11161. }());
  11162. BABYLON._StencilState = _StencilState;
  11163. })(BABYLON || (BABYLON = {}));
  11164. //# sourceMappingURL=babylon.stencilState.js.map
  11165. var __assign = (this && this.__assign) || function () {
  11166. __assign = Object.assign || function(t) {
  11167. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11168. s = arguments[i];
  11169. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11170. t[p] = s[p];
  11171. }
  11172. return t;
  11173. };
  11174. return __assign.apply(this, arguments);
  11175. };
  11176. var BABYLON;
  11177. (function (BABYLON) {
  11178. /**
  11179. * Keeps track of all the buffer info used in engine.
  11180. */
  11181. var BufferPointer = /** @class */ (function () {
  11182. function BufferPointer() {
  11183. }
  11184. return BufferPointer;
  11185. }());
  11186. /**
  11187. * Interface for attribute information associated with buffer instanciation
  11188. */
  11189. var InstancingAttributeInfo = /** @class */ (function () {
  11190. function InstancingAttributeInfo() {
  11191. }
  11192. return InstancingAttributeInfo;
  11193. }());
  11194. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11195. /**
  11196. * Define options used to create a render target texture
  11197. */
  11198. var RenderTargetCreationOptions = /** @class */ (function () {
  11199. function RenderTargetCreationOptions() {
  11200. }
  11201. return RenderTargetCreationOptions;
  11202. }());
  11203. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11204. /**
  11205. * Define options used to create a depth texture
  11206. */
  11207. var DepthTextureCreationOptions = /** @class */ (function () {
  11208. function DepthTextureCreationOptions() {
  11209. }
  11210. return DepthTextureCreationOptions;
  11211. }());
  11212. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11213. /**
  11214. * Class used to describe the capabilities of the engine relatively to the current browser
  11215. */
  11216. var EngineCapabilities = /** @class */ (function () {
  11217. function EngineCapabilities() {
  11218. }
  11219. return EngineCapabilities;
  11220. }());
  11221. BABYLON.EngineCapabilities = EngineCapabilities;
  11222. /**
  11223. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11224. */
  11225. var Engine = /** @class */ (function () {
  11226. /**
  11227. * Creates a new engine
  11228. * @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
  11229. * @param antialias defines enable antialiasing (default: false)
  11230. * @param options defines further options to be sent to the getContext() function
  11231. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11232. */
  11233. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11234. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11235. var _this = this;
  11236. // Public members
  11237. /**
  11238. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11239. */
  11240. this.forcePOTTextures = false;
  11241. /**
  11242. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11243. */
  11244. this.isFullscreen = false;
  11245. /**
  11246. * Gets a boolean indicating if the pointer is currently locked
  11247. */
  11248. this.isPointerLock = false;
  11249. /**
  11250. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11251. */
  11252. this.cullBackFaces = true;
  11253. /**
  11254. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11255. */
  11256. this.renderEvenInBackground = true;
  11257. /**
  11258. * Gets or sets a boolean indicating that cache can be kept between frames
  11259. */
  11260. this.preventCacheWipeBetweenFrames = false;
  11261. /**
  11262. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11263. **/
  11264. this.enableOfflineSupport = false;
  11265. /**
  11266. * 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)
  11267. **/
  11268. this.disableManifestCheck = false;
  11269. /**
  11270. * Gets the list of created scenes
  11271. */
  11272. this.scenes = new Array();
  11273. /**
  11274. * Gets the list of created postprocesses
  11275. */
  11276. this.postProcesses = new Array();
  11277. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11278. this.validateShaderPrograms = false;
  11279. // Observables
  11280. /**
  11281. * Observable event triggered each time the rendering canvas is resized
  11282. */
  11283. this.onResizeObservable = new BABYLON.Observable();
  11284. /**
  11285. * Observable event triggered each time the canvas loses focus
  11286. */
  11287. this.onCanvasBlurObservable = new BABYLON.Observable();
  11288. /**
  11289. * Observable event triggered each time the canvas gains focus
  11290. */
  11291. this.onCanvasFocusObservable = new BABYLON.Observable();
  11292. /**
  11293. * Observable event triggered each time the canvas receives pointerout event
  11294. */
  11295. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11296. /**
  11297. * Observable event triggered before each texture is initialized
  11298. */
  11299. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11300. //WebVR
  11301. this._vrDisplay = undefined;
  11302. this._vrSupported = false;
  11303. this._vrExclusivePointerMode = false;
  11304. // Uniform buffers list
  11305. /**
  11306. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11307. */
  11308. this.disableUniformBuffers = false;
  11309. /** @hidden */
  11310. this._uniformBuffers = new Array();
  11311. // Observables
  11312. /**
  11313. * Observable raised when the engine begins a new frame
  11314. */
  11315. this.onBeginFrameObservable = new BABYLON.Observable();
  11316. /**
  11317. * Observable raised when the engine ends the current frame
  11318. */
  11319. this.onEndFrameObservable = new BABYLON.Observable();
  11320. /**
  11321. * Observable raised when the engine is about to compile a shader
  11322. */
  11323. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11324. /**
  11325. * Observable raised when the engine has jsut compiled a shader
  11326. */
  11327. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11328. this._windowIsBackground = false;
  11329. this._webGLVersion = 1.0;
  11330. /** @hidden */
  11331. this._badOS = false;
  11332. /** @hidden */
  11333. this._badDesktopOS = false;
  11334. /**
  11335. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11336. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11337. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11338. */
  11339. this.disableTextureBindingOptimization = false;
  11340. /**
  11341. * Observable signaled when VR display mode changes
  11342. */
  11343. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11344. /**
  11345. * Observable signaled when VR request present is complete
  11346. */
  11347. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11348. /**
  11349. * Observable signaled when VR request present starts
  11350. */
  11351. this.onVRRequestPresentStart = new BABYLON.Observable();
  11352. this._colorWrite = true;
  11353. /** @hidden */
  11354. this._drawCalls = new BABYLON.PerfCounter();
  11355. /** @hidden */
  11356. this._textureCollisions = new BABYLON.PerfCounter();
  11357. this._renderingQueueLaunched = false;
  11358. this._activeRenderLoops = new Array();
  11359. // Deterministic lockstepMaxSteps
  11360. this._deterministicLockstep = false;
  11361. this._lockstepMaxSteps = 4;
  11362. // Lost context
  11363. /**
  11364. * Observable signaled when a context lost event is raised
  11365. */
  11366. this.onContextLostObservable = new BABYLON.Observable();
  11367. /**
  11368. * Observable signaled when a context restored event is raised
  11369. */
  11370. this.onContextRestoredObservable = new BABYLON.Observable();
  11371. this._contextWasLost = false;
  11372. this._doNotHandleContextLost = false;
  11373. // FPS
  11374. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11375. this._fps = 60;
  11376. this._deltaTime = 0;
  11377. /**
  11378. * Turn this value on if you want to pause FPS computation when in background
  11379. */
  11380. this.disablePerformanceMonitorInBackground = false;
  11381. // States
  11382. /** @hidden */
  11383. this._depthCullingState = new BABYLON._DepthCullingState();
  11384. /** @hidden */
  11385. this._stencilState = new BABYLON._StencilState();
  11386. /** @hidden */
  11387. this._alphaState = new BABYLON._AlphaState();
  11388. /** @hidden */
  11389. this._alphaMode = Engine.ALPHA_DISABLE;
  11390. // Cache
  11391. this._internalTexturesCache = new Array();
  11392. /** @hidden */
  11393. this._activeChannel = 0;
  11394. this._currentTextureChannel = -1;
  11395. /** @hidden */
  11396. this._boundTexturesCache = {};
  11397. this._compiledEffects = {};
  11398. this._vertexAttribArraysEnabled = [];
  11399. this._uintIndicesCurrentlySet = false;
  11400. this._currentBoundBuffer = new Array();
  11401. /** @hidden */
  11402. this._currentFramebuffer = null;
  11403. this._currentBufferPointers = new Array();
  11404. this._currentInstanceLocations = new Array();
  11405. this._currentInstanceBuffers = new Array();
  11406. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11407. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11408. this._vaoRecordInProgress = false;
  11409. this._mustWipeVertexAttributes = false;
  11410. this._nextFreeTextureSlots = new Array();
  11411. this._maxSimultaneousTextures = 0;
  11412. this._activeRequests = new Array();
  11413. // Hardware supported Compressed Textures
  11414. this._texturesSupported = new Array();
  11415. /**
  11416. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11417. */
  11418. this.premultipliedAlpha = true;
  11419. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11420. this._onVRFullScreenTriggered = function () {
  11421. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11422. //get the old size before we change
  11423. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11424. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11425. //get the width and height, change the render size
  11426. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11427. _this.setHardwareScalingLevel(1);
  11428. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11429. }
  11430. else {
  11431. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11432. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11433. }
  11434. };
  11435. this._unpackFlipYCached = null;
  11436. this._boundUniforms = {};
  11437. // Register promises
  11438. BABYLON.PromisePolyfill.Apply();
  11439. var canvas = null;
  11440. Engine.Instances.push(this);
  11441. if (!canvasOrContext) {
  11442. return;
  11443. }
  11444. options = options || {};
  11445. if (canvasOrContext.getContext) {
  11446. canvas = canvasOrContext;
  11447. this._renderingCanvas = canvas;
  11448. if (antialias != null) {
  11449. options.antialias = antialias;
  11450. }
  11451. if (options.deterministicLockstep === undefined) {
  11452. options.deterministicLockstep = false;
  11453. }
  11454. if (options.lockstepMaxSteps === undefined) {
  11455. options.lockstepMaxSteps = 4;
  11456. }
  11457. if (options.preserveDrawingBuffer === undefined) {
  11458. options.preserveDrawingBuffer = false;
  11459. }
  11460. if (options.audioEngine === undefined) {
  11461. options.audioEngine = true;
  11462. }
  11463. if (options.stencil === undefined) {
  11464. options.stencil = true;
  11465. }
  11466. if (options.premultipliedAlpha === false) {
  11467. this.premultipliedAlpha = false;
  11468. }
  11469. this._deterministicLockstep = options.deterministicLockstep;
  11470. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11471. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11472. // Exceptions
  11473. if (navigator && navigator.userAgent) {
  11474. var ua = navigator.userAgent;
  11475. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11476. var exception = _a[_i];
  11477. var key = exception.key;
  11478. var targets = exception.targets;
  11479. if (ua.indexOf(key) > -1) {
  11480. if (exception.capture && exception.captureConstraint) {
  11481. var capture = exception.capture;
  11482. var constraint = exception.captureConstraint;
  11483. var regex = new RegExp(capture);
  11484. var matches = regex.exec(ua);
  11485. if (matches && matches.length > 0) {
  11486. var capturedValue = parseInt(matches[matches.length - 1]);
  11487. if (capturedValue >= constraint) {
  11488. continue;
  11489. }
  11490. }
  11491. }
  11492. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11493. var target = targets_1[_b];
  11494. switch (target) {
  11495. case "uniformBuffer":
  11496. this.disableUniformBuffers = true;
  11497. break;
  11498. case "textureBindingOptimization":
  11499. this.disableTextureBindingOptimization = true;
  11500. break;
  11501. }
  11502. }
  11503. }
  11504. }
  11505. }
  11506. // GL
  11507. if (!options.disableWebGL2Support) {
  11508. try {
  11509. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11510. if (this._gl) {
  11511. this._webGLVersion = 2.0;
  11512. }
  11513. }
  11514. catch (e) {
  11515. // Do nothing
  11516. }
  11517. }
  11518. if (!this._gl) {
  11519. if (!canvas) {
  11520. throw new Error("The provided canvas is null or undefined.");
  11521. }
  11522. try {
  11523. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11524. }
  11525. catch (e) {
  11526. throw new Error("WebGL not supported");
  11527. }
  11528. }
  11529. if (!this._gl) {
  11530. throw new Error("WebGL not supported");
  11531. }
  11532. this._onCanvasFocus = function () {
  11533. _this.onCanvasFocusObservable.notifyObservers(_this);
  11534. };
  11535. this._onCanvasBlur = function () {
  11536. _this.onCanvasBlurObservable.notifyObservers(_this);
  11537. };
  11538. canvas.addEventListener("focus", this._onCanvasFocus);
  11539. canvas.addEventListener("blur", this._onCanvasBlur);
  11540. this._onBlur = function () {
  11541. if (_this.disablePerformanceMonitorInBackground) {
  11542. _this._performanceMonitor.disable();
  11543. }
  11544. _this._windowIsBackground = true;
  11545. };
  11546. this._onFocus = function () {
  11547. if (_this.disablePerformanceMonitorInBackground) {
  11548. _this._performanceMonitor.enable();
  11549. }
  11550. _this._windowIsBackground = false;
  11551. };
  11552. this._onCanvasPointerOut = function (ev) {
  11553. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11554. };
  11555. window.addEventListener("blur", this._onBlur);
  11556. window.addEventListener("focus", this._onFocus);
  11557. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11558. // Context lost
  11559. if (!this._doNotHandleContextLost) {
  11560. this._onContextLost = function (evt) {
  11561. evt.preventDefault();
  11562. _this._contextWasLost = true;
  11563. BABYLON.Tools.Warn("WebGL context lost.");
  11564. _this.onContextLostObservable.notifyObservers(_this);
  11565. };
  11566. this._onContextRestored = function (evt) {
  11567. // Adding a timeout to avoid race condition at browser level
  11568. setTimeout(function () {
  11569. // Rebuild gl context
  11570. _this._initGLContext();
  11571. // Rebuild effects
  11572. _this._rebuildEffects();
  11573. // Rebuild textures
  11574. _this._rebuildInternalTextures();
  11575. // Rebuild buffers
  11576. _this._rebuildBuffers();
  11577. // Cache
  11578. _this.wipeCaches(true);
  11579. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11580. _this.onContextRestoredObservable.notifyObservers(_this);
  11581. _this._contextWasLost = false;
  11582. }, 0);
  11583. };
  11584. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11585. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11586. }
  11587. }
  11588. else {
  11589. this._gl = canvasOrContext;
  11590. this._renderingCanvas = this._gl.canvas;
  11591. if (this._gl.renderbufferStorageMultisample) {
  11592. this._webGLVersion = 2.0;
  11593. }
  11594. options.stencil = this._gl.getContextAttributes().stencil;
  11595. }
  11596. // Viewport
  11597. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11598. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11599. this.resize();
  11600. this._isStencilEnable = options.stencil ? true : false;
  11601. this._initGLContext();
  11602. if (canvas) {
  11603. // Fullscreen
  11604. this._onFullscreenChange = function () {
  11605. if (document.fullscreen !== undefined) {
  11606. _this.isFullscreen = document.fullscreen;
  11607. }
  11608. else if (document.mozFullScreen !== undefined) {
  11609. _this.isFullscreen = document.mozFullScreen;
  11610. }
  11611. else if (document.webkitIsFullScreen !== undefined) {
  11612. _this.isFullscreen = document.webkitIsFullScreen;
  11613. }
  11614. else if (document.msIsFullScreen !== undefined) {
  11615. _this.isFullscreen = document.msIsFullScreen;
  11616. }
  11617. // Pointer lock
  11618. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11619. canvas.requestPointerLock = canvas.requestPointerLock ||
  11620. canvas.msRequestPointerLock ||
  11621. canvas.mozRequestPointerLock ||
  11622. canvas.webkitRequestPointerLock;
  11623. if (canvas.requestPointerLock) {
  11624. canvas.requestPointerLock();
  11625. }
  11626. }
  11627. };
  11628. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11629. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11630. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11631. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11632. // Pointer lock
  11633. this._onPointerLockChange = function () {
  11634. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11635. document.webkitPointerLockElement === canvas ||
  11636. document.msPointerLockElement === canvas ||
  11637. document.pointerLockElement === canvas);
  11638. };
  11639. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11640. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11641. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11642. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11643. this._onVRDisplayPointerRestricted = function () {
  11644. if (canvas) {
  11645. canvas.requestPointerLock();
  11646. }
  11647. };
  11648. this._onVRDisplayPointerUnrestricted = function () {
  11649. document.exitPointerLock();
  11650. };
  11651. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11652. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11653. }
  11654. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11655. Engine.audioEngine = new BABYLON.AudioEngine();
  11656. }
  11657. // Prepare buffer pointers
  11658. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11659. this._currentBufferPointers[i] = new BufferPointer();
  11660. }
  11661. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11662. // Load WebVR Devices
  11663. if (options.autoEnableWebVR) {
  11664. this.initWebVR();
  11665. }
  11666. // Detect if we are running on a faulty buggy OS.
  11667. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11668. // Detect if we are running on a faulty buggy desktop OS.
  11669. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11670. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11671. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11672. }
  11673. Object.defineProperty(Engine, "LastCreatedEngine", {
  11674. /**
  11675. * Gets the latest created engine
  11676. */
  11677. get: function () {
  11678. if (Engine.Instances.length === 0) {
  11679. return null;
  11680. }
  11681. return Engine.Instances[Engine.Instances.length - 1];
  11682. },
  11683. enumerable: true,
  11684. configurable: true
  11685. });
  11686. Object.defineProperty(Engine, "LastCreatedScene", {
  11687. /**
  11688. * Gets the latest created scene
  11689. */
  11690. get: function () {
  11691. var lastCreatedEngine = Engine.LastCreatedEngine;
  11692. if (!lastCreatedEngine) {
  11693. return null;
  11694. }
  11695. if (lastCreatedEngine.scenes.length === 0) {
  11696. return null;
  11697. }
  11698. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11699. },
  11700. enumerable: true,
  11701. configurable: true
  11702. });
  11703. /**
  11704. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11705. * @param flag defines which part of the materials must be marked as dirty
  11706. * @param predicate defines a predicate used to filter which materials should be affected
  11707. */
  11708. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11709. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11710. var engine = Engine.Instances[engineIndex];
  11711. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11712. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11713. }
  11714. }
  11715. };
  11716. Object.defineProperty(Engine, "Version", {
  11717. /**
  11718. * Returns the current version of the framework
  11719. */
  11720. get: function () {
  11721. return "3.3.0-beta.3";
  11722. },
  11723. enumerable: true,
  11724. configurable: true
  11725. });
  11726. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11727. /**
  11728. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11729. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11730. */
  11731. get: function () {
  11732. return this._vrExclusivePointerMode;
  11733. },
  11734. enumerable: true,
  11735. configurable: true
  11736. });
  11737. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11738. /**
  11739. * Gets a boolean indicating that the engine supports uniform buffers
  11740. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11741. */
  11742. get: function () {
  11743. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11749. /**
  11750. * Gets a boolean indicating that only power of 2 textures are supported
  11751. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11752. */
  11753. get: function () {
  11754. return this._webGLVersion < 2 || this.forcePOTTextures;
  11755. },
  11756. enumerable: true,
  11757. configurable: true
  11758. });
  11759. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11760. /**
  11761. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11762. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11763. */
  11764. get: function () {
  11765. return this._doNotHandleContextLost;
  11766. },
  11767. set: function (value) {
  11768. this._doNotHandleContextLost = value;
  11769. },
  11770. enumerable: true,
  11771. configurable: true
  11772. });
  11773. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11774. /**
  11775. * Gets the performance monitor attached to this engine
  11776. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11777. */
  11778. get: function () {
  11779. return this._performanceMonitor;
  11780. },
  11781. enumerable: true,
  11782. configurable: true
  11783. });
  11784. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11785. /**
  11786. * Gets the list of texture formats supported
  11787. */
  11788. get: function () {
  11789. return this._texturesSupported;
  11790. },
  11791. enumerable: true,
  11792. configurable: true
  11793. });
  11794. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11795. /**
  11796. * Gets the list of texture formats in use
  11797. */
  11798. get: function () {
  11799. return this._textureFormatInUse;
  11800. },
  11801. enumerable: true,
  11802. configurable: true
  11803. });
  11804. Object.defineProperty(Engine.prototype, "currentViewport", {
  11805. /**
  11806. * Gets the current viewport
  11807. */
  11808. get: function () {
  11809. return this._cachedViewport;
  11810. },
  11811. enumerable: true,
  11812. configurable: true
  11813. });
  11814. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11815. /**
  11816. * Gets the default empty texture
  11817. */
  11818. get: function () {
  11819. if (!this._emptyTexture) {
  11820. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11821. }
  11822. return this._emptyTexture;
  11823. },
  11824. enumerable: true,
  11825. configurable: true
  11826. });
  11827. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11828. /**
  11829. * Gets the default empty 3D texture
  11830. */
  11831. get: function () {
  11832. if (!this._emptyTexture3D) {
  11833. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11834. }
  11835. return this._emptyTexture3D;
  11836. },
  11837. enumerable: true,
  11838. configurable: true
  11839. });
  11840. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11841. /**
  11842. * Gets the default empty cube texture
  11843. */
  11844. get: function () {
  11845. if (!this._emptyCubeTexture) {
  11846. var faceData = new Uint8Array(4);
  11847. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11848. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11849. }
  11850. return this._emptyCubeTexture;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Engine.prototype._rebuildInternalTextures = function () {
  11856. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11857. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11858. var internalTexture = currentState_1[_i];
  11859. internalTexture._rebuild();
  11860. }
  11861. };
  11862. Engine.prototype._rebuildEffects = function () {
  11863. for (var key in this._compiledEffects) {
  11864. var effect = this._compiledEffects[key];
  11865. effect._prepareEffect();
  11866. }
  11867. BABYLON.Effect.ResetCache();
  11868. };
  11869. Engine.prototype._rebuildBuffers = function () {
  11870. // Index / Vertex
  11871. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11872. var scene = _a[_i];
  11873. scene.resetCachedMaterial();
  11874. scene._rebuildGeometries();
  11875. scene._rebuildTextures();
  11876. }
  11877. // Uniforms
  11878. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11879. var uniformBuffer = _c[_b];
  11880. uniformBuffer._rebuild();
  11881. }
  11882. };
  11883. Engine.prototype._initGLContext = function () {
  11884. // Caps
  11885. this._caps = new EngineCapabilities();
  11886. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11887. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11888. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11889. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11890. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11891. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11892. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11893. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11894. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11895. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11896. // Infos
  11897. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11898. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11899. if (rendererInfo != null) {
  11900. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11901. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11902. }
  11903. if (!this._glVendor) {
  11904. this._glVendor = "Unknown vendor";
  11905. }
  11906. if (!this._glRenderer) {
  11907. this._glRenderer = "Unknown renderer";
  11908. }
  11909. // Constants
  11910. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11911. if (this._gl.RGBA16F !== 0x881A) {
  11912. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11913. }
  11914. if (this._gl.RGBA32F !== 0x8814) {
  11915. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11916. }
  11917. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11918. this._gl.DEPTH24_STENCIL8 = 35056;
  11919. }
  11920. // Extensions
  11921. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11922. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11923. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11924. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11925. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11926. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11927. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11928. 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');
  11929. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11930. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11931. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11932. this._caps.highPrecisionShaderSupported = true;
  11933. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11934. if (this._caps.timerQuery) {
  11935. if (this._webGLVersion === 1) {
  11936. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11937. }
  11938. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11939. }
  11940. // Checks if some of the format renders first to allow the use of webgl inspector.
  11941. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11942. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11943. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11944. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11945. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11946. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11947. if (this._webGLVersion > 1) {
  11948. this._gl.HALF_FLOAT_OES = 0x140B;
  11949. }
  11950. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11951. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11952. // Draw buffers
  11953. if (this._webGLVersion > 1) {
  11954. this._caps.drawBuffersExtension = true;
  11955. }
  11956. else {
  11957. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11958. if (drawBuffersExtension !== null) {
  11959. this._caps.drawBuffersExtension = true;
  11960. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11961. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11962. for (var i = 0; i < 16; i++) {
  11963. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11964. }
  11965. }
  11966. else {
  11967. this._caps.drawBuffersExtension = false;
  11968. }
  11969. }
  11970. // Depth Texture
  11971. if (this._webGLVersion > 1) {
  11972. this._caps.depthTextureExtension = true;
  11973. }
  11974. else {
  11975. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11976. if (depthTextureExtension != null) {
  11977. this._caps.depthTextureExtension = true;
  11978. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11979. }
  11980. }
  11981. // Vertex array object
  11982. if (this._webGLVersion > 1) {
  11983. this._caps.vertexArrayObject = true;
  11984. }
  11985. else {
  11986. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11987. if (vertexArrayObjectExtension != null) {
  11988. this._caps.vertexArrayObject = true;
  11989. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11990. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11991. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11992. }
  11993. else {
  11994. this._caps.vertexArrayObject = false;
  11995. }
  11996. }
  11997. // Instances count
  11998. if (this._webGLVersion > 1) {
  11999. this._caps.instancedArrays = true;
  12000. }
  12001. else {
  12002. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12003. if (instanceExtension != null) {
  12004. this._caps.instancedArrays = true;
  12005. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12006. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12007. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12008. }
  12009. else {
  12010. this._caps.instancedArrays = false;
  12011. }
  12012. }
  12013. // Intelligently add supported compressed formats in order to check for.
  12014. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12015. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12016. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12017. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12018. if (this._caps.astc)
  12019. this.texturesSupported.push('-astc.ktx');
  12020. if (this._caps.s3tc)
  12021. this.texturesSupported.push('-dxt.ktx');
  12022. if (this._caps.pvrtc)
  12023. this.texturesSupported.push('-pvrtc.ktx');
  12024. if (this._caps.etc2)
  12025. this.texturesSupported.push('-etc2.ktx');
  12026. if (this._caps.etc1)
  12027. this.texturesSupported.push('-etc1.ktx');
  12028. if (this._gl.getShaderPrecisionFormat) {
  12029. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12030. if (highp) {
  12031. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12032. }
  12033. }
  12034. // Depth buffer
  12035. this.setDepthBuffer(true);
  12036. this.setDepthFunctionToLessOrEqual();
  12037. this.setDepthWrite(true);
  12038. // Texture maps
  12039. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12040. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12041. this._nextFreeTextureSlots.push(slot);
  12042. }
  12043. };
  12044. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12045. /**
  12046. * Gets version of the current webGL context
  12047. */
  12048. get: function () {
  12049. return this._webGLVersion;
  12050. },
  12051. enumerable: true,
  12052. configurable: true
  12053. });
  12054. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12055. /**
  12056. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12057. */
  12058. get: function () {
  12059. return this._isStencilEnable;
  12060. },
  12061. enumerable: true,
  12062. configurable: true
  12063. });
  12064. Engine.prototype._prepareWorkingCanvas = function () {
  12065. if (this._workingCanvas) {
  12066. return;
  12067. }
  12068. this._workingCanvas = document.createElement("canvas");
  12069. var context = this._workingCanvas.getContext("2d");
  12070. if (context) {
  12071. this._workingContext = context;
  12072. }
  12073. };
  12074. /**
  12075. * Reset the texture cache to empty state
  12076. */
  12077. Engine.prototype.resetTextureCache = function () {
  12078. for (var key in this._boundTexturesCache) {
  12079. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12080. continue;
  12081. }
  12082. var boundTexture = this._boundTexturesCache[key];
  12083. if (boundTexture) {
  12084. this._removeDesignatedSlot(boundTexture);
  12085. }
  12086. this._boundTexturesCache[key] = null;
  12087. }
  12088. if (!this.disableTextureBindingOptimization) {
  12089. this._nextFreeTextureSlots = [];
  12090. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12091. this._nextFreeTextureSlots.push(slot);
  12092. }
  12093. }
  12094. this._currentTextureChannel = -1;
  12095. };
  12096. /**
  12097. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12098. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12099. * @returns true if engine is in deterministic lock step mode
  12100. */
  12101. Engine.prototype.isDeterministicLockStep = function () {
  12102. return this._deterministicLockstep;
  12103. };
  12104. /**
  12105. * Gets the max steps when engine is running in deterministic lock step
  12106. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12107. * @returns the max steps
  12108. */
  12109. Engine.prototype.getLockstepMaxSteps = function () {
  12110. return this._lockstepMaxSteps;
  12111. };
  12112. /**
  12113. * Gets an object containing information about the current webGL context
  12114. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12115. */
  12116. Engine.prototype.getGlInfo = function () {
  12117. return {
  12118. vendor: this._glVendor,
  12119. renderer: this._glRenderer,
  12120. version: this._glVersion
  12121. };
  12122. };
  12123. /**
  12124. * Gets current aspect ratio
  12125. * @param camera defines the camera to use to get the aspect ratio
  12126. * @param useScreen defines if screen size must be used (or the current render target if any)
  12127. * @returns a number defining the aspect ratio
  12128. */
  12129. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12130. if (useScreen === void 0) { useScreen = false; }
  12131. var viewport = camera.viewport;
  12132. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12133. };
  12134. /**
  12135. * Gets current screen aspect ratio
  12136. * @returns a number defining the aspect ratio
  12137. */
  12138. Engine.prototype.getScreenAspectRatio = function () {
  12139. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12140. };
  12141. /**
  12142. * Gets the current render width
  12143. * @param useScreen defines if screen size must be used (or the current render target if any)
  12144. * @returns a number defining the current render width
  12145. */
  12146. Engine.prototype.getRenderWidth = function (useScreen) {
  12147. if (useScreen === void 0) { useScreen = false; }
  12148. if (!useScreen && this._currentRenderTarget) {
  12149. return this._currentRenderTarget.width;
  12150. }
  12151. return this._gl.drawingBufferWidth;
  12152. };
  12153. /**
  12154. * Gets the current render height
  12155. * @param useScreen defines if screen size must be used (or the current render target if any)
  12156. * @returns a number defining the current render height
  12157. */
  12158. Engine.prototype.getRenderHeight = function (useScreen) {
  12159. if (useScreen === void 0) { useScreen = false; }
  12160. if (!useScreen && this._currentRenderTarget) {
  12161. return this._currentRenderTarget.height;
  12162. }
  12163. return this._gl.drawingBufferHeight;
  12164. };
  12165. /**
  12166. * Gets the HTML canvas attached with the current webGL context
  12167. * @returns a HTML canvas
  12168. */
  12169. Engine.prototype.getRenderingCanvas = function () {
  12170. return this._renderingCanvas;
  12171. };
  12172. /**
  12173. * Gets the client rect of the HTML canvas attached with the current webGL context
  12174. * @returns a client rectanglee
  12175. */
  12176. Engine.prototype.getRenderingCanvasClientRect = function () {
  12177. if (!this._renderingCanvas) {
  12178. return null;
  12179. }
  12180. return this._renderingCanvas.getBoundingClientRect();
  12181. };
  12182. /**
  12183. * Defines the hardware scaling level.
  12184. * By default the hardware scaling level is computed from the window device ratio.
  12185. * 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.
  12186. * @param level defines the level to use
  12187. */
  12188. Engine.prototype.setHardwareScalingLevel = function (level) {
  12189. this._hardwareScalingLevel = level;
  12190. this.resize();
  12191. };
  12192. /**
  12193. * Gets the current hardware scaling level.
  12194. * By default the hardware scaling level is computed from the window device ratio.
  12195. * 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.
  12196. * @returns a number indicating the current hardware scaling level
  12197. */
  12198. Engine.prototype.getHardwareScalingLevel = function () {
  12199. return this._hardwareScalingLevel;
  12200. };
  12201. /**
  12202. * Gets the list of loaded textures
  12203. * @returns an array containing all loaded textures
  12204. */
  12205. Engine.prototype.getLoadedTexturesCache = function () {
  12206. return this._internalTexturesCache;
  12207. };
  12208. /**
  12209. * Gets the object containing all engine capabilities
  12210. * @returns the EngineCapabilities object
  12211. */
  12212. Engine.prototype.getCaps = function () {
  12213. return this._caps;
  12214. };
  12215. Object.defineProperty(Engine.prototype, "drawCalls", {
  12216. /** @hidden */
  12217. get: function () {
  12218. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12219. return 0;
  12220. },
  12221. enumerable: true,
  12222. configurable: true
  12223. });
  12224. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12225. /** @hidden */
  12226. get: function () {
  12227. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12228. return null;
  12229. },
  12230. enumerable: true,
  12231. configurable: true
  12232. });
  12233. /**
  12234. * Gets the current depth function
  12235. * @returns a number defining the depth function
  12236. */
  12237. Engine.prototype.getDepthFunction = function () {
  12238. return this._depthCullingState.depthFunc;
  12239. };
  12240. /**
  12241. * Sets the current depth function
  12242. * @param depthFunc defines the function to use
  12243. */
  12244. Engine.prototype.setDepthFunction = function (depthFunc) {
  12245. this._depthCullingState.depthFunc = depthFunc;
  12246. };
  12247. /**
  12248. * Sets the current depth function to GREATER
  12249. */
  12250. Engine.prototype.setDepthFunctionToGreater = function () {
  12251. this._depthCullingState.depthFunc = this._gl.GREATER;
  12252. };
  12253. /**
  12254. * Sets the current depth function to GEQUAL
  12255. */
  12256. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12257. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12258. };
  12259. /**
  12260. * Sets the current depth function to LESS
  12261. */
  12262. Engine.prototype.setDepthFunctionToLess = function () {
  12263. this._depthCullingState.depthFunc = this._gl.LESS;
  12264. };
  12265. /**
  12266. * Sets the current depth function to LEQUAL
  12267. */
  12268. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12269. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12270. };
  12271. /**
  12272. * Gets a boolean indicating if stencil buffer is enabled
  12273. * @returns the current stencil buffer state
  12274. */
  12275. Engine.prototype.getStencilBuffer = function () {
  12276. return this._stencilState.stencilTest;
  12277. };
  12278. /**
  12279. * Enable or disable the stencil buffer
  12280. * @param enable defines if the stencil buffer must be enabled or disabled
  12281. */
  12282. Engine.prototype.setStencilBuffer = function (enable) {
  12283. this._stencilState.stencilTest = enable;
  12284. };
  12285. /**
  12286. * Gets the current stencil mask
  12287. * @returns a number defining the new stencil mask to use
  12288. */
  12289. Engine.prototype.getStencilMask = function () {
  12290. return this._stencilState.stencilMask;
  12291. };
  12292. /**
  12293. * Sets the current stencil mask
  12294. * @param mask defines the new stencil mask to use
  12295. */
  12296. Engine.prototype.setStencilMask = function (mask) {
  12297. this._stencilState.stencilMask = mask;
  12298. };
  12299. /**
  12300. * Gets the current stencil function
  12301. * @returns a number defining the stencil function to use
  12302. */
  12303. Engine.prototype.getStencilFunction = function () {
  12304. return this._stencilState.stencilFunc;
  12305. };
  12306. /**
  12307. * Gets the current stencil reference value
  12308. * @returns a number defining the stencil reference value to use
  12309. */
  12310. Engine.prototype.getStencilFunctionReference = function () {
  12311. return this._stencilState.stencilFuncRef;
  12312. };
  12313. /**
  12314. * Gets the current stencil mask
  12315. * @returns a number defining the stencil mask to use
  12316. */
  12317. Engine.prototype.getStencilFunctionMask = function () {
  12318. return this._stencilState.stencilFuncMask;
  12319. };
  12320. /**
  12321. * Sets the current stencil function
  12322. * @param stencilFunc defines the new stencil function to use
  12323. */
  12324. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12325. this._stencilState.stencilFunc = stencilFunc;
  12326. };
  12327. /**
  12328. * Sets the current stencil reference
  12329. * @param reference defines the new stencil reference to use
  12330. */
  12331. Engine.prototype.setStencilFunctionReference = function (reference) {
  12332. this._stencilState.stencilFuncRef = reference;
  12333. };
  12334. /**
  12335. * Sets the current stencil mask
  12336. * @param mask defines the new stencil mask to use
  12337. */
  12338. Engine.prototype.setStencilFunctionMask = function (mask) {
  12339. this._stencilState.stencilFuncMask = mask;
  12340. };
  12341. /**
  12342. * Gets the current stencil operation when stencil fails
  12343. * @returns a number defining stencil operation to use when stencil fails
  12344. */
  12345. Engine.prototype.getStencilOperationFail = function () {
  12346. return this._stencilState.stencilOpStencilFail;
  12347. };
  12348. /**
  12349. * Gets the current stencil operation when depth fails
  12350. * @returns a number defining stencil operation to use when depth fails
  12351. */
  12352. Engine.prototype.getStencilOperationDepthFail = function () {
  12353. return this._stencilState.stencilOpDepthFail;
  12354. };
  12355. /**
  12356. * Gets the current stencil operation when stencil passes
  12357. * @returns a number defining stencil operation to use when stencil passes
  12358. */
  12359. Engine.prototype.getStencilOperationPass = function () {
  12360. return this._stencilState.stencilOpStencilDepthPass;
  12361. };
  12362. /**
  12363. * Sets the stencil operation to use when stencil fails
  12364. * @param operation defines the stencil operation to use when stencil fails
  12365. */
  12366. Engine.prototype.setStencilOperationFail = function (operation) {
  12367. this._stencilState.stencilOpStencilFail = operation;
  12368. };
  12369. /**
  12370. * Sets the stencil operation to use when depth fails
  12371. * @param operation defines the stencil operation to use when depth fails
  12372. */
  12373. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12374. this._stencilState.stencilOpDepthFail = operation;
  12375. };
  12376. /**
  12377. * Sets the stencil operation to use when stencil passes
  12378. * @param operation defines the stencil operation to use when stencil passes
  12379. */
  12380. Engine.prototype.setStencilOperationPass = function (operation) {
  12381. this._stencilState.stencilOpStencilDepthPass = operation;
  12382. };
  12383. /**
  12384. * Sets a boolean indicating if the dithering state is enabled or disabled
  12385. * @param value defines the dithering state
  12386. */
  12387. Engine.prototype.setDitheringState = function (value) {
  12388. if (value) {
  12389. this._gl.enable(this._gl.DITHER);
  12390. }
  12391. else {
  12392. this._gl.disable(this._gl.DITHER);
  12393. }
  12394. };
  12395. /**
  12396. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12397. * @param value defines the rasterizer state
  12398. */
  12399. Engine.prototype.setRasterizerState = function (value) {
  12400. if (value) {
  12401. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12402. }
  12403. else {
  12404. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12405. }
  12406. };
  12407. /**
  12408. * stop executing a render loop function and remove it from the execution array
  12409. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12410. */
  12411. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12412. if (!renderFunction) {
  12413. this._activeRenderLoops = [];
  12414. return;
  12415. }
  12416. var index = this._activeRenderLoops.indexOf(renderFunction);
  12417. if (index >= 0) {
  12418. this._activeRenderLoops.splice(index, 1);
  12419. }
  12420. };
  12421. /** @hidden */
  12422. Engine.prototype._renderLoop = function () {
  12423. if (!this._contextWasLost) {
  12424. var shouldRender = true;
  12425. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12426. shouldRender = false;
  12427. }
  12428. if (shouldRender) {
  12429. // Start new frame
  12430. this.beginFrame();
  12431. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12432. var renderFunction = this._activeRenderLoops[index];
  12433. renderFunction();
  12434. }
  12435. // Present
  12436. this.endFrame();
  12437. }
  12438. }
  12439. if (this._activeRenderLoops.length > 0) {
  12440. // Register new frame
  12441. var requester = null;
  12442. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12443. requester = this._vrDisplay;
  12444. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12445. }
  12446. else {
  12447. this._renderingQueueLaunched = false;
  12448. }
  12449. };
  12450. /**
  12451. * Register and execute a render loop. The engine can have more than one render function
  12452. * @param renderFunction defines the function to continuously execute
  12453. */
  12454. Engine.prototype.runRenderLoop = function (renderFunction) {
  12455. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12456. return;
  12457. }
  12458. this._activeRenderLoops.push(renderFunction);
  12459. if (!this._renderingQueueLaunched) {
  12460. this._renderingQueueLaunched = true;
  12461. this._bindedRenderFunction = this._renderLoop.bind(this);
  12462. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12463. }
  12464. };
  12465. /**
  12466. * Toggle full screen mode
  12467. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12468. * @param options defines an option object to be sent to the requestFullscreen function
  12469. */
  12470. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12471. if (this.isFullscreen) {
  12472. BABYLON.Tools.ExitFullscreen();
  12473. }
  12474. else {
  12475. this._pointerLockRequested = requestPointerLock;
  12476. if (this._renderingCanvas) {
  12477. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12478. }
  12479. }
  12480. };
  12481. /**
  12482. * Clear the current render buffer or the current render target (if any is set up)
  12483. * @param color defines the color to use
  12484. * @param backBuffer defines if the back buffer must be cleared
  12485. * @param depth defines if the depth buffer must be cleared
  12486. * @param stencil defines if the stencil buffer must be cleared
  12487. */
  12488. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12489. if (stencil === void 0) { stencil = false; }
  12490. this.applyStates();
  12491. var mode = 0;
  12492. if (backBuffer && color) {
  12493. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12494. mode |= this._gl.COLOR_BUFFER_BIT;
  12495. }
  12496. if (depth) {
  12497. this._gl.clearDepth(1.0);
  12498. mode |= this._gl.DEPTH_BUFFER_BIT;
  12499. }
  12500. if (stencil) {
  12501. this._gl.clearStencil(0);
  12502. mode |= this._gl.STENCIL_BUFFER_BIT;
  12503. }
  12504. this._gl.clear(mode);
  12505. };
  12506. /**
  12507. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12508. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12509. * @param y defines the y-coordinate of the corner of the clear rectangle
  12510. * @param width defines the width of the clear rectangle
  12511. * @param height defines the height of the clear rectangle
  12512. * @param clearColor defines the clear color
  12513. */
  12514. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12515. var gl = this._gl;
  12516. // Save state
  12517. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12518. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12519. // Change state
  12520. gl.enable(gl.SCISSOR_TEST);
  12521. gl.scissor(x, y, width, height);
  12522. // Clear
  12523. this.clear(clearColor, true, true, true);
  12524. // Restore state
  12525. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12526. if (curScissor === true) {
  12527. gl.enable(gl.SCISSOR_TEST);
  12528. }
  12529. else {
  12530. gl.disable(gl.SCISSOR_TEST);
  12531. }
  12532. };
  12533. /** @hidden */
  12534. Engine.prototype._viewport = function (x, y, width, height) {
  12535. if (x !== this._viewportCached.x ||
  12536. y !== this._viewportCached.y ||
  12537. width !== this._viewportCached.z ||
  12538. height !== this._viewportCached.w) {
  12539. this._viewportCached.x = x;
  12540. this._viewportCached.y = y;
  12541. this._viewportCached.z = width;
  12542. this._viewportCached.w = height;
  12543. this._gl.viewport(x, y, width, height);
  12544. }
  12545. };
  12546. /**
  12547. * Set the WebGL's viewport
  12548. * @param viewport defines the viewport element to be used
  12549. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12550. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12551. */
  12552. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12553. var width = requiredWidth || this.getRenderWidth();
  12554. var height = requiredHeight || this.getRenderHeight();
  12555. var x = viewport.x || 0;
  12556. var y = viewport.y || 0;
  12557. this._cachedViewport = viewport;
  12558. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12559. };
  12560. /**
  12561. * Directly set the WebGL Viewport
  12562. * @param x defines the x coordinate of the viewport (in screen space)
  12563. * @param y defines the y coordinate of the viewport (in screen space)
  12564. * @param width defines the width of the viewport (in screen space)
  12565. * @param height defines the height of the viewport (in screen space)
  12566. * @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
  12567. */
  12568. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12569. var currentViewport = this._cachedViewport;
  12570. this._cachedViewport = null;
  12571. this._viewport(x, y, width, height);
  12572. return currentViewport;
  12573. };
  12574. /**
  12575. * Begin a new frame
  12576. */
  12577. Engine.prototype.beginFrame = function () {
  12578. this.onBeginFrameObservable.notifyObservers(this);
  12579. this._measureFps();
  12580. };
  12581. /**
  12582. * Enf the current frame
  12583. */
  12584. Engine.prototype.endFrame = function () {
  12585. // Force a flush in case we are using a bad OS.
  12586. if (this._badOS) {
  12587. this.flushFramebuffer();
  12588. }
  12589. // Submit frame to the vr device, if enabled
  12590. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12591. // TODO: We should only submit the frame if we read frameData successfully.
  12592. this._vrDisplay.submitFrame();
  12593. }
  12594. this.onEndFrameObservable.notifyObservers(this);
  12595. };
  12596. /**
  12597. * Resize the view according to the canvas' size
  12598. */
  12599. Engine.prototype.resize = function () {
  12600. // We're not resizing the size of the canvas while in VR mode & presenting
  12601. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12602. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12603. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12604. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12605. }
  12606. };
  12607. /**
  12608. * Force a specific size of the canvas
  12609. * @param width defines the new canvas' width
  12610. * @param height defines the new canvas' height
  12611. */
  12612. Engine.prototype.setSize = function (width, height) {
  12613. if (!this._renderingCanvas) {
  12614. return;
  12615. }
  12616. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12617. return;
  12618. }
  12619. this._renderingCanvas.width = width;
  12620. this._renderingCanvas.height = height;
  12621. for (var index = 0; index < this.scenes.length; index++) {
  12622. var scene = this.scenes[index];
  12623. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12624. var cam = scene.cameras[camIndex];
  12625. cam._currentRenderId = 0;
  12626. }
  12627. }
  12628. if (this.onResizeObservable.hasObservers) {
  12629. this.onResizeObservable.notifyObservers(this);
  12630. }
  12631. };
  12632. // WebVR functions
  12633. /**
  12634. * Gets a boolean indicating if a webVR device was detected
  12635. * @returns true if a webVR device was detected
  12636. */
  12637. Engine.prototype.isVRDevicePresent = function () {
  12638. return !!this._vrDisplay;
  12639. };
  12640. /**
  12641. * Gets the current webVR device
  12642. * @returns the current webVR device (or null)
  12643. */
  12644. Engine.prototype.getVRDevice = function () {
  12645. return this._vrDisplay;
  12646. };
  12647. /**
  12648. * Initializes a webVR display and starts listening to display change events
  12649. * The onVRDisplayChangedObservable will be notified upon these changes
  12650. * @returns The onVRDisplayChangedObservable
  12651. */
  12652. Engine.prototype.initWebVR = function () {
  12653. this.initWebVRAsync();
  12654. return this.onVRDisplayChangedObservable;
  12655. };
  12656. /**
  12657. * Initializes a webVR display and starts listening to display change events
  12658. * The onVRDisplayChangedObservable will be notified upon these changes
  12659. * @returns A promise containing a VRDisplay and if vr is supported
  12660. */
  12661. Engine.prototype.initWebVRAsync = function () {
  12662. var _this = this;
  12663. var notifyObservers = function () {
  12664. var eventArgs = {
  12665. vrDisplay: _this._vrDisplay,
  12666. vrSupported: _this._vrSupported
  12667. };
  12668. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12669. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12670. };
  12671. if (!this._onVrDisplayConnect) {
  12672. this._onVrDisplayConnect = function (event) {
  12673. _this._vrDisplay = event.display;
  12674. notifyObservers();
  12675. };
  12676. this._onVrDisplayDisconnect = function () {
  12677. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12678. _this._vrDisplay = undefined;
  12679. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12680. notifyObservers();
  12681. };
  12682. this._onVrDisplayPresentChange = function () {
  12683. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12684. };
  12685. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12686. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12687. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12688. }
  12689. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12690. this._webVRInitPromise.then(notifyObservers);
  12691. return this._webVRInitPromise;
  12692. };
  12693. /**
  12694. * Call this function to switch to webVR mode
  12695. * Will do nothing if webVR is not supported or if there is no webVR device
  12696. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12697. */
  12698. Engine.prototype.enableVR = function () {
  12699. var _this = this;
  12700. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12701. var onResolved = function () {
  12702. _this.onVRRequestPresentComplete.notifyObservers(true);
  12703. _this._onVRFullScreenTriggered();
  12704. };
  12705. var onRejected = function () {
  12706. _this.onVRRequestPresentComplete.notifyObservers(false);
  12707. };
  12708. this.onVRRequestPresentStart.notifyObservers(this);
  12709. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12710. }
  12711. };
  12712. /**
  12713. * Call this function to leave webVR mode
  12714. * Will do nothing if webVR is not supported or if there is no webVR device
  12715. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12716. */
  12717. Engine.prototype.disableVR = function () {
  12718. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12719. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12720. }
  12721. };
  12722. Engine.prototype._getVRDisplaysAsync = function () {
  12723. var _this = this;
  12724. return new Promise(function (res, rej) {
  12725. if (navigator.getVRDisplays) {
  12726. navigator.getVRDisplays().then(function (devices) {
  12727. _this._vrSupported = true;
  12728. // note that devices may actually be an empty array. This is fine;
  12729. // we expect this._vrDisplay to be undefined in this case.
  12730. _this._vrDisplay = devices[0];
  12731. res({
  12732. vrDisplay: _this._vrDisplay,
  12733. vrSupported: _this._vrSupported
  12734. });
  12735. });
  12736. }
  12737. else {
  12738. _this._vrDisplay = undefined;
  12739. _this._vrSupported = false;
  12740. res({
  12741. vrDisplay: _this._vrDisplay,
  12742. vrSupported: _this._vrSupported
  12743. });
  12744. }
  12745. });
  12746. };
  12747. /**
  12748. * Binds the frame buffer to the specified texture.
  12749. * @param texture The texture to render to or null for the default canvas
  12750. * @param faceIndex The face of the texture to render to in case of cube texture
  12751. * @param requiredWidth The width of the target to render to
  12752. * @param requiredHeight The height of the target to render to
  12753. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12754. * @param depthStencilTexture The depth stencil texture to use to render
  12755. * @param lodLevel defines le lod level to bind to the frame buffer
  12756. */
  12757. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12758. if (lodLevel === void 0) { lodLevel = 0; }
  12759. if (this._currentRenderTarget) {
  12760. this.unBindFramebuffer(this._currentRenderTarget);
  12761. }
  12762. this._currentRenderTarget = texture;
  12763. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12764. var gl = this._gl;
  12765. if (texture.isCube) {
  12766. if (faceIndex === undefined) {
  12767. faceIndex = 0;
  12768. }
  12769. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12770. if (depthStencilTexture) {
  12771. if (depthStencilTexture._generateStencilBuffer) {
  12772. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12773. }
  12774. else {
  12775. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12776. }
  12777. }
  12778. }
  12779. if (this._cachedViewport && !forceFullscreenViewport) {
  12780. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12781. }
  12782. else {
  12783. if (!requiredWidth) {
  12784. requiredWidth = texture.width;
  12785. if (lodLevel) {
  12786. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12787. }
  12788. }
  12789. if (!requiredHeight) {
  12790. requiredHeight = texture.height;
  12791. if (lodLevel) {
  12792. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12793. }
  12794. }
  12795. this._viewport(0, 0, requiredWidth, requiredHeight);
  12796. }
  12797. this.wipeCaches();
  12798. };
  12799. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12800. if (this._currentFramebuffer !== framebuffer) {
  12801. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12802. this._currentFramebuffer = framebuffer;
  12803. }
  12804. };
  12805. /**
  12806. * Unbind the current render target texture from the webGL context
  12807. * @param texture defines the render target texture to unbind
  12808. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12809. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12810. */
  12811. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12812. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12813. this._currentRenderTarget = null;
  12814. // If MSAA, we need to bitblt back to main texture
  12815. var gl = this._gl;
  12816. if (texture._MSAAFramebuffer) {
  12817. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12818. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12819. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12820. }
  12821. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12822. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12823. gl.generateMipmap(gl.TEXTURE_2D);
  12824. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12825. }
  12826. if (onBeforeUnbind) {
  12827. if (texture._MSAAFramebuffer) {
  12828. // Bind the correct framebuffer
  12829. this.bindUnboundFramebuffer(texture._framebuffer);
  12830. }
  12831. onBeforeUnbind();
  12832. }
  12833. this.bindUnboundFramebuffer(null);
  12834. };
  12835. /**
  12836. * Unbind a list of render target textures from the webGL context
  12837. * This is used only when drawBuffer extension or webGL2 are active
  12838. * @param textures defines the render target textures to unbind
  12839. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12840. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12841. */
  12842. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12843. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12844. this._currentRenderTarget = null;
  12845. // If MSAA, we need to bitblt back to main texture
  12846. var gl = this._gl;
  12847. if (textures[0]._MSAAFramebuffer) {
  12848. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12849. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12850. var attachments = textures[0]._attachments;
  12851. if (!attachments) {
  12852. attachments = new Array(textures.length);
  12853. textures[0]._attachments = attachments;
  12854. }
  12855. for (var i = 0; i < textures.length; i++) {
  12856. var texture = textures[i];
  12857. for (var j = 0; j < attachments.length; j++) {
  12858. attachments[j] = gl.NONE;
  12859. }
  12860. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12861. gl.readBuffer(attachments[i]);
  12862. gl.drawBuffers(attachments);
  12863. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12864. }
  12865. for (var i = 0; i < attachments.length; i++) {
  12866. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12867. }
  12868. gl.drawBuffers(attachments);
  12869. }
  12870. for (var i = 0; i < textures.length; i++) {
  12871. var texture = textures[i];
  12872. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12873. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12874. gl.generateMipmap(gl.TEXTURE_2D);
  12875. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12876. }
  12877. }
  12878. if (onBeforeUnbind) {
  12879. if (textures[0]._MSAAFramebuffer) {
  12880. // Bind the correct framebuffer
  12881. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12882. }
  12883. onBeforeUnbind();
  12884. }
  12885. this.bindUnboundFramebuffer(null);
  12886. };
  12887. /**
  12888. * Force the mipmap generation for the given render target texture
  12889. * @param texture defines the render target texture to use
  12890. */
  12891. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12892. if (texture.generateMipMaps) {
  12893. var gl = this._gl;
  12894. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12895. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12896. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12897. }
  12898. };
  12899. /**
  12900. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12901. */
  12902. Engine.prototype.flushFramebuffer = function () {
  12903. this._gl.flush();
  12904. };
  12905. /**
  12906. * Unbind the current render target and bind the default framebuffer
  12907. */
  12908. Engine.prototype.restoreDefaultFramebuffer = function () {
  12909. if (this._currentRenderTarget) {
  12910. this.unBindFramebuffer(this._currentRenderTarget);
  12911. }
  12912. else {
  12913. this.bindUnboundFramebuffer(null);
  12914. }
  12915. if (this._cachedViewport) {
  12916. this.setViewport(this._cachedViewport);
  12917. }
  12918. this.wipeCaches();
  12919. };
  12920. // UBOs
  12921. /**
  12922. * Create an uniform buffer
  12923. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12924. * @param elements defines the content of the uniform buffer
  12925. * @returns the webGL uniform buffer
  12926. */
  12927. Engine.prototype.createUniformBuffer = function (elements) {
  12928. var ubo = this._gl.createBuffer();
  12929. if (!ubo) {
  12930. throw new Error("Unable to create uniform buffer");
  12931. }
  12932. this.bindUniformBuffer(ubo);
  12933. if (elements instanceof Float32Array) {
  12934. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12935. }
  12936. else {
  12937. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12938. }
  12939. this.bindUniformBuffer(null);
  12940. ubo.references = 1;
  12941. return ubo;
  12942. };
  12943. /**
  12944. * Create a dynamic uniform buffer
  12945. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12946. * @param elements defines the content of the uniform buffer
  12947. * @returns the webGL uniform buffer
  12948. */
  12949. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12950. var ubo = this._gl.createBuffer();
  12951. if (!ubo) {
  12952. throw new Error("Unable to create dynamic uniform buffer");
  12953. }
  12954. this.bindUniformBuffer(ubo);
  12955. if (elements instanceof Float32Array) {
  12956. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12957. }
  12958. else {
  12959. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12960. }
  12961. this.bindUniformBuffer(null);
  12962. ubo.references = 1;
  12963. return ubo;
  12964. };
  12965. /**
  12966. * Update an existing uniform buffer
  12967. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12968. * @param uniformBuffer defines the target uniform buffer
  12969. * @param elements defines the content to update
  12970. * @param offset defines the offset in the uniform buffer where update should start
  12971. * @param count defines the size of the data to update
  12972. */
  12973. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12974. this.bindUniformBuffer(uniformBuffer);
  12975. if (offset === undefined) {
  12976. offset = 0;
  12977. }
  12978. if (count === undefined) {
  12979. if (elements instanceof Float32Array) {
  12980. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12981. }
  12982. else {
  12983. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12984. }
  12985. }
  12986. else {
  12987. if (elements instanceof Float32Array) {
  12988. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12989. }
  12990. else {
  12991. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12992. }
  12993. }
  12994. this.bindUniformBuffer(null);
  12995. };
  12996. // VBOs
  12997. Engine.prototype._resetVertexBufferBinding = function () {
  12998. this.bindArrayBuffer(null);
  12999. this._cachedVertexBuffers = null;
  13000. };
  13001. /**
  13002. * Creates a vertex buffer
  13003. * @param data the data for the vertex buffer
  13004. * @returns the new WebGL static buffer
  13005. */
  13006. Engine.prototype.createVertexBuffer = function (data) {
  13007. var vbo = this._gl.createBuffer();
  13008. if (!vbo) {
  13009. throw new Error("Unable to create vertex buffer");
  13010. }
  13011. this.bindArrayBuffer(vbo);
  13012. if (data instanceof Array) {
  13013. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13014. }
  13015. else {
  13016. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13017. }
  13018. this._resetVertexBufferBinding();
  13019. vbo.references = 1;
  13020. return vbo;
  13021. };
  13022. /**
  13023. * Creates a dynamic vertex buffer
  13024. * @param data the data for the dynamic vertex buffer
  13025. * @returns the new WebGL dynamic buffer
  13026. */
  13027. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13028. var vbo = this._gl.createBuffer();
  13029. if (!vbo) {
  13030. throw new Error("Unable to create dynamic vertex buffer");
  13031. }
  13032. this.bindArrayBuffer(vbo);
  13033. if (data instanceof Array) {
  13034. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13035. }
  13036. else {
  13037. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13038. }
  13039. this._resetVertexBufferBinding();
  13040. vbo.references = 1;
  13041. return vbo;
  13042. };
  13043. /**
  13044. * Update a dynamic index buffer
  13045. * @param indexBuffer defines the target index buffer
  13046. * @param indices defines the data to update
  13047. * @param offset defines the offset in the target index buffer where update should start
  13048. */
  13049. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13050. if (offset === void 0) { offset = 0; }
  13051. // Force cache update
  13052. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13053. this.bindIndexBuffer(indexBuffer);
  13054. var arrayBuffer;
  13055. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13056. arrayBuffer = indices;
  13057. }
  13058. else {
  13059. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13060. }
  13061. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13062. this._resetIndexBufferBinding();
  13063. };
  13064. /**
  13065. * Updates a dynamic vertex buffer.
  13066. * @param vertexBuffer the vertex buffer to update
  13067. * @param data the data used to update the vertex buffer
  13068. * @param byteOffset the byte offset of the data
  13069. * @param byteLength the byte length of the data
  13070. */
  13071. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13072. this.bindArrayBuffer(vertexBuffer);
  13073. if (byteOffset === undefined) {
  13074. byteOffset = 0;
  13075. }
  13076. if (byteLength === undefined) {
  13077. if (data instanceof Array) {
  13078. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13079. }
  13080. else {
  13081. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13082. }
  13083. }
  13084. else {
  13085. if (data instanceof Array) {
  13086. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13087. }
  13088. else {
  13089. if (data instanceof ArrayBuffer) {
  13090. data = new Uint8Array(data, byteOffset, byteLength);
  13091. }
  13092. else {
  13093. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13094. }
  13095. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13096. }
  13097. }
  13098. this._resetVertexBufferBinding();
  13099. };
  13100. Engine.prototype._resetIndexBufferBinding = function () {
  13101. this.bindIndexBuffer(null);
  13102. this._cachedIndexBuffer = null;
  13103. };
  13104. /**
  13105. * Creates a new index buffer
  13106. * @param indices defines the content of the index buffer
  13107. * @param updatable defines if the index buffer must be updatable
  13108. * @returns a new webGL buffer
  13109. */
  13110. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13111. var vbo = this._gl.createBuffer();
  13112. if (!vbo) {
  13113. throw new Error("Unable to create index buffer");
  13114. }
  13115. this.bindIndexBuffer(vbo);
  13116. // Check for 32 bits indices
  13117. var arrayBuffer;
  13118. var need32Bits = false;
  13119. if (indices instanceof Uint16Array) {
  13120. arrayBuffer = indices;
  13121. }
  13122. else {
  13123. //check 32 bit support
  13124. if (this._caps.uintIndices) {
  13125. if (indices instanceof Uint32Array) {
  13126. arrayBuffer = indices;
  13127. need32Bits = true;
  13128. }
  13129. else {
  13130. //number[] or Int32Array, check if 32 bit is necessary
  13131. for (var index = 0; index < indices.length; index++) {
  13132. if (indices[index] > 65535) {
  13133. need32Bits = true;
  13134. break;
  13135. }
  13136. }
  13137. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13138. }
  13139. }
  13140. else {
  13141. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13142. arrayBuffer = new Uint16Array(indices);
  13143. }
  13144. }
  13145. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13146. this._resetIndexBufferBinding();
  13147. vbo.references = 1;
  13148. vbo.is32Bits = need32Bits;
  13149. return vbo;
  13150. };
  13151. /**
  13152. * Bind a webGL buffer to the webGL context
  13153. * @param buffer defines the buffer to bind
  13154. */
  13155. Engine.prototype.bindArrayBuffer = function (buffer) {
  13156. if (!this._vaoRecordInProgress) {
  13157. this._unbindVertexArrayObject();
  13158. }
  13159. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13160. };
  13161. /**
  13162. * Bind an uniform buffer to the current webGL context
  13163. * @param buffer defines the buffer to bind
  13164. */
  13165. Engine.prototype.bindUniformBuffer = function (buffer) {
  13166. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13167. };
  13168. /**
  13169. * Bind a buffer to the current webGL context at a given location
  13170. * @param buffer defines the buffer to bind
  13171. * @param location defines the index where to bind the buffer
  13172. */
  13173. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13174. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13175. };
  13176. /**
  13177. * Bind a specific block at a given index in a specific shader program
  13178. * @param shaderProgram defines the shader program
  13179. * @param blockName defines the block name
  13180. * @param index defines the index where to bind the block
  13181. */
  13182. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13183. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13184. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13185. };
  13186. ;
  13187. Engine.prototype.bindIndexBuffer = function (buffer) {
  13188. if (!this._vaoRecordInProgress) {
  13189. this._unbindVertexArrayObject();
  13190. }
  13191. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13192. };
  13193. Engine.prototype.bindBuffer = function (buffer, target) {
  13194. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13195. this._gl.bindBuffer(target, buffer);
  13196. this._currentBoundBuffer[target] = buffer;
  13197. }
  13198. };
  13199. /**
  13200. * update the bound buffer with the given data
  13201. * @param data defines the data to update
  13202. */
  13203. Engine.prototype.updateArrayBuffer = function (data) {
  13204. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13205. };
  13206. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13207. var pointer = this._currentBufferPointers[indx];
  13208. var changed = false;
  13209. if (!pointer.active) {
  13210. changed = true;
  13211. pointer.active = true;
  13212. pointer.index = indx;
  13213. pointer.size = size;
  13214. pointer.type = type;
  13215. pointer.normalized = normalized;
  13216. pointer.stride = stride;
  13217. pointer.offset = offset;
  13218. pointer.buffer = buffer;
  13219. }
  13220. else {
  13221. if (pointer.buffer !== buffer) {
  13222. pointer.buffer = buffer;
  13223. changed = true;
  13224. }
  13225. if (pointer.size !== size) {
  13226. pointer.size = size;
  13227. changed = true;
  13228. }
  13229. if (pointer.type !== type) {
  13230. pointer.type = type;
  13231. changed = true;
  13232. }
  13233. if (pointer.normalized !== normalized) {
  13234. pointer.normalized = normalized;
  13235. changed = true;
  13236. }
  13237. if (pointer.stride !== stride) {
  13238. pointer.stride = stride;
  13239. changed = true;
  13240. }
  13241. if (pointer.offset !== offset) {
  13242. pointer.offset = offset;
  13243. changed = true;
  13244. }
  13245. }
  13246. if (changed || this._vaoRecordInProgress) {
  13247. this.bindArrayBuffer(buffer);
  13248. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13249. }
  13250. };
  13251. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13252. if (indexBuffer == null) {
  13253. return;
  13254. }
  13255. if (this._cachedIndexBuffer !== indexBuffer) {
  13256. this._cachedIndexBuffer = indexBuffer;
  13257. this.bindIndexBuffer(indexBuffer);
  13258. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13259. }
  13260. };
  13261. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13262. var attributes = effect.getAttributesNames();
  13263. if (!this._vaoRecordInProgress) {
  13264. this._unbindVertexArrayObject();
  13265. }
  13266. this.unbindAllAttributes();
  13267. for (var index = 0; index < attributes.length; index++) {
  13268. var order = effect.getAttributeLocation(index);
  13269. if (order >= 0) {
  13270. var vertexBuffer = vertexBuffers[attributes[index]];
  13271. if (!vertexBuffer) {
  13272. continue;
  13273. }
  13274. this._gl.enableVertexAttribArray(order);
  13275. if (!this._vaoRecordInProgress) {
  13276. this._vertexAttribArraysEnabled[order] = true;
  13277. }
  13278. var buffer = vertexBuffer.getBuffer();
  13279. if (buffer) {
  13280. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13281. if (vertexBuffer.getIsInstanced()) {
  13282. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13283. if (!this._vaoRecordInProgress) {
  13284. this._currentInstanceLocations.push(order);
  13285. this._currentInstanceBuffers.push(buffer);
  13286. }
  13287. }
  13288. }
  13289. }
  13290. }
  13291. };
  13292. /**
  13293. * Records a vertex array object
  13294. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13295. * @param vertexBuffers defines the list of vertex buffers to store
  13296. * @param indexBuffer defines the index buffer to store
  13297. * @param effect defines the effect to store
  13298. * @returns the new vertex array object
  13299. */
  13300. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13301. var vao = this._gl.createVertexArray();
  13302. this._vaoRecordInProgress = true;
  13303. this._gl.bindVertexArray(vao);
  13304. this._mustWipeVertexAttributes = true;
  13305. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13306. this.bindIndexBuffer(indexBuffer);
  13307. this._vaoRecordInProgress = false;
  13308. this._gl.bindVertexArray(null);
  13309. return vao;
  13310. };
  13311. /**
  13312. * Bind a specific vertex array object
  13313. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13314. * @param vertexArrayObject defines the vertex array object to bind
  13315. * @param indexBuffer defines the index buffer to bind
  13316. */
  13317. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13318. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13319. this._cachedVertexArrayObject = vertexArrayObject;
  13320. this._gl.bindVertexArray(vertexArrayObject);
  13321. this._cachedVertexBuffers = null;
  13322. this._cachedIndexBuffer = null;
  13323. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13324. this._mustWipeVertexAttributes = true;
  13325. }
  13326. };
  13327. /**
  13328. * Bind webGl buffers directly to the webGL context
  13329. * @param vertexBuffer defines the vertex buffer to bind
  13330. * @param indexBuffer defines the index buffer to bind
  13331. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13332. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13333. * @param effect defines the effect associated with the vertex buffer
  13334. */
  13335. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13336. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13337. this._cachedVertexBuffers = vertexBuffer;
  13338. this._cachedEffectForVertexBuffers = effect;
  13339. var attributesCount = effect.getAttributesCount();
  13340. this._unbindVertexArrayObject();
  13341. this.unbindAllAttributes();
  13342. var offset = 0;
  13343. for (var index = 0; index < attributesCount; index++) {
  13344. if (index < vertexDeclaration.length) {
  13345. var order = effect.getAttributeLocation(index);
  13346. if (order >= 0) {
  13347. this._gl.enableVertexAttribArray(order);
  13348. this._vertexAttribArraysEnabled[order] = true;
  13349. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13350. }
  13351. offset += vertexDeclaration[index] * 4;
  13352. }
  13353. }
  13354. }
  13355. this._bindIndexBufferWithCache(indexBuffer);
  13356. };
  13357. Engine.prototype._unbindVertexArrayObject = function () {
  13358. if (!this._cachedVertexArrayObject) {
  13359. return;
  13360. }
  13361. this._cachedVertexArrayObject = null;
  13362. this._gl.bindVertexArray(null);
  13363. };
  13364. /**
  13365. * Bind a list of vertex buffers to the webGL context
  13366. * @param vertexBuffers defines the list of vertex buffers to bind
  13367. * @param indexBuffer defines the index buffer to bind
  13368. * @param effect defines the effect associated with the vertex buffers
  13369. */
  13370. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13371. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13372. this._cachedVertexBuffers = vertexBuffers;
  13373. this._cachedEffectForVertexBuffers = effect;
  13374. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13375. }
  13376. this._bindIndexBufferWithCache(indexBuffer);
  13377. };
  13378. /**
  13379. * Unbind all instance attributes
  13380. */
  13381. Engine.prototype.unbindInstanceAttributes = function () {
  13382. var boundBuffer;
  13383. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13384. var instancesBuffer = this._currentInstanceBuffers[i];
  13385. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13386. boundBuffer = instancesBuffer;
  13387. this.bindArrayBuffer(instancesBuffer);
  13388. }
  13389. var offsetLocation = this._currentInstanceLocations[i];
  13390. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13391. }
  13392. this._currentInstanceBuffers.length = 0;
  13393. this._currentInstanceLocations.length = 0;
  13394. };
  13395. /**
  13396. * Release and free the memory of a vertex array object
  13397. * @param vao defines the vertex array object to delete
  13398. */
  13399. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13400. this._gl.deleteVertexArray(vao);
  13401. };
  13402. /** @hidden */
  13403. Engine.prototype._releaseBuffer = function (buffer) {
  13404. buffer.references--;
  13405. if (buffer.references === 0) {
  13406. this._gl.deleteBuffer(buffer);
  13407. return true;
  13408. }
  13409. return false;
  13410. };
  13411. /**
  13412. * Creates a webGL buffer to use with instanciation
  13413. * @param capacity defines the size of the buffer
  13414. * @returns the webGL buffer
  13415. */
  13416. Engine.prototype.createInstancesBuffer = function (capacity) {
  13417. var buffer = this._gl.createBuffer();
  13418. if (!buffer) {
  13419. throw new Error("Unable to create instance buffer");
  13420. }
  13421. buffer.capacity = capacity;
  13422. this.bindArrayBuffer(buffer);
  13423. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13424. return buffer;
  13425. };
  13426. /**
  13427. * Delete a webGL buffer used with instanciation
  13428. * @param buffer defines the webGL buffer to delete
  13429. */
  13430. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13431. this._gl.deleteBuffer(buffer);
  13432. };
  13433. /**
  13434. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13435. * @param instancesBuffer defines the webGL buffer to update and bind
  13436. * @param data defines the data to store in the buffer
  13437. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13438. */
  13439. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13440. this.bindArrayBuffer(instancesBuffer);
  13441. if (data) {
  13442. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13443. }
  13444. if (offsetLocations[0].index !== undefined) {
  13445. var stride = 0;
  13446. for (var i = 0; i < offsetLocations.length; i++) {
  13447. var ai = offsetLocations[i];
  13448. stride += ai.attributeSize * 4;
  13449. }
  13450. for (var i = 0; i < offsetLocations.length; i++) {
  13451. var ai = offsetLocations[i];
  13452. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13453. this._gl.enableVertexAttribArray(ai.index);
  13454. this._vertexAttribArraysEnabled[ai.index] = true;
  13455. }
  13456. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13457. this._gl.vertexAttribDivisor(ai.index, 1);
  13458. this._currentInstanceLocations.push(ai.index);
  13459. this._currentInstanceBuffers.push(instancesBuffer);
  13460. }
  13461. }
  13462. else {
  13463. for (var index = 0; index < 4; index++) {
  13464. var offsetLocation = offsetLocations[index];
  13465. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13466. this._gl.enableVertexAttribArray(offsetLocation);
  13467. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13468. }
  13469. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13470. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13471. this._currentInstanceLocations.push(offsetLocation);
  13472. this._currentInstanceBuffers.push(instancesBuffer);
  13473. }
  13474. }
  13475. };
  13476. /**
  13477. * Apply all cached states (depth, culling, stencil and alpha)
  13478. */
  13479. Engine.prototype.applyStates = function () {
  13480. this._depthCullingState.apply(this._gl);
  13481. this._stencilState.apply(this._gl);
  13482. this._alphaState.apply(this._gl);
  13483. };
  13484. /**
  13485. * Send a draw order
  13486. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13487. * @param indexStart defines the starting index
  13488. * @param indexCount defines the number of index to draw
  13489. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13490. */
  13491. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13492. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13493. };
  13494. /**
  13495. * Draw a list of points
  13496. * @param verticesStart defines the index of first vertex to draw
  13497. * @param verticesCount defines the count of vertices to draw
  13498. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13499. */
  13500. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13501. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13502. };
  13503. /**
  13504. * Draw a list of unindexed primitives
  13505. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13506. * @param verticesStart defines the index of first vertex to draw
  13507. * @param verticesCount defines the count of vertices to draw
  13508. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13509. */
  13510. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13511. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13512. };
  13513. /**
  13514. * Draw a list of indexed primitives
  13515. * @param fillMode defines the primitive to use
  13516. * @param indexStart defines the starting index
  13517. * @param indexCount defines the number of index to draw
  13518. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13519. */
  13520. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13521. // Apply states
  13522. this.applyStates();
  13523. this._drawCalls.addCount(1, false);
  13524. // Render
  13525. var drawMode = this._drawMode(fillMode);
  13526. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13527. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13528. if (instancesCount) {
  13529. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13530. }
  13531. else {
  13532. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13533. }
  13534. };
  13535. /**
  13536. * Draw a list of unindexed primitives
  13537. * @param fillMode defines the primitive to use
  13538. * @param verticesStart defines the index of first vertex to draw
  13539. * @param verticesCount defines the count of vertices to draw
  13540. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13541. */
  13542. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13543. // Apply states
  13544. this.applyStates();
  13545. this._drawCalls.addCount(1, false);
  13546. var drawMode = this._drawMode(fillMode);
  13547. if (instancesCount) {
  13548. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13549. }
  13550. else {
  13551. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13552. }
  13553. };
  13554. Engine.prototype._drawMode = function (fillMode) {
  13555. switch (fillMode) {
  13556. // Triangle views
  13557. case BABYLON.Material.TriangleFillMode:
  13558. return this._gl.TRIANGLES;
  13559. case BABYLON.Material.PointFillMode:
  13560. return this._gl.POINTS;
  13561. case BABYLON.Material.WireFrameFillMode:
  13562. return this._gl.LINES;
  13563. // Draw modes
  13564. case BABYLON.Material.PointListDrawMode:
  13565. return this._gl.POINTS;
  13566. case BABYLON.Material.LineListDrawMode:
  13567. return this._gl.LINES;
  13568. case BABYLON.Material.LineLoopDrawMode:
  13569. return this._gl.LINE_LOOP;
  13570. case BABYLON.Material.LineStripDrawMode:
  13571. return this._gl.LINE_STRIP;
  13572. case BABYLON.Material.TriangleStripDrawMode:
  13573. return this._gl.TRIANGLE_STRIP;
  13574. case BABYLON.Material.TriangleFanDrawMode:
  13575. return this._gl.TRIANGLE_FAN;
  13576. default:
  13577. return this._gl.TRIANGLES;
  13578. }
  13579. };
  13580. // Shaders
  13581. /** @hidden */
  13582. Engine.prototype._releaseEffect = function (effect) {
  13583. if (this._compiledEffects[effect._key]) {
  13584. delete this._compiledEffects[effect._key];
  13585. this._deleteProgram(effect.getProgram());
  13586. }
  13587. };
  13588. /** @hidden */
  13589. Engine.prototype._deleteProgram = function (program) {
  13590. if (program) {
  13591. program.__SPECTOR_rebuildProgram = null;
  13592. if (program.transformFeedback) {
  13593. this.deleteTransformFeedback(program.transformFeedback);
  13594. program.transformFeedback = null;
  13595. }
  13596. this._gl.deleteProgram(program);
  13597. }
  13598. };
  13599. /**
  13600. * Create a new effect (used to store vertex/fragment shaders)
  13601. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13602. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13603. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13604. * @param samplers defines an array of string used to represent textures
  13605. * @param defines defines the string containing the defines to use to compile the shaders
  13606. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13607. * @param onCompiled defines a function to call when the effect creation is successful
  13608. * @param onError defines a function to call when the effect creation has failed
  13609. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13610. * @returns the new Effect
  13611. */
  13612. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13613. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13614. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13615. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13616. if (this._compiledEffects[name]) {
  13617. var compiledEffect = this._compiledEffects[name];
  13618. if (onCompiled && compiledEffect.isReady()) {
  13619. onCompiled(compiledEffect);
  13620. }
  13621. return compiledEffect;
  13622. }
  13623. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13624. effect._key = name;
  13625. this._compiledEffects[name] = effect;
  13626. return effect;
  13627. };
  13628. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13629. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13630. };
  13631. ;
  13632. Engine.prototype._compileRawShader = function (source, type) {
  13633. var gl = this._gl;
  13634. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13635. gl.shaderSource(shader, source);
  13636. gl.compileShader(shader);
  13637. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13638. var log = gl.getShaderInfoLog(shader);
  13639. if (log) {
  13640. throw new Error(log);
  13641. }
  13642. }
  13643. if (!shader) {
  13644. throw new Error("Something went wrong while compile the shader.");
  13645. }
  13646. return shader;
  13647. };
  13648. ;
  13649. /**
  13650. * Directly creates a webGL program
  13651. * @param vertexCode defines the vertex shader code to use
  13652. * @param fragmentCode defines the fragment shader code to use
  13653. * @param context defines the webGL context to use (if not set, the current one will be used)
  13654. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13655. * @returns the new webGL program
  13656. */
  13657. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13658. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13659. context = context || this._gl;
  13660. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13661. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13662. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13663. };
  13664. /**
  13665. * Creates a webGL program
  13666. * @param vertexCode defines the vertex shader code to use
  13667. * @param fragmentCode defines the fragment shader code to use
  13668. * @param defines defines the string containing the defines to use to compile the shaders
  13669. * @param context defines the webGL context to use (if not set, the current one will be used)
  13670. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13671. * @returns the new webGL program
  13672. */
  13673. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13674. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13675. context = context || this._gl;
  13676. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13677. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13678. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13679. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13680. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13681. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13682. return program;
  13683. };
  13684. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13685. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13686. var shaderProgram = context.createProgram();
  13687. if (!shaderProgram) {
  13688. throw new Error("Unable to create program");
  13689. }
  13690. context.attachShader(shaderProgram, vertexShader);
  13691. context.attachShader(shaderProgram, fragmentShader);
  13692. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13693. var transformFeedback = this.createTransformFeedback();
  13694. this.bindTransformFeedback(transformFeedback);
  13695. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13696. shaderProgram.transformFeedback = transformFeedback;
  13697. }
  13698. context.linkProgram(shaderProgram);
  13699. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13700. this.bindTransformFeedback(null);
  13701. }
  13702. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13703. if (!linked) {
  13704. var error = context.getProgramInfoLog(shaderProgram);
  13705. if (error) {
  13706. throw new Error(error);
  13707. }
  13708. }
  13709. if (this.validateShaderPrograms) {
  13710. context.validateProgram(shaderProgram);
  13711. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13712. if (!validated) {
  13713. var error = context.getProgramInfoLog(shaderProgram);
  13714. if (error) {
  13715. throw new Error(error);
  13716. }
  13717. }
  13718. }
  13719. context.deleteShader(vertexShader);
  13720. context.deleteShader(fragmentShader);
  13721. return shaderProgram;
  13722. };
  13723. /**
  13724. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13725. * @param shaderProgram defines the webGL program to use
  13726. * @param uniformsNames defines the list of uniform names
  13727. * @returns an array of webGL uniform locations
  13728. */
  13729. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13730. var results = new Array();
  13731. for (var index = 0; index < uniformsNames.length; index++) {
  13732. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13733. }
  13734. return results;
  13735. };
  13736. /**
  13737. * Gets the lsit of active attributes for a given webGL program
  13738. * @param shaderProgram defines the webGL program to use
  13739. * @param attributesNames defines the list of attribute names to get
  13740. * @returns an array of indices indicating the offset of each attribute
  13741. */
  13742. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13743. var results = [];
  13744. for (var index = 0; index < attributesNames.length; index++) {
  13745. try {
  13746. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13747. }
  13748. catch (e) {
  13749. results.push(-1);
  13750. }
  13751. }
  13752. return results;
  13753. };
  13754. /**
  13755. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13756. * @param effect defines the effect to activate
  13757. */
  13758. Engine.prototype.enableEffect = function (effect) {
  13759. if (!effect || effect === this._currentEffect) {
  13760. return;
  13761. }
  13762. // Use program
  13763. this.bindSamplers(effect);
  13764. this._currentEffect = effect;
  13765. if (effect.onBind) {
  13766. effect.onBind(effect);
  13767. }
  13768. if (effect._onBindObservable) {
  13769. effect._onBindObservable.notifyObservers(effect);
  13770. }
  13771. };
  13772. /**
  13773. * Set the value of an uniform to an array of int32
  13774. * @param uniform defines the webGL uniform location where to store the value
  13775. * @param array defines the array of int32 to store
  13776. */
  13777. Engine.prototype.setIntArray = function (uniform, array) {
  13778. if (!uniform)
  13779. return;
  13780. this._gl.uniform1iv(uniform, array);
  13781. };
  13782. /**
  13783. * Set the value of an uniform to an array of int32 (stored as vec2)
  13784. * @param uniform defines the webGL uniform location where to store the value
  13785. * @param array defines the array of int32 to store
  13786. */
  13787. Engine.prototype.setIntArray2 = function (uniform, array) {
  13788. if (!uniform || array.length % 2 !== 0)
  13789. return;
  13790. this._gl.uniform2iv(uniform, array);
  13791. };
  13792. /**
  13793. * Set the value of an uniform to an array of int32 (stored as vec3)
  13794. * @param uniform defines the webGL uniform location where to store the value
  13795. * @param array defines the array of int32 to store
  13796. */
  13797. Engine.prototype.setIntArray3 = function (uniform, array) {
  13798. if (!uniform || array.length % 3 !== 0)
  13799. return;
  13800. this._gl.uniform3iv(uniform, array);
  13801. };
  13802. /**
  13803. * Set the value of an uniform to an array of int32 (stored as vec4)
  13804. * @param uniform defines the webGL uniform location where to store the value
  13805. * @param array defines the array of int32 to store
  13806. */
  13807. Engine.prototype.setIntArray4 = function (uniform, array) {
  13808. if (!uniform || array.length % 4 !== 0)
  13809. return;
  13810. this._gl.uniform4iv(uniform, array);
  13811. };
  13812. /**
  13813. * Set the value of an uniform to an array of float32
  13814. * @param uniform defines the webGL uniform location where to store the value
  13815. * @param array defines the array of float32 to store
  13816. */
  13817. Engine.prototype.setFloatArray = function (uniform, array) {
  13818. if (!uniform)
  13819. return;
  13820. this._gl.uniform1fv(uniform, array);
  13821. };
  13822. /**
  13823. * Set the value of an uniform to an array of float32 (stored as vec2)
  13824. * @param uniform defines the webGL uniform location where to store the value
  13825. * @param array defines the array of float32 to store
  13826. */
  13827. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13828. if (!uniform || array.length % 2 !== 0)
  13829. return;
  13830. this._gl.uniform2fv(uniform, array);
  13831. };
  13832. /**
  13833. * Set the value of an uniform to an array of float32 (stored as vec3)
  13834. * @param uniform defines the webGL uniform location where to store the value
  13835. * @param array defines the array of float32 to store
  13836. */
  13837. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13838. if (!uniform || array.length % 3 !== 0)
  13839. return;
  13840. this._gl.uniform3fv(uniform, array);
  13841. };
  13842. /**
  13843. * Set the value of an uniform to an array of float32 (stored as vec4)
  13844. * @param uniform defines the webGL uniform location where to store the value
  13845. * @param array defines the array of float32 to store
  13846. */
  13847. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13848. if (!uniform || array.length % 4 !== 0)
  13849. return;
  13850. this._gl.uniform4fv(uniform, array);
  13851. };
  13852. /**
  13853. * Set the value of an uniform to an array of number
  13854. * @param uniform defines the webGL uniform location where to store the value
  13855. * @param array defines the array of number to store
  13856. */
  13857. Engine.prototype.setArray = function (uniform, array) {
  13858. if (!uniform)
  13859. return;
  13860. this._gl.uniform1fv(uniform, array);
  13861. };
  13862. /**
  13863. * Set the value of an uniform to an array of number (stored as vec2)
  13864. * @param uniform defines the webGL uniform location where to store the value
  13865. * @param array defines the array of number to store
  13866. */
  13867. Engine.prototype.setArray2 = function (uniform, array) {
  13868. if (!uniform || array.length % 2 !== 0)
  13869. return;
  13870. this._gl.uniform2fv(uniform, array);
  13871. };
  13872. /**
  13873. * Set the value of an uniform to an array of number (stored as vec3)
  13874. * @param uniform defines the webGL uniform location where to store the value
  13875. * @param array defines the array of number to store
  13876. */
  13877. Engine.prototype.setArray3 = function (uniform, array) {
  13878. if (!uniform || array.length % 3 !== 0)
  13879. return;
  13880. this._gl.uniform3fv(uniform, array);
  13881. };
  13882. /**
  13883. * Set the value of an uniform to an array of number (stored as vec4)
  13884. * @param uniform defines the webGL uniform location where to store the value
  13885. * @param array defines the array of number to store
  13886. */
  13887. Engine.prototype.setArray4 = function (uniform, array) {
  13888. if (!uniform || array.length % 4 !== 0)
  13889. return;
  13890. this._gl.uniform4fv(uniform, array);
  13891. };
  13892. /**
  13893. * Set the value of an uniform to an array of float32 (stored as matrices)
  13894. * @param uniform defines the webGL uniform location where to store the value
  13895. * @param matrices defines the array of float32 to store
  13896. */
  13897. Engine.prototype.setMatrices = function (uniform, matrices) {
  13898. if (!uniform)
  13899. return;
  13900. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13901. };
  13902. /**
  13903. * Set the value of an uniform to a matrix
  13904. * @param uniform defines the webGL uniform location where to store the value
  13905. * @param matrix defines the matrix to store
  13906. */
  13907. Engine.prototype.setMatrix = function (uniform, matrix) {
  13908. if (!uniform)
  13909. return;
  13910. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13911. };
  13912. /**
  13913. * Set the value of an uniform to a matrix (3x3)
  13914. * @param uniform defines the webGL uniform location where to store the value
  13915. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13916. */
  13917. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13918. if (!uniform)
  13919. return;
  13920. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13921. };
  13922. /**
  13923. * Set the value of an uniform to a matrix (2x2)
  13924. * @param uniform defines the webGL uniform location where to store the value
  13925. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13926. */
  13927. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13928. if (!uniform)
  13929. return;
  13930. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13931. };
  13932. /**
  13933. * Set the value of an uniform to a number (int)
  13934. * @param uniform defines the webGL uniform location where to store the value
  13935. * @param value defines the int number to store
  13936. */
  13937. Engine.prototype.setInt = function (uniform, value) {
  13938. if (!uniform)
  13939. return;
  13940. this._gl.uniform1i(uniform, value);
  13941. };
  13942. /**
  13943. * Set the value of an uniform to a number (float)
  13944. * @param uniform defines the webGL uniform location where to store the value
  13945. * @param value defines the float number to store
  13946. */
  13947. Engine.prototype.setFloat = function (uniform, value) {
  13948. if (!uniform)
  13949. return;
  13950. this._gl.uniform1f(uniform, value);
  13951. };
  13952. /**
  13953. * Set the value of an uniform to a vec2
  13954. * @param uniform defines the webGL uniform location where to store the value
  13955. * @param x defines the 1st component of the value
  13956. * @param y defines the 2nd component of the value
  13957. */
  13958. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13959. if (!uniform)
  13960. return;
  13961. this._gl.uniform2f(uniform, x, y);
  13962. };
  13963. /**
  13964. * Set the value of an uniform to a vec3
  13965. * @param uniform defines the webGL uniform location where to store the value
  13966. * @param x defines the 1st component of the value
  13967. * @param y defines the 2nd component of the value
  13968. * @param z defines the 3rd component of the value
  13969. */
  13970. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13971. if (!uniform)
  13972. return;
  13973. this._gl.uniform3f(uniform, x, y, z);
  13974. };
  13975. /**
  13976. * Set the value of an uniform to a boolean
  13977. * @param uniform defines the webGL uniform location where to store the value
  13978. * @param bool defines the boolean to store
  13979. */
  13980. Engine.prototype.setBool = function (uniform, bool) {
  13981. if (!uniform)
  13982. return;
  13983. this._gl.uniform1i(uniform, bool);
  13984. };
  13985. /**
  13986. * Set the value of an uniform to a vec4
  13987. * @param uniform defines the webGL uniform location where to store the value
  13988. * @param x defines the 1st component of the value
  13989. * @param y defines the 2nd component of the value
  13990. * @param z defines the 3rd component of the value
  13991. * @param w defines the 4th component of the value
  13992. */
  13993. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13994. if (!uniform)
  13995. return;
  13996. this._gl.uniform4f(uniform, x, y, z, w);
  13997. };
  13998. /**
  13999. * Set the value of an uniform to a Color3
  14000. * @param uniform defines the webGL uniform location where to store the value
  14001. * @param color3 defines the color to store
  14002. */
  14003. Engine.prototype.setColor3 = function (uniform, color3) {
  14004. if (!uniform)
  14005. return;
  14006. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14007. };
  14008. /**
  14009. * Set the value of an uniform to a Color3 and an alpha value
  14010. * @param uniform defines the webGL uniform location where to store the value
  14011. * @param color3 defines the color to store
  14012. * @param alpha defines the alpha component to store
  14013. */
  14014. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14015. if (!uniform)
  14016. return;
  14017. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14018. };
  14019. /**
  14020. * Sets a Color4 on a uniform variable
  14021. * @param uniform defines the uniform location
  14022. * @param color4 defines the value to be set
  14023. */
  14024. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14025. if (!uniform)
  14026. return;
  14027. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14028. };
  14029. // States
  14030. /**
  14031. * Set various states to the webGL context
  14032. * @param culling defines backface culling state
  14033. * @param zOffset defines the value to apply to zOffset (0 by default)
  14034. * @param force defines if states must be applied even if cache is up to date
  14035. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14036. */
  14037. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14038. if (zOffset === void 0) { zOffset = 0; }
  14039. if (reverseSide === void 0) { reverseSide = false; }
  14040. // Culling
  14041. if (this._depthCullingState.cull !== culling || force) {
  14042. this._depthCullingState.cull = culling;
  14043. }
  14044. // Cull face
  14045. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14046. if (this._depthCullingState.cullFace !== cullFace || force) {
  14047. this._depthCullingState.cullFace = cullFace;
  14048. }
  14049. // Z offset
  14050. this.setZOffset(zOffset);
  14051. // Front face
  14052. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14053. if (this._depthCullingState.frontFace !== frontFace || force) {
  14054. this._depthCullingState.frontFace = frontFace;
  14055. }
  14056. };
  14057. /**
  14058. * Set the z offset to apply to current rendering
  14059. * @param value defines the offset to apply
  14060. */
  14061. Engine.prototype.setZOffset = function (value) {
  14062. this._depthCullingState.zOffset = value;
  14063. };
  14064. /**
  14065. * Gets the current value of the zOffset
  14066. * @returns the current zOffset state
  14067. */
  14068. Engine.prototype.getZOffset = function () {
  14069. return this._depthCullingState.zOffset;
  14070. };
  14071. /**
  14072. * Enable or disable depth buffering
  14073. * @param enable defines the state to set
  14074. */
  14075. Engine.prototype.setDepthBuffer = function (enable) {
  14076. this._depthCullingState.depthTest = enable;
  14077. };
  14078. /**
  14079. * Gets a boolean indicating if depth writing is enabled
  14080. * @returns the current depth writing state
  14081. */
  14082. Engine.prototype.getDepthWrite = function () {
  14083. return this._depthCullingState.depthMask;
  14084. };
  14085. /**
  14086. * Enable or disable depth writing
  14087. * @param enable defines the state to set
  14088. */
  14089. Engine.prototype.setDepthWrite = function (enable) {
  14090. this._depthCullingState.depthMask = enable;
  14091. };
  14092. /**
  14093. * Enable or disable color writing
  14094. * @param enable defines the state to set
  14095. */
  14096. Engine.prototype.setColorWrite = function (enable) {
  14097. this._gl.colorMask(enable, enable, enable, enable);
  14098. this._colorWrite = enable;
  14099. };
  14100. /**
  14101. * Gets a boolean indicating if color writing is enabled
  14102. * @returns the current color writing state
  14103. */
  14104. Engine.prototype.getColorWrite = function () {
  14105. return this._colorWrite;
  14106. };
  14107. /**
  14108. * Sets alpha constants used by some alpha blending modes
  14109. * @param r defines the red component
  14110. * @param g defines the green component
  14111. * @param b defines the blue component
  14112. * @param a defines the alpha component
  14113. */
  14114. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14115. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14116. };
  14117. /**
  14118. * Sets the current alpha mode
  14119. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14120. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14121. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14122. */
  14123. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14124. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14125. if (this._alphaMode === mode) {
  14126. return;
  14127. }
  14128. switch (mode) {
  14129. case Engine.ALPHA_DISABLE:
  14130. this._alphaState.alphaBlend = false;
  14131. break;
  14132. case Engine.ALPHA_PREMULTIPLIED:
  14133. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14134. this._alphaState.alphaBlend = true;
  14135. break;
  14136. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14137. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14138. this._alphaState.alphaBlend = true;
  14139. break;
  14140. case Engine.ALPHA_COMBINE:
  14141. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14142. this._alphaState.alphaBlend = true;
  14143. break;
  14144. case Engine.ALPHA_ONEONE:
  14145. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14146. this._alphaState.alphaBlend = true;
  14147. break;
  14148. case Engine.ALPHA_ADD:
  14149. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14150. this._alphaState.alphaBlend = true;
  14151. break;
  14152. case Engine.ALPHA_SUBTRACT:
  14153. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14154. this._alphaState.alphaBlend = true;
  14155. break;
  14156. case Engine.ALPHA_MULTIPLY:
  14157. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14158. this._alphaState.alphaBlend = true;
  14159. break;
  14160. case Engine.ALPHA_MAXIMIZED:
  14161. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14162. this._alphaState.alphaBlend = true;
  14163. break;
  14164. case Engine.ALPHA_INTERPOLATE:
  14165. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14166. this._alphaState.alphaBlend = true;
  14167. break;
  14168. case Engine.ALPHA_SCREENMODE:
  14169. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14170. this._alphaState.alphaBlend = true;
  14171. break;
  14172. }
  14173. if (!noDepthWriteChange) {
  14174. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14175. }
  14176. this._alphaMode = mode;
  14177. };
  14178. /**
  14179. * Gets the current alpha mode
  14180. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14181. * @returns the current alpha mode
  14182. */
  14183. Engine.prototype.getAlphaMode = function () {
  14184. return this._alphaMode;
  14185. };
  14186. // Textures
  14187. /**
  14188. * Clears the list of texture accessible through engine.
  14189. * This can help preventing texture load conflict due to name collision.
  14190. */
  14191. Engine.prototype.clearInternalTexturesCache = function () {
  14192. this._internalTexturesCache = [];
  14193. };
  14194. /**
  14195. * Force the entire cache to be cleared
  14196. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14197. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14198. */
  14199. Engine.prototype.wipeCaches = function (bruteForce) {
  14200. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14201. return;
  14202. }
  14203. this._currentEffect = null;
  14204. this._unpackFlipYCached = null;
  14205. this._viewportCached.x = 0;
  14206. this._viewportCached.y = 0;
  14207. this._viewportCached.z = 0;
  14208. this._viewportCached.w = 0;
  14209. if (bruteForce) {
  14210. this.resetTextureCache();
  14211. this._currentProgram = null;
  14212. this._stencilState.reset();
  14213. this._depthCullingState.reset();
  14214. this.setDepthFunctionToLessOrEqual();
  14215. this._alphaState.reset();
  14216. }
  14217. this._resetVertexBufferBinding();
  14218. this._cachedIndexBuffer = null;
  14219. this._cachedEffectForVertexBuffers = null;
  14220. this._unbindVertexArrayObject();
  14221. this.bindIndexBuffer(null);
  14222. };
  14223. /**
  14224. * Set the compressed texture format to use, based on the formats you have, and the formats
  14225. * supported by the hardware / browser.
  14226. *
  14227. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14228. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14229. * to API arguments needed to compressed textures. This puts the burden on the container
  14230. * generator to house the arcane code for determining these for current & future formats.
  14231. *
  14232. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14233. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14234. *
  14235. * Note: The result of this call is not taken into account when a texture is base64.
  14236. *
  14237. * @param formatsAvailable defines the list of those format families you have created
  14238. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14239. *
  14240. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14241. * @returns The extension selected.
  14242. */
  14243. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14244. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14245. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14246. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14247. return this._textureFormatInUse = this._texturesSupported[i];
  14248. }
  14249. }
  14250. }
  14251. // actively set format to nothing, to allow this to be called more than once
  14252. // and possibly fail the 2nd time
  14253. this._textureFormatInUse = null;
  14254. return null;
  14255. };
  14256. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14257. var gl = this._gl;
  14258. var magFilter = gl.NEAREST;
  14259. var minFilter = gl.NEAREST;
  14260. switch (samplingMode) {
  14261. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14262. magFilter = gl.LINEAR;
  14263. if (generateMipMaps) {
  14264. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14265. }
  14266. else {
  14267. minFilter = gl.LINEAR;
  14268. }
  14269. break;
  14270. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14271. magFilter = gl.LINEAR;
  14272. if (generateMipMaps) {
  14273. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14274. }
  14275. else {
  14276. minFilter = gl.LINEAR;
  14277. }
  14278. break;
  14279. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14280. magFilter = gl.NEAREST;
  14281. if (generateMipMaps) {
  14282. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14283. }
  14284. else {
  14285. minFilter = gl.NEAREST;
  14286. }
  14287. break;
  14288. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14289. magFilter = gl.NEAREST;
  14290. if (generateMipMaps) {
  14291. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14292. }
  14293. else {
  14294. minFilter = gl.NEAREST;
  14295. }
  14296. break;
  14297. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14298. magFilter = gl.NEAREST;
  14299. if (generateMipMaps) {
  14300. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14301. }
  14302. else {
  14303. minFilter = gl.LINEAR;
  14304. }
  14305. break;
  14306. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14307. magFilter = gl.NEAREST;
  14308. if (generateMipMaps) {
  14309. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14310. }
  14311. else {
  14312. minFilter = gl.LINEAR;
  14313. }
  14314. break;
  14315. case Engine.TEXTURE_NEAREST_LINEAR:
  14316. magFilter = gl.NEAREST;
  14317. minFilter = gl.LINEAR;
  14318. break;
  14319. case Engine.TEXTURE_NEAREST_NEAREST:
  14320. magFilter = gl.NEAREST;
  14321. minFilter = gl.NEAREST;
  14322. break;
  14323. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14324. magFilter = gl.LINEAR;
  14325. if (generateMipMaps) {
  14326. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14327. }
  14328. else {
  14329. minFilter = gl.NEAREST;
  14330. }
  14331. break;
  14332. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14333. magFilter = gl.LINEAR;
  14334. if (generateMipMaps) {
  14335. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14336. }
  14337. else {
  14338. minFilter = gl.NEAREST;
  14339. }
  14340. break;
  14341. case Engine.TEXTURE_LINEAR_LINEAR:
  14342. magFilter = gl.LINEAR;
  14343. minFilter = gl.LINEAR;
  14344. break;
  14345. case Engine.TEXTURE_LINEAR_NEAREST:
  14346. magFilter = gl.LINEAR;
  14347. minFilter = gl.NEAREST;
  14348. break;
  14349. }
  14350. return {
  14351. min: minFilter,
  14352. mag: magFilter
  14353. };
  14354. };
  14355. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14356. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14357. var img;
  14358. var onload = function () {
  14359. loadedImages[index] = img;
  14360. loadedImages._internalCount++;
  14361. if (scene) {
  14362. scene._removePendingData(img);
  14363. }
  14364. if (loadedImages._internalCount === 6) {
  14365. onfinish(loadedImages);
  14366. }
  14367. };
  14368. var onerror = function (message, exception) {
  14369. if (scene) {
  14370. scene._removePendingData(img);
  14371. }
  14372. if (onErrorCallBack) {
  14373. onErrorCallBack(message, exception);
  14374. }
  14375. };
  14376. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14377. if (scene) {
  14378. scene._addPendingData(img);
  14379. }
  14380. };
  14381. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14382. if (onError === void 0) { onError = null; }
  14383. var loadedImages = [];
  14384. loadedImages._internalCount = 0;
  14385. for (var index = 0; index < 6; index++) {
  14386. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14387. }
  14388. };
  14389. ;
  14390. /** @hidden */
  14391. Engine.prototype._createTexture = function () {
  14392. var texture = this._gl.createTexture();
  14393. if (!texture) {
  14394. throw new Error("Unable to create texture");
  14395. }
  14396. return texture;
  14397. };
  14398. /**
  14399. * Usually called from BABYLON.Texture.ts.
  14400. * Passed information to create a WebGLTexture
  14401. * @param urlArg defines a value which contains one of the following:
  14402. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14403. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14404. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14405. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14406. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14407. * @param scene needed for loading to the correct scene
  14408. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14409. * @param onLoad optional callback to be called upon successful completion
  14410. * @param onError optional callback to be called upon failure
  14411. * @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
  14412. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14413. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14414. * @param forcedExtension defines the extension to use to pick the right loader
  14415. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14416. */
  14417. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14418. var _this = this;
  14419. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14420. if (onLoad === void 0) { onLoad = null; }
  14421. if (onError === void 0) { onError = null; }
  14422. if (buffer === void 0) { buffer = null; }
  14423. if (fallback === void 0) { fallback = null; }
  14424. if (format === void 0) { format = null; }
  14425. if (forcedExtension === void 0) { forcedExtension = null; }
  14426. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14427. var fromData = url.substr(0, 5) === "data:";
  14428. var fromBlob = url.substr(0, 5) === "blob:";
  14429. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14430. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14431. // establish the file extension, if possible
  14432. var lastDot = url.lastIndexOf('.');
  14433. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14434. var loader = null;
  14435. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14436. var availableLoader = _a[_i];
  14437. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14438. loader = availableLoader;
  14439. break;
  14440. }
  14441. }
  14442. if (loader) {
  14443. url = loader.transformUrl(url, this._textureFormatInUse);
  14444. }
  14445. if (scene) {
  14446. scene._addPendingData(texture);
  14447. }
  14448. texture.url = url;
  14449. texture.generateMipMaps = !noMipmap;
  14450. texture.samplingMode = samplingMode;
  14451. texture.invertY = invertY;
  14452. if (!this._doNotHandleContextLost) {
  14453. // Keep a link to the buffer only if we plan to handle context lost
  14454. texture._buffer = buffer;
  14455. }
  14456. var onLoadObserver = null;
  14457. if (onLoad && !fallback) {
  14458. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14459. }
  14460. if (!fallback)
  14461. this._internalTexturesCache.push(texture);
  14462. var onInternalError = function (message, exception) {
  14463. if (scene) {
  14464. scene._removePendingData(texture);
  14465. }
  14466. var customFallback = false;
  14467. if (loader) {
  14468. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14469. if (fallbackUrl) {
  14470. // Add Back
  14471. customFallback = true;
  14472. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14473. }
  14474. }
  14475. if (!customFallback) {
  14476. if (onLoadObserver) {
  14477. texture.onLoadedObservable.remove(onLoadObserver);
  14478. }
  14479. if (BABYLON.Tools.UseFallbackTexture) {
  14480. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14481. }
  14482. }
  14483. if (onError) {
  14484. onError(message || "Unknown error", exception);
  14485. }
  14486. };
  14487. // processing for non-image formats
  14488. if (loader) {
  14489. var callback = function (data) {
  14490. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14491. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14492. done();
  14493. return false;
  14494. }, samplingMode);
  14495. });
  14496. };
  14497. if (!buffer) {
  14498. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14499. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14500. });
  14501. }
  14502. else {
  14503. callback(buffer);
  14504. }
  14505. }
  14506. else {
  14507. var onload = function (img) {
  14508. if (fromBlob && !_this._doNotHandleContextLost) {
  14509. // We need to store the image if we need to rebuild the texture
  14510. // in case of a webgl context lost
  14511. texture._buffer = img;
  14512. }
  14513. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14514. var gl = _this._gl;
  14515. var isPot = (img.width === potWidth && img.height === potHeight);
  14516. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14517. if (isPot) {
  14518. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14519. return false;
  14520. }
  14521. var maxTextureSize = _this._caps.maxTextureSize;
  14522. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14523. _this._prepareWorkingCanvas();
  14524. if (!_this._workingCanvas || !_this._workingContext) {
  14525. return false;
  14526. }
  14527. _this._workingCanvas.width = potWidth;
  14528. _this._workingCanvas.height = potHeight;
  14529. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14530. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14531. texture.width = potWidth;
  14532. texture.height = potHeight;
  14533. return false;
  14534. }
  14535. else {
  14536. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14537. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14538. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14539. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14540. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14541. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14542. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14543. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14544. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14545. _this._releaseTexture(source_1);
  14546. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14547. continuationCallback();
  14548. });
  14549. }
  14550. return true;
  14551. }, samplingMode);
  14552. };
  14553. if (!fromData || isBase64) {
  14554. if (buffer instanceof HTMLImageElement) {
  14555. onload(buffer);
  14556. }
  14557. else {
  14558. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14559. }
  14560. }
  14561. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14562. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14563. }
  14564. else {
  14565. onload(buffer);
  14566. }
  14567. }
  14568. return texture;
  14569. };
  14570. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14571. var _this = this;
  14572. var rtt = this.createRenderTargetTexture({
  14573. width: destination.width,
  14574. height: destination.height,
  14575. }, {
  14576. generateMipMaps: false,
  14577. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14578. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14579. generateDepthBuffer: false,
  14580. generateStencilBuffer: false
  14581. });
  14582. if (!this._rescalePostProcess) {
  14583. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14584. }
  14585. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14586. _this._rescalePostProcess.onApply = function (effect) {
  14587. effect._bindTexture("textureSampler", source);
  14588. };
  14589. var hostingScene = scene;
  14590. if (!hostingScene) {
  14591. hostingScene = _this.scenes[_this.scenes.length - 1];
  14592. }
  14593. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14594. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14595. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14596. _this.unBindFramebuffer(rtt);
  14597. _this._releaseTexture(rtt);
  14598. if (onComplete) {
  14599. onComplete();
  14600. }
  14601. });
  14602. };
  14603. /**
  14604. * Update a raw texture
  14605. * @param texture defines the texture to update
  14606. * @param data defines the data to store in the texture
  14607. * @param format defines the format of the data
  14608. * @param invertY defines if data must be stored with Y axis inverted
  14609. * @param compression defines the compression used (null by default)
  14610. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14611. */
  14612. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14613. if (compression === void 0) { compression = null; }
  14614. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14615. if (!texture) {
  14616. return;
  14617. }
  14618. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14619. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14620. // babylon's internalFormat but gl's texImage2D format
  14621. var internalFormat = this._getInternalFormat(format);
  14622. var textureType = this._getWebGLTextureType(type);
  14623. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14624. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14625. if (!this._doNotHandleContextLost) {
  14626. texture._bufferView = data;
  14627. texture.format = format;
  14628. texture.type = type;
  14629. texture.invertY = invertY;
  14630. texture._compression = compression;
  14631. }
  14632. if (texture.width % 4 !== 0) {
  14633. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14634. }
  14635. if (compression && data) {
  14636. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14637. }
  14638. else {
  14639. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14640. }
  14641. if (texture.generateMipMaps) {
  14642. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14643. }
  14644. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14645. // this.resetTextureCache();
  14646. texture.isReady = true;
  14647. };
  14648. /**
  14649. * Creates a raw texture
  14650. * @param data defines the data to store in the texture
  14651. * @param width defines the width of the texture
  14652. * @param height defines the height of the texture
  14653. * @param format defines the format of the data
  14654. * @param generateMipMaps defines if the engine should generate the mip levels
  14655. * @param invertY defines if data must be stored with Y axis inverted
  14656. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14657. * @param compression defines the compression used (null by default)
  14658. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14659. * @returns the raw texture inside an InternalTexture
  14660. */
  14661. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14662. if (compression === void 0) { compression = null; }
  14663. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14664. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14665. texture.baseWidth = width;
  14666. texture.baseHeight = height;
  14667. texture.width = width;
  14668. texture.height = height;
  14669. texture.format = format;
  14670. texture.generateMipMaps = generateMipMaps;
  14671. texture.samplingMode = samplingMode;
  14672. texture.invertY = invertY;
  14673. texture._compression = compression;
  14674. texture.type = type;
  14675. if (!this._doNotHandleContextLost) {
  14676. texture._bufferView = data;
  14677. }
  14678. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14679. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14680. // Filters
  14681. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14682. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14683. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14684. if (generateMipMaps) {
  14685. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14686. }
  14687. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14688. this._internalTexturesCache.push(texture);
  14689. return texture;
  14690. };
  14691. /** @hidden */
  14692. Engine.prototype._unpackFlipY = function (value) {
  14693. if (this._unpackFlipYCached !== value) {
  14694. this._unpackFlipYCached = value;
  14695. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14696. }
  14697. };
  14698. /** @hidden */
  14699. Engine.prototype._getUnpackAlignement = function () {
  14700. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14701. };
  14702. /**
  14703. * Creates a dynamic texture
  14704. * @param width defines the width of the texture
  14705. * @param height defines the height of the texture
  14706. * @param generateMipMaps defines if the engine should generate the mip levels
  14707. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14708. * @returns the dynamic texture inside an InternalTexture
  14709. */
  14710. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14711. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14712. texture.baseWidth = width;
  14713. texture.baseHeight = height;
  14714. if (generateMipMaps) {
  14715. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14716. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14717. }
  14718. // this.resetTextureCache();
  14719. texture.width = width;
  14720. texture.height = height;
  14721. texture.isReady = false;
  14722. texture.generateMipMaps = generateMipMaps;
  14723. texture.samplingMode = samplingMode;
  14724. this.updateTextureSamplingMode(samplingMode, texture);
  14725. this._internalTexturesCache.push(texture);
  14726. return texture;
  14727. };
  14728. /**
  14729. * Update the sampling mode of a given texture
  14730. * @param samplingMode defines the required sampling mode
  14731. * @param texture defines the texture to update
  14732. */
  14733. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14734. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14735. if (texture.isCube) {
  14736. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14737. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14738. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14739. }
  14740. else if (texture.is3D) {
  14741. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14742. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14743. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14744. }
  14745. else {
  14746. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14747. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14748. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14749. }
  14750. texture.samplingMode = samplingMode;
  14751. };
  14752. /**
  14753. * Update the content of a dynamic texture
  14754. * @param texture defines the texture to update
  14755. * @param canvas defines the canvas containing the source
  14756. * @param invertY defines if data must be stored with Y axis inverted
  14757. * @param premulAlpha defines if alpha is stored as premultiplied
  14758. * @param format defines the format of the data
  14759. */
  14760. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14761. if (premulAlpha === void 0) { premulAlpha = false; }
  14762. if (!texture) {
  14763. return;
  14764. }
  14765. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14766. this._unpackFlipY(invertY);
  14767. if (premulAlpha) {
  14768. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14769. }
  14770. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14771. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14772. if (texture.generateMipMaps) {
  14773. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14774. }
  14775. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14776. if (premulAlpha) {
  14777. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14778. }
  14779. texture.isReady = true;
  14780. };
  14781. /**
  14782. * Update a video texture
  14783. * @param texture defines the texture to update
  14784. * @param video defines the video element to use
  14785. * @param invertY defines if data must be stored with Y axis inverted
  14786. */
  14787. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14788. if (!texture || texture._isDisabled) {
  14789. return;
  14790. }
  14791. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14792. this._unpackFlipY(!invertY); // Video are upside down by default
  14793. try {
  14794. // Testing video texture support
  14795. if (this._videoTextureSupported === undefined) {
  14796. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14797. if (this._gl.getError() !== 0) {
  14798. this._videoTextureSupported = false;
  14799. }
  14800. else {
  14801. this._videoTextureSupported = true;
  14802. }
  14803. }
  14804. // Copy video through the current working canvas if video texture is not supported
  14805. if (!this._videoTextureSupported) {
  14806. if (!texture._workingCanvas) {
  14807. texture._workingCanvas = document.createElement("canvas");
  14808. var context = texture._workingCanvas.getContext("2d");
  14809. if (!context) {
  14810. throw new Error("Unable to get 2d context");
  14811. }
  14812. texture._workingContext = context;
  14813. texture._workingCanvas.width = texture.width;
  14814. texture._workingCanvas.height = texture.height;
  14815. }
  14816. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14817. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14818. }
  14819. else {
  14820. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14821. }
  14822. if (texture.generateMipMaps) {
  14823. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14824. }
  14825. if (!wasPreviouslyBound) {
  14826. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14827. }
  14828. // this.resetTextureCache();
  14829. texture.isReady = true;
  14830. }
  14831. catch (ex) {
  14832. // Something unexpected
  14833. // Let's disable the texture
  14834. texture._isDisabled = true;
  14835. }
  14836. };
  14837. /**
  14838. * Updates a depth texture Comparison Mode and Function.
  14839. * If the comparison Function is equal to 0, the mode will be set to none.
  14840. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14841. * @param texture The texture to set the comparison function for
  14842. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14843. */
  14844. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14845. if (this.webGLVersion === 1) {
  14846. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14847. return;
  14848. }
  14849. var gl = this._gl;
  14850. if (texture.isCube) {
  14851. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14852. if (comparisonFunction === 0) {
  14853. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14854. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14855. }
  14856. else {
  14857. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14858. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14859. }
  14860. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14861. }
  14862. else {
  14863. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14864. if (comparisonFunction === 0) {
  14865. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14866. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14867. }
  14868. else {
  14869. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14871. }
  14872. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14873. }
  14874. texture._comparisonFunction = comparisonFunction;
  14875. };
  14876. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14877. var width = size.width || size;
  14878. var height = size.height || size;
  14879. internalTexture.baseWidth = width;
  14880. internalTexture.baseHeight = height;
  14881. internalTexture.width = width;
  14882. internalTexture.height = height;
  14883. internalTexture.isReady = true;
  14884. internalTexture.samples = 1;
  14885. internalTexture.generateMipMaps = false;
  14886. internalTexture._generateDepthBuffer = true;
  14887. internalTexture._generateStencilBuffer = generateStencil;
  14888. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14889. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14890. internalTexture._comparisonFunction = comparisonFunction;
  14891. var gl = this._gl;
  14892. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14893. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14894. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14895. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14896. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14897. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14898. if (comparisonFunction === 0) {
  14899. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14900. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14901. }
  14902. else {
  14903. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14904. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14905. }
  14906. };
  14907. /**
  14908. * Creates a depth stencil texture.
  14909. * This is only available in WebGL 2 or with the depth texture extension available.
  14910. * @param size The size of face edge in the texture.
  14911. * @param options The options defining the texture.
  14912. * @returns The texture
  14913. */
  14914. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14915. if (options.isCube) {
  14916. var width = size.width || size;
  14917. return this._createDepthStencilCubeTexture(width, options);
  14918. }
  14919. else {
  14920. return this._createDepthStencilTexture(size, options);
  14921. }
  14922. };
  14923. /**
  14924. * Creates a depth stencil texture.
  14925. * This is only available in WebGL 2 or with the depth texture extension available.
  14926. * @param size The size of face edge in the texture.
  14927. * @param options The options defining the texture.
  14928. * @returns The texture
  14929. */
  14930. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14931. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14932. if (!this._caps.depthTextureExtension) {
  14933. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14934. return internalTexture;
  14935. }
  14936. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14937. var gl = this._gl;
  14938. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14939. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14940. if (this.webGLVersion > 1) {
  14941. if (internalOptions.generateStencil) {
  14942. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14943. }
  14944. else {
  14945. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14946. }
  14947. }
  14948. else {
  14949. if (internalOptions.generateStencil) {
  14950. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14951. }
  14952. else {
  14953. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14954. }
  14955. }
  14956. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14957. return internalTexture;
  14958. };
  14959. /**
  14960. * Creates a depth stencil cube texture.
  14961. * This is only available in WebGL 2.
  14962. * @param size The size of face edge in the cube texture.
  14963. * @param options The options defining the cube texture.
  14964. * @returns The cube texture
  14965. */
  14966. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14967. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14968. internalTexture.isCube = true;
  14969. if (this.webGLVersion === 1) {
  14970. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14971. return internalTexture;
  14972. }
  14973. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14974. var gl = this._gl;
  14975. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14976. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14977. // Create the depth/stencil buffer
  14978. for (var face = 0; face < 6; face++) {
  14979. if (internalOptions.generateStencil) {
  14980. 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);
  14981. }
  14982. else {
  14983. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14984. }
  14985. }
  14986. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14987. return internalTexture;
  14988. };
  14989. /**
  14990. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14991. * @param renderTarget The render target to set the frame buffer for
  14992. */
  14993. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14994. // Create the framebuffer
  14995. var internalTexture = renderTarget.getInternalTexture();
  14996. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14997. return;
  14998. }
  14999. var gl = this._gl;
  15000. var depthStencilTexture = renderTarget.depthStencilTexture;
  15001. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15002. if (depthStencilTexture.isCube) {
  15003. if (depthStencilTexture._generateStencilBuffer) {
  15004. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15005. }
  15006. else {
  15007. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15008. }
  15009. }
  15010. else {
  15011. if (depthStencilTexture._generateStencilBuffer) {
  15012. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15013. }
  15014. else {
  15015. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15016. }
  15017. }
  15018. this.bindUnboundFramebuffer(null);
  15019. };
  15020. /**
  15021. * Creates a new render target texture
  15022. * @param size defines the size of the texture
  15023. * @param options defines the options used to create the texture
  15024. * @returns a new render target texture stored in an InternalTexture
  15025. */
  15026. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15027. var fullOptions = new RenderTargetCreationOptions();
  15028. if (options !== undefined && typeof options === "object") {
  15029. fullOptions.generateMipMaps = options.generateMipMaps;
  15030. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15031. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15032. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15033. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15034. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15035. }
  15036. else {
  15037. fullOptions.generateMipMaps = options;
  15038. fullOptions.generateDepthBuffer = true;
  15039. fullOptions.generateStencilBuffer = false;
  15040. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15041. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15042. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15043. }
  15044. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15045. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15046. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15047. }
  15048. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15049. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15050. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15051. }
  15052. var gl = this._gl;
  15053. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15054. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15055. var width = size.width || size;
  15056. var height = size.height || size;
  15057. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15058. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15059. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15060. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15061. }
  15062. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15064. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15065. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15066. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15067. // Create the framebuffer
  15068. var currentFrameBuffer = this._currentFramebuffer;
  15069. var framebuffer = gl.createFramebuffer();
  15070. this.bindUnboundFramebuffer(framebuffer);
  15071. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15072. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15073. if (fullOptions.generateMipMaps) {
  15074. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15075. }
  15076. // Unbind
  15077. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15078. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15079. this.bindUnboundFramebuffer(currentFrameBuffer);
  15080. texture._framebuffer = framebuffer;
  15081. texture.baseWidth = width;
  15082. texture.baseHeight = height;
  15083. texture.width = width;
  15084. texture.height = height;
  15085. texture.isReady = true;
  15086. texture.samples = 1;
  15087. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15088. texture.samplingMode = fullOptions.samplingMode;
  15089. texture.type = fullOptions.type;
  15090. texture.format = fullOptions.format;
  15091. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15092. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15093. // this.resetTextureCache();
  15094. this._internalTexturesCache.push(texture);
  15095. return texture;
  15096. };
  15097. /**
  15098. * Create a multi render target texture
  15099. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15100. * @param size defines the size of the texture
  15101. * @param options defines the creation options
  15102. * @returns the cube texture as an InternalTexture
  15103. */
  15104. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15105. var generateMipMaps = false;
  15106. var generateDepthBuffer = true;
  15107. var generateStencilBuffer = false;
  15108. var generateDepthTexture = false;
  15109. var textureCount = 1;
  15110. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15111. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15112. var types = new Array();
  15113. var samplingModes = new Array();
  15114. if (options !== undefined) {
  15115. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15116. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15117. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15118. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15119. textureCount = options.textureCount || 1;
  15120. if (options.types) {
  15121. types = options.types;
  15122. }
  15123. if (options.samplingModes) {
  15124. samplingModes = options.samplingModes;
  15125. }
  15126. }
  15127. var gl = this._gl;
  15128. // Create the framebuffer
  15129. var framebuffer = gl.createFramebuffer();
  15130. this.bindUnboundFramebuffer(framebuffer);
  15131. var width = size.width || size;
  15132. var height = size.height || size;
  15133. var textures = [];
  15134. var attachments = [];
  15135. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15136. for (var i = 0; i < textureCount; i++) {
  15137. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15138. var type = types[i] || defaultType;
  15139. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15140. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15141. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15142. }
  15143. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15144. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15145. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15146. }
  15147. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15148. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15149. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15150. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15151. }
  15152. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15153. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15154. textures.push(texture);
  15155. attachments.push(attachment);
  15156. gl.activeTexture(gl["TEXTURE" + i]);
  15157. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15158. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15159. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15160. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15161. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15162. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15163. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15164. if (generateMipMaps) {
  15165. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15166. }
  15167. // Unbind
  15168. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15169. texture._framebuffer = framebuffer;
  15170. texture._depthStencilBuffer = depthStencilBuffer;
  15171. texture.baseWidth = width;
  15172. texture.baseHeight = height;
  15173. texture.width = width;
  15174. texture.height = height;
  15175. texture.isReady = true;
  15176. texture.samples = 1;
  15177. texture.generateMipMaps = generateMipMaps;
  15178. texture.samplingMode = samplingMode;
  15179. texture.type = type;
  15180. texture._generateDepthBuffer = generateDepthBuffer;
  15181. texture._generateStencilBuffer = generateStencilBuffer;
  15182. texture._attachments = attachments;
  15183. this._internalTexturesCache.push(texture);
  15184. }
  15185. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15186. // Depth texture
  15187. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15188. gl.activeTexture(gl.TEXTURE0);
  15189. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15191. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15192. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15194. 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);
  15195. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15196. depthTexture._framebuffer = framebuffer;
  15197. depthTexture.baseWidth = width;
  15198. depthTexture.baseHeight = height;
  15199. depthTexture.width = width;
  15200. depthTexture.height = height;
  15201. depthTexture.isReady = true;
  15202. depthTexture.samples = 1;
  15203. depthTexture.generateMipMaps = generateMipMaps;
  15204. depthTexture.samplingMode = gl.NEAREST;
  15205. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15206. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15207. textures.push(depthTexture);
  15208. this._internalTexturesCache.push(depthTexture);
  15209. }
  15210. gl.drawBuffers(attachments);
  15211. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15212. this.bindUnboundFramebuffer(null);
  15213. this.resetTextureCache();
  15214. return textures;
  15215. };
  15216. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15217. if (samples === void 0) { samples = 1; }
  15218. var depthStencilBuffer = null;
  15219. var gl = this._gl;
  15220. // Create the depth/stencil buffer
  15221. if (generateStencilBuffer) {
  15222. depthStencilBuffer = gl.createRenderbuffer();
  15223. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15224. if (samples > 1) {
  15225. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15226. }
  15227. else {
  15228. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15229. }
  15230. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15231. }
  15232. else if (generateDepthBuffer) {
  15233. depthStencilBuffer = gl.createRenderbuffer();
  15234. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15235. if (samples > 1) {
  15236. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15237. }
  15238. else {
  15239. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15240. }
  15241. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15242. }
  15243. return depthStencilBuffer;
  15244. };
  15245. /**
  15246. * Updates the sample count of a render target texture
  15247. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15248. * @param texture defines the texture to update
  15249. * @param samples defines the sample count to set
  15250. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15251. */
  15252. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15253. if (this.webGLVersion < 2 || !texture) {
  15254. return 1;
  15255. }
  15256. if (texture.samples === samples) {
  15257. return samples;
  15258. }
  15259. var gl = this._gl;
  15260. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15261. // Dispose previous render buffers
  15262. if (texture._depthStencilBuffer) {
  15263. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15264. texture._depthStencilBuffer = null;
  15265. }
  15266. if (texture._MSAAFramebuffer) {
  15267. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15268. texture._MSAAFramebuffer = null;
  15269. }
  15270. if (texture._MSAARenderBuffer) {
  15271. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15272. texture._MSAARenderBuffer = null;
  15273. }
  15274. if (samples > 1) {
  15275. var framebuffer = gl.createFramebuffer();
  15276. if (!framebuffer) {
  15277. throw new Error("Unable to create multi sampled framebuffer");
  15278. }
  15279. texture._MSAAFramebuffer = framebuffer;
  15280. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15281. var colorRenderbuffer = gl.createRenderbuffer();
  15282. if (!colorRenderbuffer) {
  15283. throw new Error("Unable to create multi sampled framebuffer");
  15284. }
  15285. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15286. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15287. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15288. texture._MSAARenderBuffer = colorRenderbuffer;
  15289. }
  15290. else {
  15291. this.bindUnboundFramebuffer(texture._framebuffer);
  15292. }
  15293. texture.samples = samples;
  15294. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15295. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15296. this.bindUnboundFramebuffer(null);
  15297. return samples;
  15298. };
  15299. /**
  15300. * Update the sample count for a given multiple render target texture
  15301. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15302. * @param textures defines the textures to update
  15303. * @param samples defines the sample count to set
  15304. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15305. */
  15306. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15307. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15308. return 1;
  15309. }
  15310. if (textures[0].samples === samples) {
  15311. return samples;
  15312. }
  15313. var gl = this._gl;
  15314. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15315. // Dispose previous render buffers
  15316. if (textures[0]._depthStencilBuffer) {
  15317. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15318. textures[0]._depthStencilBuffer = null;
  15319. }
  15320. if (textures[0]._MSAAFramebuffer) {
  15321. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15322. textures[0]._MSAAFramebuffer = null;
  15323. }
  15324. for (var i = 0; i < textures.length; i++) {
  15325. if (textures[i]._MSAARenderBuffer) {
  15326. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15327. textures[i]._MSAARenderBuffer = null;
  15328. }
  15329. }
  15330. if (samples > 1) {
  15331. var framebuffer = gl.createFramebuffer();
  15332. if (!framebuffer) {
  15333. throw new Error("Unable to create multi sampled framebuffer");
  15334. }
  15335. this.bindUnboundFramebuffer(framebuffer);
  15336. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15337. var attachments = [];
  15338. for (var i = 0; i < textures.length; i++) {
  15339. var texture = textures[i];
  15340. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15341. var colorRenderbuffer = gl.createRenderbuffer();
  15342. if (!colorRenderbuffer) {
  15343. throw new Error("Unable to create multi sampled framebuffer");
  15344. }
  15345. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15346. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15347. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15348. texture._MSAAFramebuffer = framebuffer;
  15349. texture._MSAARenderBuffer = colorRenderbuffer;
  15350. texture.samples = samples;
  15351. texture._depthStencilBuffer = depthStencilBuffer;
  15352. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15353. attachments.push(attachment);
  15354. }
  15355. gl.drawBuffers(attachments);
  15356. }
  15357. else {
  15358. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15359. }
  15360. this.bindUnboundFramebuffer(null);
  15361. return samples;
  15362. };
  15363. /** @hidden */
  15364. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15365. if (faceIndex === void 0) { faceIndex = 0; }
  15366. if (lod === void 0) { lod = 0; }
  15367. var gl = this._gl;
  15368. var target = gl.TEXTURE_2D;
  15369. if (texture.isCube) {
  15370. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15371. }
  15372. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15373. };
  15374. /** @hidden */
  15375. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15376. if (faceIndex === void 0) { faceIndex = 0; }
  15377. if (lod === void 0) { lod = 0; }
  15378. var gl = this._gl;
  15379. var textureType = this._getWebGLTextureType(texture.type);
  15380. var format = this._getInternalFormat(texture.format);
  15381. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15382. this._unpackFlipY(texture.invertY);
  15383. var target = gl.TEXTURE_2D;
  15384. if (texture.isCube) {
  15385. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15386. }
  15387. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15388. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15389. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15390. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15391. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15392. };
  15393. /** @hidden */
  15394. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15395. if (faceIndex === void 0) { faceIndex = 0; }
  15396. if (lod === void 0) { lod = 0; }
  15397. var gl = this._gl;
  15398. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15399. this._bindTextureDirectly(bindTarget, texture, true);
  15400. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15401. this._bindTextureDirectly(bindTarget, null, true);
  15402. };
  15403. /** @hidden */
  15404. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15405. if (faceIndex === void 0) { faceIndex = 0; }
  15406. if (lod === void 0) { lod = 0; }
  15407. var gl = this._gl;
  15408. var textureType = this._getWebGLTextureType(texture.type);
  15409. var format = this._getInternalFormat(texture.format);
  15410. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15411. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15412. this._bindTextureDirectly(bindTarget, texture, true);
  15413. this._unpackFlipY(texture.invertY);
  15414. var target = gl.TEXTURE_2D;
  15415. if (texture.isCube) {
  15416. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15417. }
  15418. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15419. this._bindTextureDirectly(bindTarget, null, true);
  15420. };
  15421. /**
  15422. * Creates a new render target cube texture
  15423. * @param size defines the size of the texture
  15424. * @param options defines the options used to create the texture
  15425. * @returns a new render target cube texture stored in an InternalTexture
  15426. */
  15427. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15428. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15429. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15430. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15431. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15432. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15433. }
  15434. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15435. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15436. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15437. }
  15438. var gl = this._gl;
  15439. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15440. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15441. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15442. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15443. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15444. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15445. }
  15446. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15447. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15448. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15449. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15450. for (var face = 0; face < 6; face++) {
  15451. 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);
  15452. }
  15453. // Create the framebuffer
  15454. var framebuffer = gl.createFramebuffer();
  15455. this.bindUnboundFramebuffer(framebuffer);
  15456. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15457. // MipMaps
  15458. if (fullOptions.generateMipMaps) {
  15459. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15460. }
  15461. // Unbind
  15462. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15463. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15464. this.bindUnboundFramebuffer(null);
  15465. texture._framebuffer = framebuffer;
  15466. texture.width = size;
  15467. texture.height = size;
  15468. texture.isReady = true;
  15469. texture.isCube = true;
  15470. texture.samples = 1;
  15471. texture.generateMipMaps = fullOptions.generateMipMaps;
  15472. texture.samplingMode = fullOptions.samplingMode;
  15473. texture.type = fullOptions.type;
  15474. texture.format = fullOptions.format;
  15475. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15476. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15477. this._internalTexturesCache.push(texture);
  15478. return texture;
  15479. };
  15480. /**
  15481. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15482. * @param rootUrl defines the url where the file to load is located
  15483. * @param scene defines the current scene
  15484. * @param lodScale defines scale to apply to the mip map selection
  15485. * @param lodOffset defines offset to apply to the mip map selection
  15486. * @param onLoad defines an optional callback raised when the texture is loaded
  15487. * @param onError defines an optional callback raised if there is an issue to load the texture
  15488. * @param format defines the format of the data
  15489. * @param forcedExtension defines the extension to use to pick the right loader
  15490. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15491. * @returns the cube texture as an InternalTexture
  15492. */
  15493. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15494. var _this = this;
  15495. if (onLoad === void 0) { onLoad = null; }
  15496. if (onError === void 0) { onError = null; }
  15497. if (forcedExtension === void 0) { forcedExtension = null; }
  15498. if (createPolynomials === void 0) { createPolynomials = true; }
  15499. var callback = function (loadData) {
  15500. if (!loadData) {
  15501. if (onLoad) {
  15502. onLoad(null);
  15503. }
  15504. return;
  15505. }
  15506. var texture = loadData.texture;
  15507. if (!createPolynomials) {
  15508. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15509. }
  15510. else if (loadData.info.sphericalPolynomial) {
  15511. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15512. }
  15513. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15514. if (_this._caps.textureLOD) {
  15515. // Do not add extra process if texture lod is supported.
  15516. if (onLoad) {
  15517. onLoad(texture);
  15518. }
  15519. return;
  15520. }
  15521. var mipSlices = 3;
  15522. var gl = _this._gl;
  15523. var width = loadData.width;
  15524. if (!width) {
  15525. return;
  15526. }
  15527. var textures = [];
  15528. for (var i = 0; i < mipSlices; i++) {
  15529. //compute LOD from even spacing in smoothness (matching shader calculation)
  15530. var smoothness = i / (mipSlices - 1);
  15531. var roughness = 1 - smoothness;
  15532. var minLODIndex = lodOffset; // roughness = 0
  15533. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15534. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15535. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15536. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15537. glTextureFromLod.type = texture.type;
  15538. glTextureFromLod.format = texture.format;
  15539. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15540. glTextureFromLod.height = glTextureFromLod.width;
  15541. glTextureFromLod.isCube = true;
  15542. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15543. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15544. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15545. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15546. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15547. if (loadData.isDDS) {
  15548. var info = loadData.info;
  15549. var data = loadData.data;
  15550. _this._unpackFlipY(info.isCompressed);
  15551. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15552. }
  15553. else {
  15554. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15555. }
  15556. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15557. // Wrap in a base texture for easy binding.
  15558. var lodTexture = new BABYLON.BaseTexture(scene);
  15559. lodTexture.isCube = true;
  15560. lodTexture._texture = glTextureFromLod;
  15561. glTextureFromLod.isReady = true;
  15562. textures.push(lodTexture);
  15563. }
  15564. texture._lodTextureHigh = textures[2];
  15565. texture._lodTextureMid = textures[1];
  15566. texture._lodTextureLow = textures[0];
  15567. if (onLoad) {
  15568. onLoad(texture);
  15569. }
  15570. };
  15571. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15572. };
  15573. /**
  15574. * Creates a cube texture
  15575. * @param rootUrl defines the url where the files to load is located
  15576. * @param scene defines the current scene
  15577. * @param files defines the list of files to load (1 per face)
  15578. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15579. * @param onLoad defines an optional callback raised when the texture is loaded
  15580. * @param onError defines an optional callback raised if there is an issue to load the texture
  15581. * @param format defines the format of the data
  15582. * @param forcedExtension defines the extension to use to pick the right loader
  15583. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15584. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15585. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15586. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15587. * @returns the cube texture as an InternalTexture
  15588. */
  15589. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15590. var _this = this;
  15591. if (onLoad === void 0) { onLoad = null; }
  15592. if (onError === void 0) { onError = null; }
  15593. if (forcedExtension === void 0) { forcedExtension = null; }
  15594. if (createPolynomials === void 0) { createPolynomials = false; }
  15595. if (lodScale === void 0) { lodScale = 0; }
  15596. if (lodOffset === void 0) { lodOffset = 0; }
  15597. if (fallback === void 0) { fallback = null; }
  15598. var gl = this._gl;
  15599. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15600. texture.isCube = true;
  15601. texture.url = rootUrl;
  15602. texture.generateMipMaps = !noMipmap;
  15603. texture._lodGenerationScale = lodScale;
  15604. texture._lodGenerationOffset = lodOffset;
  15605. if (!this._doNotHandleContextLost) {
  15606. texture._extension = forcedExtension;
  15607. texture._files = files;
  15608. }
  15609. var lastDot = rootUrl.lastIndexOf('.');
  15610. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15611. var loader = null;
  15612. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15613. var availableLoader = _a[_i];
  15614. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15615. loader = availableLoader;
  15616. break;
  15617. }
  15618. }
  15619. var onInternalError = function (request, exception) {
  15620. if (loader) {
  15621. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15622. if (fallbackUrl) {
  15623. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15624. }
  15625. }
  15626. if (onError && request) {
  15627. onError(request.status + " " + request.statusText, exception);
  15628. }
  15629. };
  15630. if (loader) {
  15631. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15632. var onloaddata = function (data) {
  15633. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15634. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15635. };
  15636. if (files && files.length === 6) {
  15637. if (loader.supportCascades) {
  15638. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15639. }
  15640. else if (onError) {
  15641. onError("Textures type does not support cascades.");
  15642. }
  15643. }
  15644. else {
  15645. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15646. }
  15647. }
  15648. else {
  15649. if (!files) {
  15650. throw new Error("Cannot load cubemap because files were not defined");
  15651. }
  15652. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15653. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15654. var height = width;
  15655. _this._prepareWorkingCanvas();
  15656. if (!_this._workingCanvas || !_this._workingContext) {
  15657. return;
  15658. }
  15659. _this._workingCanvas.width = width;
  15660. _this._workingCanvas.height = height;
  15661. var faces = [
  15662. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15663. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15664. ];
  15665. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15666. _this._unpackFlipY(false);
  15667. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15668. for (var index = 0; index < faces.length; index++) {
  15669. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15670. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15671. }
  15672. if (!noMipmap) {
  15673. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15674. }
  15675. _this._setCubeMapTextureParams(!noMipmap);
  15676. texture.width = width;
  15677. texture.height = height;
  15678. texture.isReady = true;
  15679. if (format) {
  15680. texture.format = format;
  15681. }
  15682. texture.onLoadedObservable.notifyObservers(texture);
  15683. texture.onLoadedObservable.clear();
  15684. if (onLoad) {
  15685. onLoad();
  15686. }
  15687. }, files, onError);
  15688. }
  15689. this._internalTexturesCache.push(texture);
  15690. return texture;
  15691. };
  15692. /**
  15693. * @hidden
  15694. */
  15695. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15696. var gl = this._gl;
  15697. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15698. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15699. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15700. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15701. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15702. // this.resetTextureCache();
  15703. };
  15704. /**
  15705. * Update a raw cube texture
  15706. * @param texture defines the texture to udpdate
  15707. * @param data defines the data to store
  15708. * @param format defines the data format
  15709. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15710. * @param invertY defines if data must be stored with Y axis inverted
  15711. * @param compression defines the compression used (null by default)
  15712. * @param level defines which level of the texture to update
  15713. */
  15714. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15715. if (compression === void 0) { compression = null; }
  15716. if (level === void 0) { level = 0; }
  15717. texture._bufferViewArray = data;
  15718. texture.format = format;
  15719. texture.type = type;
  15720. texture.invertY = invertY;
  15721. texture._compression = compression;
  15722. var gl = this._gl;
  15723. var textureType = this._getWebGLTextureType(type);
  15724. var internalFormat = this._getInternalFormat(format);
  15725. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15726. var needConversion = false;
  15727. if (internalFormat === gl.RGB) {
  15728. internalFormat = gl.RGBA;
  15729. needConversion = true;
  15730. }
  15731. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15732. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15733. if (texture.width % 4 !== 0) {
  15734. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15735. }
  15736. // Data are known to be in +X +Y +Z -X -Y -Z
  15737. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15738. var faceData = data[faceIndex];
  15739. if (compression) {
  15740. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15741. }
  15742. else {
  15743. if (needConversion) {
  15744. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15745. }
  15746. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15747. }
  15748. }
  15749. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15750. if (isPot && texture.generateMipMaps && level === 0) {
  15751. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15752. }
  15753. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15754. // this.resetTextureCache();
  15755. texture.isReady = true;
  15756. };
  15757. /**
  15758. * Creates a new raw cube texture
  15759. * @param data defines the array of data to use to create each face
  15760. * @param size defines the size of the textures
  15761. * @param format defines the format of the data
  15762. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15763. * @param generateMipMaps defines if the engine should generate the mip levels
  15764. * @param invertY defines if data must be stored with Y axis inverted
  15765. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15766. * @param compression defines the compression used (null by default)
  15767. * @returns the cube texture as an InternalTexture
  15768. */
  15769. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15770. if (compression === void 0) { compression = null; }
  15771. var gl = this._gl;
  15772. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15773. texture.isCube = true;
  15774. texture.format = format;
  15775. texture.type = type;
  15776. if (!this._doNotHandleContextLost) {
  15777. texture._bufferViewArray = data;
  15778. }
  15779. var textureType = this._getWebGLTextureType(type);
  15780. var internalFormat = this._getInternalFormat(format);
  15781. if (internalFormat === gl.RGB) {
  15782. internalFormat = gl.RGBA;
  15783. }
  15784. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15785. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15786. generateMipMaps = false;
  15787. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15788. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15789. }
  15790. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15791. generateMipMaps = false;
  15792. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15793. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15794. }
  15795. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15796. generateMipMaps = false;
  15797. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15798. }
  15799. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15800. generateMipMaps = false;
  15801. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15802. }
  15803. var width = size;
  15804. var height = width;
  15805. texture.width = width;
  15806. texture.height = height;
  15807. // Double check on POT to generate Mips.
  15808. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15809. if (!isPot) {
  15810. generateMipMaps = false;
  15811. }
  15812. // Upload data if needed. The texture won't be ready until then.
  15813. if (data) {
  15814. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15815. }
  15816. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15817. // Filters
  15818. if (data && generateMipMaps) {
  15819. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15820. }
  15821. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15822. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15824. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15825. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15826. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15827. texture.generateMipMaps = generateMipMaps;
  15828. return texture;
  15829. };
  15830. /**
  15831. * Creates a new raw cube texture from a specified url
  15832. * @param url defines the url where the data is located
  15833. * @param scene defines the current scene
  15834. * @param size defines the size of the textures
  15835. * @param format defines the format of the data
  15836. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15837. * @param noMipmap defines if the engine should avoid generating the mip levels
  15838. * @param callback defines a callback used to extract texture data from loaded data
  15839. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15840. * @param onLoad defines a callback called when texture is loaded
  15841. * @param onError defines a callback called if there is an error
  15842. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15843. * @param invertY defines if data must be stored with Y axis inverted
  15844. * @returns the cube texture as an InternalTexture
  15845. */
  15846. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15847. var _this = this;
  15848. if (onLoad === void 0) { onLoad = null; }
  15849. if (onError === void 0) { onError = null; }
  15850. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15851. if (invertY === void 0) { invertY = false; }
  15852. var gl = this._gl;
  15853. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15854. scene._addPendingData(texture);
  15855. texture.url = url;
  15856. this._internalTexturesCache.push(texture);
  15857. var onerror = function (request, exception) {
  15858. scene._removePendingData(texture);
  15859. if (onError && request) {
  15860. onError(request.status + " " + request.statusText, exception);
  15861. }
  15862. };
  15863. var internalCallback = function (data) {
  15864. var width = texture.width;
  15865. var faceDataArrays = callback(data);
  15866. if (!faceDataArrays) {
  15867. return;
  15868. }
  15869. if (mipmapGenerator) {
  15870. var textureType = _this._getWebGLTextureType(type);
  15871. var internalFormat = _this._getInternalFormat(format);
  15872. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15873. var needConversion = false;
  15874. if (internalFormat === gl.RGB) {
  15875. internalFormat = gl.RGBA;
  15876. needConversion = true;
  15877. }
  15878. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15879. _this._unpackFlipY(false);
  15880. var mipData = mipmapGenerator(faceDataArrays);
  15881. for (var level = 0; level < mipData.length; level++) {
  15882. var mipSize = width >> level;
  15883. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15884. var mipFaceData = mipData[level][faceIndex];
  15885. if (needConversion) {
  15886. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15887. }
  15888. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15889. }
  15890. }
  15891. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15892. }
  15893. else {
  15894. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15895. }
  15896. texture.isReady = true;
  15897. // this.resetTextureCache();
  15898. scene._removePendingData(texture);
  15899. if (onLoad) {
  15900. onLoad();
  15901. }
  15902. };
  15903. this._loadFile(url, function (data) {
  15904. internalCallback(data);
  15905. }, undefined, scene.database, true, onerror);
  15906. return texture;
  15907. };
  15908. ;
  15909. /**
  15910. * Update a raw 3D texture
  15911. * @param texture defines the texture to update
  15912. * @param data defines the data to store
  15913. * @param format defines the data format
  15914. * @param invertY defines if data must be stored with Y axis inverted
  15915. * @param compression defines the used compression (can be null)
  15916. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15917. */
  15918. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15919. if (compression === void 0) { compression = null; }
  15920. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15921. var internalType = this._getWebGLTextureType(textureType);
  15922. var internalFormat = this._getInternalFormat(format);
  15923. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15924. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15925. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15926. if (!this._doNotHandleContextLost) {
  15927. texture._bufferView = data;
  15928. texture.format = format;
  15929. texture.invertY = invertY;
  15930. texture._compression = compression;
  15931. }
  15932. if (texture.width % 4 !== 0) {
  15933. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15934. }
  15935. if (compression && data) {
  15936. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15937. }
  15938. else {
  15939. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15940. }
  15941. if (texture.generateMipMaps) {
  15942. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15943. }
  15944. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15945. // this.resetTextureCache();
  15946. texture.isReady = true;
  15947. };
  15948. /**
  15949. * Creates a new raw 3D texture
  15950. * @param data defines the data used to create the texture
  15951. * @param width defines the width of the texture
  15952. * @param height defines the height of the texture
  15953. * @param depth defines the depth of the texture
  15954. * @param format defines the format of the texture
  15955. * @param generateMipMaps defines if the engine must generate mip levels
  15956. * @param invertY defines if data must be stored with Y axis inverted
  15957. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15958. * @param compression defines the compressed used (can be null)
  15959. * @param textureType defines the compressed used (can be null)
  15960. * @returns a new raw 3D texture (stored in an InternalTexture)
  15961. */
  15962. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15963. if (compression === void 0) { compression = null; }
  15964. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15965. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15966. texture.baseWidth = width;
  15967. texture.baseHeight = height;
  15968. texture.baseDepth = depth;
  15969. texture.width = width;
  15970. texture.height = height;
  15971. texture.depth = depth;
  15972. texture.format = format;
  15973. texture.type = textureType;
  15974. texture.generateMipMaps = generateMipMaps;
  15975. texture.samplingMode = samplingMode;
  15976. texture.is3D = true;
  15977. if (!this._doNotHandleContextLost) {
  15978. texture._bufferView = data;
  15979. }
  15980. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15981. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15982. // Filters
  15983. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15984. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15985. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15986. if (generateMipMaps) {
  15987. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15988. }
  15989. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15990. this._internalTexturesCache.push(texture);
  15991. return texture;
  15992. };
  15993. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15994. var gl = this._gl;
  15995. if (!gl) {
  15996. return;
  15997. }
  15998. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  15999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16001. if (!noMipmap && !isCompressed) {
  16002. gl.generateMipmap(gl.TEXTURE_2D);
  16003. }
  16004. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16005. // this.resetTextureCache();
  16006. if (scene) {
  16007. scene._removePendingData(texture);
  16008. }
  16009. texture.onLoadedObservable.notifyObservers(texture);
  16010. texture.onLoadedObservable.clear();
  16011. };
  16012. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16013. var _this = this;
  16014. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16015. var maxTextureSize = this.getCaps().maxTextureSize;
  16016. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16017. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16018. var gl = this._gl;
  16019. if (!gl) {
  16020. return;
  16021. }
  16022. if (!texture._webGLTexture) {
  16023. // this.resetTextureCache();
  16024. if (scene) {
  16025. scene._removePendingData(texture);
  16026. }
  16027. return;
  16028. }
  16029. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16030. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16031. texture.baseWidth = width;
  16032. texture.baseHeight = height;
  16033. texture.width = potWidth;
  16034. texture.height = potHeight;
  16035. texture.isReady = true;
  16036. if (processFunction(potWidth, potHeight, function () {
  16037. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16038. })) {
  16039. // Returning as texture needs extra async steps
  16040. return;
  16041. }
  16042. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16043. };
  16044. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16045. // Create new RGBA data container.
  16046. var rgbaData;
  16047. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16048. rgbaData = new Float32Array(width * height * 4);
  16049. }
  16050. else {
  16051. rgbaData = new Uint32Array(width * height * 4);
  16052. }
  16053. // Convert each pixel.
  16054. for (var x = 0; x < width; x++) {
  16055. for (var y = 0; y < height; y++) {
  16056. var index = (y * width + x) * 3;
  16057. var newIndex = (y * width + x) * 4;
  16058. // Map Old Value to new value.
  16059. rgbaData[newIndex + 0] = rgbData[index + 0];
  16060. rgbaData[newIndex + 1] = rgbData[index + 1];
  16061. rgbaData[newIndex + 2] = rgbData[index + 2];
  16062. // Add fully opaque alpha channel.
  16063. rgbaData[newIndex + 3] = 1;
  16064. }
  16065. }
  16066. return rgbaData;
  16067. };
  16068. /** @hidden */
  16069. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16070. var gl = this._gl;
  16071. if (texture._framebuffer) {
  16072. gl.deleteFramebuffer(texture._framebuffer);
  16073. texture._framebuffer = null;
  16074. }
  16075. if (texture._depthStencilBuffer) {
  16076. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16077. texture._depthStencilBuffer = null;
  16078. }
  16079. if (texture._MSAAFramebuffer) {
  16080. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16081. texture._MSAAFramebuffer = null;
  16082. }
  16083. if (texture._MSAARenderBuffer) {
  16084. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16085. texture._MSAARenderBuffer = null;
  16086. }
  16087. };
  16088. /** @hidden */
  16089. Engine.prototype._releaseTexture = function (texture) {
  16090. var gl = this._gl;
  16091. this._releaseFramebufferObjects(texture);
  16092. gl.deleteTexture(texture._webGLTexture);
  16093. // Unbind channels
  16094. this.unbindAllTextures();
  16095. var index = this._internalTexturesCache.indexOf(texture);
  16096. if (index !== -1) {
  16097. this._internalTexturesCache.splice(index, 1);
  16098. }
  16099. // Integrated fixed lod samplers.
  16100. if (texture._lodTextureHigh) {
  16101. texture._lodTextureHigh.dispose();
  16102. }
  16103. if (texture._lodTextureMid) {
  16104. texture._lodTextureMid.dispose();
  16105. }
  16106. if (texture._lodTextureLow) {
  16107. texture._lodTextureLow.dispose();
  16108. }
  16109. // Set output texture of post process to null if the texture has been released/disposed
  16110. this.scenes.forEach(function (scene) {
  16111. scene.postProcesses.forEach(function (postProcess) {
  16112. if (postProcess._outputTexture == texture) {
  16113. postProcess._outputTexture = null;
  16114. }
  16115. });
  16116. scene.cameras.forEach(function (camera) {
  16117. camera._postProcesses.forEach(function (postProcess) {
  16118. if (postProcess) {
  16119. if (postProcess._outputTexture == texture) {
  16120. postProcess._outputTexture = null;
  16121. }
  16122. }
  16123. });
  16124. });
  16125. });
  16126. };
  16127. Engine.prototype.setProgram = function (program) {
  16128. if (this._currentProgram !== program) {
  16129. this._gl.useProgram(program);
  16130. this._currentProgram = program;
  16131. }
  16132. };
  16133. /**
  16134. * Binds an effect to the webGL context
  16135. * @param effect defines the effect to bind
  16136. */
  16137. Engine.prototype.bindSamplers = function (effect) {
  16138. this.setProgram(effect.getProgram());
  16139. var samplers = effect.getSamplers();
  16140. for (var index = 0; index < samplers.length; index++) {
  16141. var uniform = effect.getUniform(samplers[index]);
  16142. if (uniform) {
  16143. this._boundUniforms[index] = uniform;
  16144. }
  16145. }
  16146. this._currentEffect = null;
  16147. };
  16148. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16149. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16150. return;
  16151. }
  16152. // Remove
  16153. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16154. // Bind last to it
  16155. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16156. // Bind to dummy
  16157. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16158. };
  16159. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16160. if (!internalTexture) {
  16161. return -1;
  16162. }
  16163. internalTexture._initialSlot = channel;
  16164. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16165. if (channel !== internalTexture._designatedSlot) {
  16166. this._textureCollisions.addCount(1, false);
  16167. }
  16168. }
  16169. else {
  16170. if (channel !== internalTexture._designatedSlot) {
  16171. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16172. return internalTexture._designatedSlot;
  16173. }
  16174. else {
  16175. // No slot for this texture, let's pick a new one (if we find a free slot)
  16176. if (this._nextFreeTextureSlots.length) {
  16177. return this._nextFreeTextureSlots[0];
  16178. }
  16179. // We need to recycle the oldest bound texture, sorry.
  16180. this._textureCollisions.addCount(1, false);
  16181. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16182. }
  16183. }
  16184. }
  16185. return channel;
  16186. };
  16187. Engine.prototype._linkTrackers = function (previous, next) {
  16188. previous.next = next;
  16189. next.previous = previous;
  16190. };
  16191. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16192. var currentSlot = internalTexture._designatedSlot;
  16193. if (currentSlot === -1) {
  16194. return -1;
  16195. }
  16196. internalTexture._designatedSlot = -1;
  16197. if (this.disableTextureBindingOptimization) {
  16198. return -1;
  16199. }
  16200. // Remove from bound list
  16201. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16202. // Free the slot
  16203. this._boundTexturesCache[currentSlot] = null;
  16204. this._nextFreeTextureSlots.push(currentSlot);
  16205. return currentSlot;
  16206. };
  16207. Engine.prototype._activateCurrentTexture = function () {
  16208. if (this._currentTextureChannel !== this._activeChannel) {
  16209. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16210. this._currentTextureChannel = this._activeChannel;
  16211. }
  16212. };
  16213. /** @hidden */
  16214. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16215. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16216. if (force === void 0) { force = false; }
  16217. var wasPreviouslyBound = false;
  16218. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16219. this._activeChannel = texture._designatedSlot;
  16220. }
  16221. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16222. var isTextureForRendering = texture && texture._initialSlot > -1;
  16223. if (currentTextureBound !== texture || force) {
  16224. if (currentTextureBound) {
  16225. this._removeDesignatedSlot(currentTextureBound);
  16226. }
  16227. this._activateCurrentTexture();
  16228. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16229. this._boundTexturesCache[this._activeChannel] = texture;
  16230. if (texture) {
  16231. if (!this.disableTextureBindingOptimization) {
  16232. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16233. if (slotIndex > -1) {
  16234. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16235. }
  16236. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16237. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16238. }
  16239. texture._designatedSlot = this._activeChannel;
  16240. }
  16241. }
  16242. else if (forTextureDataUpdate) {
  16243. wasPreviouslyBound = true;
  16244. this._activateCurrentTexture();
  16245. }
  16246. if (isTextureForRendering && !forTextureDataUpdate) {
  16247. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16248. }
  16249. return wasPreviouslyBound;
  16250. };
  16251. /** @hidden */
  16252. Engine.prototype._bindTexture = function (channel, texture) {
  16253. if (channel < 0) {
  16254. return;
  16255. }
  16256. if (texture) {
  16257. channel = this._getCorrectTextureChannel(channel, texture);
  16258. }
  16259. this._activeChannel = channel;
  16260. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16261. };
  16262. /**
  16263. * Sets a texture to the webGL context from a postprocess
  16264. * @param channel defines the channel to use
  16265. * @param postProcess defines the source postprocess
  16266. */
  16267. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16268. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16269. };
  16270. /**
  16271. * Binds the output of the passed in post process to the texture channel specified
  16272. * @param channel The channel the texture should be bound to
  16273. * @param postProcess The post process which's output should be bound
  16274. */
  16275. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16276. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16277. };
  16278. /**
  16279. * Unbind all textures from the webGL context
  16280. */
  16281. Engine.prototype.unbindAllTextures = function () {
  16282. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16283. this._activeChannel = channel;
  16284. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16285. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16286. if (this.webGLVersion > 1) {
  16287. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16288. }
  16289. }
  16290. };
  16291. /**
  16292. * Sets a texture to the according uniform.
  16293. * @param channel The texture channel
  16294. * @param uniform The uniform to set
  16295. * @param texture The texture to apply
  16296. */
  16297. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16298. if (channel < 0) {
  16299. return;
  16300. }
  16301. if (uniform) {
  16302. this._boundUniforms[channel] = uniform;
  16303. }
  16304. this._setTexture(channel, texture);
  16305. };
  16306. /**
  16307. * Sets a depth stencil texture from a render target to the according uniform.
  16308. * @param channel The texture channel
  16309. * @param uniform The uniform to set
  16310. * @param texture The render target texture containing the depth stencil texture to apply
  16311. */
  16312. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16313. if (channel < 0) {
  16314. return;
  16315. }
  16316. if (uniform) {
  16317. this._boundUniforms[channel] = uniform;
  16318. }
  16319. if (!texture || !texture.depthStencilTexture) {
  16320. this._setTexture(channel, null);
  16321. }
  16322. else {
  16323. this._setTexture(channel, texture, false, true);
  16324. }
  16325. };
  16326. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16327. var uniform = this._boundUniforms[sourceSlot];
  16328. if (uniform._currentState === destination) {
  16329. return;
  16330. }
  16331. this._gl.uniform1i(uniform, destination);
  16332. uniform._currentState = destination;
  16333. };
  16334. Engine.prototype._getTextureWrapMode = function (mode) {
  16335. switch (mode) {
  16336. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16337. return this._gl.REPEAT;
  16338. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16339. return this._gl.CLAMP_TO_EDGE;
  16340. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16341. return this._gl.MIRRORED_REPEAT;
  16342. }
  16343. return this._gl.REPEAT;
  16344. };
  16345. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16346. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16347. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16348. // Not ready?
  16349. if (!texture) {
  16350. if (this._boundTexturesCache[channel] != null) {
  16351. this._activeChannel = channel;
  16352. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16353. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16354. if (this.webGLVersion > 1) {
  16355. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16356. }
  16357. }
  16358. return false;
  16359. }
  16360. // Video
  16361. if (texture.video) {
  16362. this._activeChannel = channel;
  16363. texture.update();
  16364. }
  16365. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16366. texture.delayLoad();
  16367. return false;
  16368. }
  16369. var internalTexture;
  16370. if (depthStencilTexture) {
  16371. internalTexture = texture.depthStencilTexture;
  16372. }
  16373. else if (texture.isReady()) {
  16374. internalTexture = texture.getInternalTexture();
  16375. }
  16376. else if (texture.isCube) {
  16377. internalTexture = this.emptyCubeTexture;
  16378. }
  16379. else if (texture.is3D) {
  16380. internalTexture = this.emptyTexture3D;
  16381. }
  16382. else {
  16383. internalTexture = this.emptyTexture;
  16384. }
  16385. if (!isPartOfTextureArray) {
  16386. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16387. }
  16388. var needToBind = true;
  16389. if (this._boundTexturesCache[channel] === internalTexture) {
  16390. this._moveBoundTextureOnTop(internalTexture);
  16391. if (!isPartOfTextureArray) {
  16392. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16393. }
  16394. needToBind = false;
  16395. }
  16396. this._activeChannel = channel;
  16397. if (internalTexture && internalTexture.is3D) {
  16398. if (needToBind) {
  16399. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16400. }
  16401. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16402. internalTexture._cachedWrapU = texture.wrapU;
  16403. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16404. }
  16405. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16406. internalTexture._cachedWrapV = texture.wrapV;
  16407. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16408. }
  16409. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16410. internalTexture._cachedWrapR = texture.wrapR;
  16411. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16412. }
  16413. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16414. }
  16415. else if (internalTexture && internalTexture.isCube) {
  16416. if (needToBind) {
  16417. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16418. }
  16419. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16420. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16421. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16422. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16423. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16424. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16425. }
  16426. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16427. }
  16428. else {
  16429. if (needToBind) {
  16430. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16431. }
  16432. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16433. internalTexture._cachedWrapU = texture.wrapU;
  16434. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16435. }
  16436. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16437. internalTexture._cachedWrapV = texture.wrapV;
  16438. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16439. }
  16440. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16441. }
  16442. return true;
  16443. };
  16444. /**
  16445. * Sets an array of texture to the webGL context
  16446. * @param channel defines the channel where the texture array must be set
  16447. * @param uniform defines the associated uniform location
  16448. * @param textures defines the array of textures to bind
  16449. */
  16450. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16451. if (channel < 0 || !uniform) {
  16452. return;
  16453. }
  16454. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16455. this._textureUnits = new Int32Array(textures.length);
  16456. }
  16457. for (var i = 0; i < textures.length; i++) {
  16458. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16459. }
  16460. this._gl.uniform1iv(uniform, this._textureUnits);
  16461. for (var index = 0; index < textures.length; index++) {
  16462. this._setTexture(this._textureUnits[index], textures[index], true);
  16463. }
  16464. };
  16465. /** @hidden */
  16466. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16467. var internalTexture = texture.getInternalTexture();
  16468. if (!internalTexture) {
  16469. return;
  16470. }
  16471. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16472. var value = texture.anisotropicFilteringLevel;
  16473. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16474. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16475. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16476. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16477. }
  16478. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16479. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16480. internalTexture._cachedAnisotropicFilteringLevel = value;
  16481. }
  16482. };
  16483. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16484. this._bindTextureDirectly(target, texture, true, true);
  16485. this._gl.texParameterf(target, parameter, value);
  16486. };
  16487. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16488. if (texture) {
  16489. this._bindTextureDirectly(target, texture, true, true);
  16490. }
  16491. this._gl.texParameteri(target, parameter, value);
  16492. };
  16493. /**
  16494. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16495. * @param x defines the x coordinate of the rectangle where pixels must be read
  16496. * @param y defines the y coordinate of the rectangle where pixels must be read
  16497. * @param width defines the width of the rectangle where pixels must be read
  16498. * @param height defines the height of the rectangle where pixels must be read
  16499. * @returns a Uint8Array containing RGBA colors
  16500. */
  16501. Engine.prototype.readPixels = function (x, y, width, height) {
  16502. var data = new Uint8Array(height * width * 4);
  16503. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16504. return data;
  16505. };
  16506. /**
  16507. * Add an externaly attached data from its key.
  16508. * This method call will fail and return false, if such key already exists.
  16509. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16510. * @param key the unique key that identifies the data
  16511. * @param data the data object to associate to the key for this Engine instance
  16512. * @return true if no such key were already present and the data was added successfully, false otherwise
  16513. */
  16514. Engine.prototype.addExternalData = function (key, data) {
  16515. if (!this._externalData) {
  16516. this._externalData = new BABYLON.StringDictionary();
  16517. }
  16518. return this._externalData.add(key, data);
  16519. };
  16520. /**
  16521. * Get an externaly attached data from its key
  16522. * @param key the unique key that identifies the data
  16523. * @return the associated data, if present (can be null), or undefined if not present
  16524. */
  16525. Engine.prototype.getExternalData = function (key) {
  16526. if (!this._externalData) {
  16527. this._externalData = new BABYLON.StringDictionary();
  16528. }
  16529. return this._externalData.get(key);
  16530. };
  16531. /**
  16532. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16533. * @param key the unique key that identifies the data
  16534. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16535. * @return the associated data, can be null if the factory returned null.
  16536. */
  16537. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16538. if (!this._externalData) {
  16539. this._externalData = new BABYLON.StringDictionary();
  16540. }
  16541. return this._externalData.getOrAddWithFactory(key, factory);
  16542. };
  16543. /**
  16544. * Remove an externaly attached data from the Engine instance
  16545. * @param key the unique key that identifies the data
  16546. * @return true if the data was successfully removed, false if it doesn't exist
  16547. */
  16548. Engine.prototype.removeExternalData = function (key) {
  16549. if (!this._externalData) {
  16550. this._externalData = new BABYLON.StringDictionary();
  16551. }
  16552. return this._externalData.remove(key);
  16553. };
  16554. /**
  16555. * Unbind all vertex attributes from the webGL context
  16556. */
  16557. Engine.prototype.unbindAllAttributes = function () {
  16558. if (this._mustWipeVertexAttributes) {
  16559. this._mustWipeVertexAttributes = false;
  16560. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16561. this._gl.disableVertexAttribArray(i);
  16562. this._vertexAttribArraysEnabled[i] = false;
  16563. this._currentBufferPointers[i].active = false;
  16564. }
  16565. return;
  16566. }
  16567. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16568. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16569. continue;
  16570. }
  16571. this._gl.disableVertexAttribArray(i);
  16572. this._vertexAttribArraysEnabled[i] = false;
  16573. this._currentBufferPointers[i].active = false;
  16574. }
  16575. };
  16576. /**
  16577. * 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
  16578. */
  16579. Engine.prototype.releaseEffects = function () {
  16580. for (var name in this._compiledEffects) {
  16581. this._deleteProgram(this._compiledEffects[name]._program);
  16582. }
  16583. this._compiledEffects = {};
  16584. };
  16585. /**
  16586. * Dispose and release all associated resources
  16587. */
  16588. Engine.prototype.dispose = function () {
  16589. this.hideLoadingUI();
  16590. this.stopRenderLoop();
  16591. // Release postProcesses
  16592. while (this.postProcesses.length) {
  16593. this.postProcesses[0].dispose();
  16594. }
  16595. // Empty texture
  16596. if (this._emptyTexture) {
  16597. this._releaseTexture(this._emptyTexture);
  16598. this._emptyTexture = null;
  16599. }
  16600. if (this._emptyCubeTexture) {
  16601. this._releaseTexture(this._emptyCubeTexture);
  16602. this._emptyCubeTexture = null;
  16603. }
  16604. // Rescale PP
  16605. if (this._rescalePostProcess) {
  16606. this._rescalePostProcess.dispose();
  16607. }
  16608. // Release scenes
  16609. while (this.scenes.length) {
  16610. this.scenes[0].dispose();
  16611. }
  16612. // Release audio engine
  16613. if (Engine.audioEngine) {
  16614. Engine.audioEngine.dispose();
  16615. }
  16616. // Release effects
  16617. this.releaseEffects();
  16618. // Unbind
  16619. this.unbindAllAttributes();
  16620. this._boundUniforms = [];
  16621. if (this._dummyFramebuffer) {
  16622. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16623. }
  16624. //WebVR
  16625. this.disableVR();
  16626. // Events
  16627. if (BABYLON.Tools.IsWindowObjectExist()) {
  16628. window.removeEventListener("blur", this._onBlur);
  16629. window.removeEventListener("focus", this._onFocus);
  16630. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16631. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16632. if (this._renderingCanvas) {
  16633. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16634. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16635. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16636. if (!this._doNotHandleContextLost) {
  16637. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16638. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16639. }
  16640. }
  16641. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16642. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16643. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16644. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16645. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16646. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16647. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16648. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16649. if (this._onVrDisplayConnect) {
  16650. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16651. if (this._onVrDisplayDisconnect) {
  16652. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16653. }
  16654. if (this._onVrDisplayPresentChange) {
  16655. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16656. }
  16657. this._onVrDisplayConnect = null;
  16658. this._onVrDisplayDisconnect = null;
  16659. }
  16660. }
  16661. // Remove from Instances
  16662. var index = Engine.Instances.indexOf(this);
  16663. if (index >= 0) {
  16664. Engine.Instances.splice(index, 1);
  16665. }
  16666. this._workingCanvas = null;
  16667. this._workingContext = null;
  16668. this._currentBufferPointers = [];
  16669. this._renderingCanvas = null;
  16670. this._currentProgram = null;
  16671. this._bindedRenderFunction = null;
  16672. this.onResizeObservable.clear();
  16673. this.onCanvasBlurObservable.clear();
  16674. this.onCanvasFocusObservable.clear();
  16675. this.onCanvasPointerOutObservable.clear();
  16676. this.onBeginFrameObservable.clear();
  16677. this.onEndFrameObservable.clear();
  16678. BABYLON.Effect.ResetCache();
  16679. // Abort active requests
  16680. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16681. var request = _a[_i];
  16682. request.abort();
  16683. }
  16684. };
  16685. // Loading screen
  16686. /**
  16687. * Display the loading screen
  16688. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16689. */
  16690. Engine.prototype.displayLoadingUI = function () {
  16691. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16692. return;
  16693. }
  16694. var loadingScreen = this.loadingScreen;
  16695. if (loadingScreen) {
  16696. loadingScreen.displayLoadingUI();
  16697. }
  16698. };
  16699. /**
  16700. * Hide the loading screen
  16701. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16702. */
  16703. Engine.prototype.hideLoadingUI = function () {
  16704. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16705. return;
  16706. }
  16707. var loadingScreen = this.loadingScreen;
  16708. if (loadingScreen) {
  16709. loadingScreen.hideLoadingUI();
  16710. }
  16711. };
  16712. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16713. /**
  16714. * Gets the current loading screen object
  16715. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16716. */
  16717. get: function () {
  16718. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16719. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16720. return this._loadingScreen;
  16721. },
  16722. /**
  16723. * Sets the current loading screen object
  16724. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16725. */
  16726. set: function (loadingScreen) {
  16727. this._loadingScreen = loadingScreen;
  16728. },
  16729. enumerable: true,
  16730. configurable: true
  16731. });
  16732. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16733. /**
  16734. * Sets the current loading screen text
  16735. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16736. */
  16737. set: function (text) {
  16738. this.loadingScreen.loadingUIText = text;
  16739. },
  16740. enumerable: true,
  16741. configurable: true
  16742. });
  16743. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16744. /**
  16745. * Sets the current loading screen background color
  16746. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16747. */
  16748. set: function (color) {
  16749. this.loadingScreen.loadingUIBackgroundColor = color;
  16750. },
  16751. enumerable: true,
  16752. configurable: true
  16753. });
  16754. /**
  16755. * Attach a new callback raised when context lost event is fired
  16756. * @param callback defines the callback to call
  16757. */
  16758. Engine.prototype.attachContextLostEvent = function (callback) {
  16759. if (this._renderingCanvas) {
  16760. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16761. }
  16762. };
  16763. /**
  16764. * Attach a new callback raised when context restored event is fired
  16765. * @param callback defines the callback to call
  16766. */
  16767. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16768. if (this._renderingCanvas) {
  16769. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16770. }
  16771. };
  16772. /**
  16773. * Gets the source code of the vertex shader associated with a specific webGL program
  16774. * @param program defines the program to use
  16775. * @returns a string containing the source code of the vertex shader associated with the program
  16776. */
  16777. Engine.prototype.getVertexShaderSource = function (program) {
  16778. var shaders = this._gl.getAttachedShaders(program);
  16779. if (!shaders) {
  16780. return null;
  16781. }
  16782. return this._gl.getShaderSource(shaders[0]);
  16783. };
  16784. /**
  16785. * Gets the source code of the fragment shader associated with a specific webGL program
  16786. * @param program defines the program to use
  16787. * @returns a string containing the source code of the fragment shader associated with the program
  16788. */
  16789. Engine.prototype.getFragmentShaderSource = function (program) {
  16790. var shaders = this._gl.getAttachedShaders(program);
  16791. if (!shaders) {
  16792. return null;
  16793. }
  16794. return this._gl.getShaderSource(shaders[1]);
  16795. };
  16796. /**
  16797. * Get the current error code of the webGL context
  16798. * @returns the error code
  16799. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16800. */
  16801. Engine.prototype.getError = function () {
  16802. return this._gl.getError();
  16803. };
  16804. // FPS
  16805. /**
  16806. * Gets the current framerate
  16807. * @returns a number representing the framerate
  16808. */
  16809. Engine.prototype.getFps = function () {
  16810. return this._fps;
  16811. };
  16812. /**
  16813. * Gets the time spent between current and previous frame
  16814. * @returns a number representing the delta time in ms
  16815. */
  16816. Engine.prototype.getDeltaTime = function () {
  16817. return this._deltaTime;
  16818. };
  16819. Engine.prototype._measureFps = function () {
  16820. this._performanceMonitor.sampleFrame();
  16821. this._fps = this._performanceMonitor.averageFPS;
  16822. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16823. };
  16824. /** @hidden */
  16825. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16826. if (faceIndex === void 0) { faceIndex = -1; }
  16827. if (level === void 0) { level = 0; }
  16828. var gl = this._gl;
  16829. if (!this._dummyFramebuffer) {
  16830. var dummy = gl.createFramebuffer();
  16831. if (!dummy) {
  16832. throw new Error("Unable to create dummy framebuffer");
  16833. }
  16834. this._dummyFramebuffer = dummy;
  16835. }
  16836. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16837. if (faceIndex > -1) {
  16838. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16839. }
  16840. else {
  16841. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16842. }
  16843. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16844. var buffer;
  16845. switch (readType) {
  16846. case gl.UNSIGNED_BYTE:
  16847. buffer = new Uint8Array(4 * width * height);
  16848. readType = gl.UNSIGNED_BYTE;
  16849. break;
  16850. default:
  16851. buffer = new Float32Array(4 * width * height);
  16852. readType = gl.FLOAT;
  16853. break;
  16854. }
  16855. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16856. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16857. return buffer;
  16858. };
  16859. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16860. if (this._webGLVersion > 1) {
  16861. return this._caps.colorBufferFloat;
  16862. }
  16863. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16864. };
  16865. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16866. if (this._webGLVersion > 1) {
  16867. return this._caps.colorBufferFloat;
  16868. }
  16869. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16870. };
  16871. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16872. Engine.prototype._canRenderToFramebuffer = function (type) {
  16873. var gl = this._gl;
  16874. //clear existing errors
  16875. while (gl.getError() !== gl.NO_ERROR) { }
  16876. var successful = true;
  16877. var texture = gl.createTexture();
  16878. gl.bindTexture(gl.TEXTURE_2D, texture);
  16879. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16880. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16881. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16882. var fb = gl.createFramebuffer();
  16883. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16884. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16885. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16886. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16887. successful = successful && (gl.getError() === gl.NO_ERROR);
  16888. //try render by clearing frame buffer's color buffer
  16889. if (successful) {
  16890. gl.clear(gl.COLOR_BUFFER_BIT);
  16891. successful = successful && (gl.getError() === gl.NO_ERROR);
  16892. }
  16893. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16894. if (successful) {
  16895. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16896. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16897. var readFormat = gl.RGBA;
  16898. var readType = gl.UNSIGNED_BYTE;
  16899. var buffer = new Uint8Array(4);
  16900. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16901. successful = successful && (gl.getError() === gl.NO_ERROR);
  16902. }
  16903. //clean up
  16904. gl.deleteTexture(texture);
  16905. gl.deleteFramebuffer(fb);
  16906. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16907. //clear accumulated errors
  16908. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16909. return successful;
  16910. };
  16911. /** @hidden */
  16912. Engine.prototype._getWebGLTextureType = function (type) {
  16913. if (this._webGLVersion === 1) {
  16914. switch (type) {
  16915. case Engine.TEXTURETYPE_FLOAT:
  16916. return this._gl.FLOAT;
  16917. case Engine.TEXTURETYPE_HALF_FLOAT:
  16918. return this._gl.HALF_FLOAT_OES;
  16919. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16920. return this._gl.UNSIGNED_BYTE;
  16921. }
  16922. return this._gl.UNSIGNED_BYTE;
  16923. }
  16924. switch (type) {
  16925. case Engine.TEXTURETYPE_BYTE:
  16926. return this._gl.BYTE;
  16927. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16928. return this._gl.UNSIGNED_BYTE;
  16929. case Engine.TEXTURETYPE_SHORT:
  16930. return this._gl.SHORT;
  16931. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  16932. return this._gl.UNSIGNED_SHORT;
  16933. case Engine.TEXTURETYPE_INT:
  16934. return this._gl.INT;
  16935. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  16936. return this._gl.UNSIGNED_INT;
  16937. case Engine.TEXTURETYPE_FLOAT:
  16938. return this._gl.FLOAT;
  16939. case Engine.TEXTURETYPE_HALF_FLOAT:
  16940. return this._gl.HALF_FLOAT;
  16941. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  16942. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  16943. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  16944. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  16945. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  16946. return this._gl.UNSIGNED_SHORT_5_6_5;
  16947. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  16948. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  16949. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  16950. return this._gl.UNSIGNED_INT_24_8;
  16951. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  16952. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  16953. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  16954. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  16955. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  16956. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  16957. }
  16958. return this._gl.UNSIGNED_BYTE;
  16959. };
  16960. ;
  16961. Engine.prototype._getInternalFormat = function (format) {
  16962. var internalFormat = this._gl.RGBA;
  16963. switch (format) {
  16964. case Engine.TEXTUREFORMAT_ALPHA:
  16965. internalFormat = this._gl.ALPHA;
  16966. break;
  16967. case Engine.TEXTUREFORMAT_LUMINANCE:
  16968. internalFormat = this._gl.LUMINANCE;
  16969. break;
  16970. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16971. internalFormat = this._gl.LUMINANCE_ALPHA;
  16972. break;
  16973. case Engine.TEXTUREFORMAT_RED:
  16974. internalFormat = this._gl.RED;
  16975. break;
  16976. case Engine.TEXTUREFORMAT_RG:
  16977. internalFormat = this._gl.RG;
  16978. break;
  16979. case Engine.TEXTUREFORMAT_RGB:
  16980. internalFormat = this._gl.RGB;
  16981. break;
  16982. case Engine.TEXTUREFORMAT_RGBA:
  16983. internalFormat = this._gl.RGBA;
  16984. break;
  16985. }
  16986. if (this._webGLVersion > 1) {
  16987. switch (format) {
  16988. case Engine.TEXTUREFORMAT_RED_INTEGER:
  16989. internalFormat = this._gl.RED_INTEGER;
  16990. break;
  16991. case Engine.TEXTUREFORMAT_RG_INTEGER:
  16992. internalFormat = this._gl.RG_INTEGER;
  16993. break;
  16994. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  16995. internalFormat = this._gl.RGB_INTEGER;
  16996. break;
  16997. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  16998. internalFormat = this._gl.RGBA_INTEGER;
  16999. break;
  17000. }
  17001. }
  17002. return internalFormat;
  17003. };
  17004. /** @hidden */
  17005. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17006. if (this._webGLVersion === 1) {
  17007. if (format !== undefined) {
  17008. switch (format) {
  17009. case Engine.TEXTUREFORMAT_ALPHA:
  17010. return this._gl.ALPHA;
  17011. case Engine.TEXTUREFORMAT_LUMINANCE:
  17012. return this._gl.LUMINANCE;
  17013. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17014. return this._gl.LUMINANCE_ALPHA;
  17015. }
  17016. }
  17017. return this._gl.RGBA;
  17018. }
  17019. switch (type) {
  17020. case Engine.TEXTURETYPE_BYTE:
  17021. switch (format) {
  17022. case Engine.TEXTUREFORMAT_RED:
  17023. return this._gl.R8_SNORM;
  17024. case Engine.TEXTUREFORMAT_RG:
  17025. return this._gl.RG8_SNORM;
  17026. case Engine.TEXTUREFORMAT_RGB:
  17027. return this._gl.RGB8_SNORM;
  17028. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17029. return this._gl.R8I;
  17030. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17031. return this._gl.RG8I;
  17032. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17033. return this._gl.RGB8I;
  17034. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17035. return this._gl.RGBA8I;
  17036. default:
  17037. return this._gl.RGBA8_SNORM;
  17038. }
  17039. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17040. switch (format) {
  17041. case Engine.TEXTUREFORMAT_RED:
  17042. return this._gl.R8;
  17043. case Engine.TEXTUREFORMAT_RG:
  17044. return this._gl.RG8;
  17045. case Engine.TEXTUREFORMAT_RGB:
  17046. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17047. case Engine.TEXTUREFORMAT_RGBA:
  17048. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17049. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17050. return this._gl.R8UI;
  17051. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17052. return this._gl.RG8UI;
  17053. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17054. return this._gl.RGB8UI;
  17055. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17056. return this._gl.RGBA8UI;
  17057. default:
  17058. return this._gl.RGBA8;
  17059. }
  17060. case Engine.TEXTURETYPE_SHORT:
  17061. switch (format) {
  17062. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17063. return this._gl.R16I;
  17064. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17065. return this._gl.RG16I;
  17066. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17067. return this._gl.RGB16I;
  17068. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17069. return this._gl.RGBA16I;
  17070. default:
  17071. return this._gl.RGBA16I;
  17072. }
  17073. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17074. switch (format) {
  17075. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17076. return this._gl.R16UI;
  17077. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17078. return this._gl.RG16UI;
  17079. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17080. return this._gl.RGB16UI;
  17081. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17082. return this._gl.RGBA16UI;
  17083. default:
  17084. return this._gl.RGBA16UI;
  17085. }
  17086. case Engine.TEXTURETYPE_INT:
  17087. switch (format) {
  17088. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17089. return this._gl.R32I;
  17090. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17091. return this._gl.RG32I;
  17092. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17093. return this._gl.RGB32I;
  17094. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17095. return this._gl.RGBA32I;
  17096. default:
  17097. return this._gl.RGBA32I;
  17098. }
  17099. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17100. switch (format) {
  17101. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17102. return this._gl.R32UI;
  17103. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17104. return this._gl.RG32UI;
  17105. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17106. return this._gl.RGB32UI;
  17107. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17108. return this._gl.RGBA32UI;
  17109. default:
  17110. return this._gl.RGBA32UI;
  17111. }
  17112. case Engine.TEXTURETYPE_FLOAT:
  17113. switch (format) {
  17114. case Engine.TEXTUREFORMAT_RED:
  17115. return this._gl.R32F; // By default. Other possibility is R16F.
  17116. case Engine.TEXTUREFORMAT_RG:
  17117. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17118. case Engine.TEXTUREFORMAT_RGB:
  17119. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17120. case Engine.TEXTUREFORMAT_RGBA:
  17121. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17122. default:
  17123. return this._gl.RGBA32F;
  17124. }
  17125. case Engine.TEXTURETYPE_HALF_FLOAT:
  17126. switch (format) {
  17127. case Engine.TEXTUREFORMAT_RED:
  17128. return this._gl.R16F;
  17129. case Engine.TEXTUREFORMAT_RG:
  17130. return this._gl.RG16F;
  17131. case Engine.TEXTUREFORMAT_RGB:
  17132. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17133. case Engine.TEXTUREFORMAT_RGBA:
  17134. return this._gl.RGBA16F;
  17135. default:
  17136. return this._gl.RGBA16F;
  17137. }
  17138. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17139. return this._gl.RGB565;
  17140. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17141. return this._gl.R11F_G11F_B10F;
  17142. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17143. return this._gl.RGB9_E5;
  17144. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17145. return this._gl.RGBA4;
  17146. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17147. return this._gl.RGB5_A1;
  17148. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17149. switch (format) {
  17150. case Engine.TEXTUREFORMAT_RGBA:
  17151. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17152. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17153. return this._gl.RGB10_A2UI;
  17154. default:
  17155. return this._gl.RGB10_A2;
  17156. }
  17157. }
  17158. return this._gl.RGBA8;
  17159. };
  17160. ;
  17161. /** @hidden */
  17162. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17163. if (type === Engine.TEXTURETYPE_FLOAT) {
  17164. return this._gl.RGBA32F;
  17165. }
  17166. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17167. return this._gl.RGBA16F;
  17168. }
  17169. return this._gl.RGBA8;
  17170. };
  17171. ;
  17172. /** @hidden */
  17173. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17174. var _this = this;
  17175. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17176. this._activeRequests.push(request);
  17177. request.onCompleteObservable.add(function (request) {
  17178. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17179. });
  17180. return request;
  17181. };
  17182. /** @hidden */
  17183. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17184. var _this = this;
  17185. return new Promise(function (resolve, reject) {
  17186. _this._loadFile(url, function (data) {
  17187. resolve(data);
  17188. }, undefined, database, useArrayBuffer, function (request, exception) {
  17189. reject(exception);
  17190. });
  17191. });
  17192. };
  17193. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17194. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17195. var onload = function (data) {
  17196. loadedFiles[index] = data;
  17197. loadedFiles._internalCount++;
  17198. if (loadedFiles._internalCount === 6) {
  17199. onfinish(loadedFiles);
  17200. }
  17201. };
  17202. var onerror = function (request, exception) {
  17203. if (onErrorCallBack && request) {
  17204. onErrorCallBack(request.status + " " + request.statusText, exception);
  17205. }
  17206. };
  17207. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17208. };
  17209. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17210. if (onError === void 0) { onError = null; }
  17211. var loadedFiles = [];
  17212. loadedFiles._internalCount = 0;
  17213. for (var index = 0; index < 6; index++) {
  17214. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17215. }
  17216. };
  17217. // Statics
  17218. /**
  17219. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17220. * @returns true if the engine can be created
  17221. * @ignorenaming
  17222. */
  17223. Engine.isSupported = function () {
  17224. try {
  17225. var tempcanvas = document.createElement("canvas");
  17226. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17227. return gl != null && !!window.WebGLRenderingContext;
  17228. }
  17229. catch (e) {
  17230. return false;
  17231. }
  17232. };
  17233. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17234. Engine.ExceptionList = [
  17235. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17236. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17237. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17238. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17239. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17240. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17241. ];
  17242. /** Gets the list of created engines */
  17243. Engine.Instances = new Array();
  17244. /**
  17245. * Hidden
  17246. */
  17247. Engine._TextureLoaders = [];
  17248. // Const statics
  17249. /** Defines that alpha blending is disabled */
  17250. Engine.ALPHA_DISABLE = 0;
  17251. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17252. Engine.ALPHA_ADD = 1;
  17253. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17254. Engine.ALPHA_COMBINE = 2;
  17255. /** Defines that alpha blending to DEST - SRC * DEST */
  17256. Engine.ALPHA_SUBTRACT = 3;
  17257. /** Defines that alpha blending to SRC * DEST */
  17258. Engine.ALPHA_MULTIPLY = 4;
  17259. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17260. Engine.ALPHA_MAXIMIZED = 5;
  17261. /** Defines that alpha blending to SRC + DEST */
  17262. Engine.ALPHA_ONEONE = 6;
  17263. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17264. Engine.ALPHA_PREMULTIPLIED = 7;
  17265. /**
  17266. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17267. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17268. */
  17269. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17270. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17271. Engine.ALPHA_INTERPOLATE = 9;
  17272. /**
  17273. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17274. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17275. */
  17276. Engine.ALPHA_SCREENMODE = 10;
  17277. /** Defines that the ressource is not delayed*/
  17278. Engine.DELAYLOADSTATE_NONE = 0;
  17279. /** Defines that the ressource was successfully delay loaded */
  17280. Engine.DELAYLOADSTATE_LOADED = 1;
  17281. /** Defines that the ressource is currently delay loading */
  17282. Engine.DELAYLOADSTATE_LOADING = 2;
  17283. /** Defines that the ressource is delayed and has not started loading */
  17284. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17285. // Depht or Stencil test Constants.
  17286. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17287. Engine.NEVER = 0x0200;
  17288. /** 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 */
  17289. Engine.ALWAYS = 0x0207;
  17290. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17291. Engine.LESS = 0x0201;
  17292. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17293. Engine.EQUAL = 0x0202;
  17294. /** 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 */
  17295. Engine.LEQUAL = 0x0203;
  17296. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17297. Engine.GREATER = 0x0204;
  17298. /** 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 */
  17299. Engine.GEQUAL = 0x0206;
  17300. /** 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 */
  17301. Engine.NOTEQUAL = 0x0205;
  17302. // Stencil Actions Constants.
  17303. /** Passed to stencilOperation to specify that stencil value must be kept */
  17304. Engine.KEEP = 0x1E00;
  17305. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17306. Engine.REPLACE = 0x1E01;
  17307. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17308. Engine.INCR = 0x1E02;
  17309. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17310. Engine.DECR = 0x1E03;
  17311. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17312. Engine.INVERT = 0x150A;
  17313. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17314. Engine.INCR_WRAP = 0x8507;
  17315. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17316. Engine.DECR_WRAP = 0x8508;
  17317. /** Texture is not repeating outside of 0..1 UVs */
  17318. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17319. /** Texture is repeating outside of 0..1 UVs */
  17320. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17321. /** Texture is repeating and mirrored */
  17322. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17323. /** ALPHA */
  17324. Engine.TEXTUREFORMAT_ALPHA = 0;
  17325. /** LUMINANCE */
  17326. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17327. /** LUMINANCE_ALPHA */
  17328. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17329. /** RGB */
  17330. Engine.TEXTUREFORMAT_RGB = 4;
  17331. /** RGBA */
  17332. Engine.TEXTUREFORMAT_RGBA = 5;
  17333. /** RED */
  17334. Engine.TEXTUREFORMAT_RED = 6;
  17335. /** RED (2nd reference) */
  17336. Engine.TEXTUREFORMAT_R = 6;
  17337. /** RG */
  17338. Engine.TEXTUREFORMAT_RG = 7;
  17339. /** RED_INTEGER */
  17340. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17341. /** RED_INTEGER (2nd reference) */
  17342. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17343. /** RG_INTEGER */
  17344. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17345. /** RGB_INTEGER */
  17346. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17347. /** RGBA_INTEGER */
  17348. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17349. /** UNSIGNED_BYTE */
  17350. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17351. /** UNSIGNED_BYTE (2nd reference) */
  17352. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17353. /** FLOAT */
  17354. Engine.TEXTURETYPE_FLOAT = 1;
  17355. /** HALF_FLOAT */
  17356. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17357. /** BYTE */
  17358. Engine.TEXTURETYPE_BYTE = 3;
  17359. /** SHORT */
  17360. Engine.TEXTURETYPE_SHORT = 4;
  17361. /** UNSIGNED_SHORT */
  17362. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17363. /** INT */
  17364. Engine.TEXTURETYPE_INT = 6;
  17365. /** UNSIGNED_INT */
  17366. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17367. /** UNSIGNED_SHORT_4_4_4_4 */
  17368. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17369. /** UNSIGNED_SHORT_5_5_5_1 */
  17370. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17371. /** UNSIGNED_SHORT_5_6_5 */
  17372. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17373. /** UNSIGNED_INT_2_10_10_10_REV */
  17374. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17375. /** UNSIGNED_INT_24_8 */
  17376. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17377. /** UNSIGNED_INT_10F_11F_11F_REV */
  17378. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17379. /** UNSIGNED_INT_5_9_9_9_REV */
  17380. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17381. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17382. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17383. /** nearest is mag = nearest and min = nearest and mip = linear */
  17384. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17385. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17386. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17387. /** Trilinear is mag = linear and min = linear and mip = linear */
  17388. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17389. /** nearest is mag = nearest and min = nearest and mip = linear */
  17390. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17391. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17392. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17393. /** Trilinear is mag = linear and min = linear and mip = linear */
  17394. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17395. /** mag = nearest and min = nearest and mip = nearest */
  17396. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17397. /** mag = nearest and min = linear and mip = nearest */
  17398. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17399. /** mag = nearest and min = linear and mip = linear */
  17400. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17401. /** mag = nearest and min = linear and mip = none */
  17402. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17403. /** mag = nearest and min = nearest and mip = none */
  17404. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17405. /** mag = linear and min = nearest and mip = nearest */
  17406. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17407. /** mag = linear and min = nearest and mip = linear */
  17408. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17409. /** mag = linear and min = linear and mip = none */
  17410. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17411. /** mag = linear and min = nearest and mip = none */
  17412. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17413. /** Explicit coordinates mode */
  17414. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17415. /** Spherical coordinates mode */
  17416. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17417. /** Planar coordinates mode */
  17418. Engine.TEXTURE_PLANAR_MODE = 2;
  17419. /** Cubic coordinates mode */
  17420. Engine.TEXTURE_CUBIC_MODE = 3;
  17421. /** Projection coordinates mode */
  17422. Engine.TEXTURE_PROJECTION_MODE = 4;
  17423. /** Skybox coordinates mode */
  17424. Engine.TEXTURE_SKYBOX_MODE = 5;
  17425. /** Inverse Cubic coordinates mode */
  17426. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17427. /** Equirectangular coordinates mode */
  17428. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17429. /** Equirectangular Fixed coordinates mode */
  17430. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17431. /** Equirectangular Fixed Mirrored coordinates mode */
  17432. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17433. // Texture rescaling mode
  17434. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17435. Engine.SCALEMODE_FLOOR = 1;
  17436. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17437. Engine.SCALEMODE_NEAREST = 2;
  17438. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17439. Engine.SCALEMODE_CEILING = 3;
  17440. // Updatable statics so stick with vars here
  17441. /**
  17442. * Gets or sets the epsilon value used by collision engine
  17443. */
  17444. Engine.CollisionsEpsilon = 0.001;
  17445. /**
  17446. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17447. */
  17448. Engine.CodeRepository = "src/";
  17449. /**
  17450. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17451. */
  17452. Engine.ShadersRepository = "src/Shaders/";
  17453. return Engine;
  17454. }());
  17455. BABYLON.Engine = Engine;
  17456. })(BABYLON || (BABYLON = {}));
  17457. //# sourceMappingURL=babylon.engine.js.map
  17458. var BABYLON;
  17459. (function (BABYLON) {
  17460. /**
  17461. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17462. */
  17463. var Node = /** @class */ (function () {
  17464. /**
  17465. * Creates a new Node
  17466. * @param {string} name - the name and id to be given to this node
  17467. * @param {BABYLON.Scene} the scene this node will be added to
  17468. */
  17469. function Node(name, scene) {
  17470. if (scene === void 0) { scene = null; }
  17471. /**
  17472. * Gets or sets a string used to store user defined state for the node
  17473. */
  17474. this.state = "";
  17475. /**
  17476. * Gets or sets an object used to store user defined information for the node
  17477. */
  17478. this.metadata = null;
  17479. /**
  17480. * Gets or sets a boolean used to define if the node must be serialized
  17481. */
  17482. this.doNotSerialize = false;
  17483. /** @hidden */
  17484. this._isDisposed = false;
  17485. /**
  17486. * Gets a list of Animations associated with the node
  17487. */
  17488. this.animations = new Array();
  17489. this._ranges = {};
  17490. this._isEnabled = true;
  17491. this._isReady = true;
  17492. /** @hidden */
  17493. this._currentRenderId = -1;
  17494. this._parentRenderId = -1;
  17495. this._childRenderId = -1;
  17496. this._animationPropertiesOverride = null;
  17497. /**
  17498. * An event triggered when the mesh is disposed
  17499. */
  17500. this.onDisposeObservable = new BABYLON.Observable();
  17501. // Behaviors
  17502. this._behaviors = new Array();
  17503. this.name = name;
  17504. this.id = name;
  17505. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17506. this.uniqueId = this._scene.getUniqueId();
  17507. this._initCache();
  17508. }
  17509. /**
  17510. * Add a new node constructor
  17511. * @param type defines the type name of the node to construct
  17512. * @param constructorFunc defines the constructor function
  17513. */
  17514. Node.AddNodeConstructor = function (type, constructorFunc) {
  17515. this._NodeConstructors[type] = constructorFunc;
  17516. };
  17517. /**
  17518. * Returns a node constructor based on type name
  17519. * @param type defines the type name
  17520. * @param name defines the new node name
  17521. * @param scene defines the hosting scene
  17522. * @param options defines optional options to transmit to constructors
  17523. * @returns the new constructor or null
  17524. */
  17525. Node.Construct = function (type, name, scene, options) {
  17526. var constructorFunc = this._NodeConstructors[type];
  17527. if (!constructorFunc) {
  17528. return null;
  17529. }
  17530. return constructorFunc(name, scene, options);
  17531. };
  17532. /**
  17533. * Gets a boolean indicating if the node has been disposed
  17534. * @returns true if the node was disposed
  17535. */
  17536. Node.prototype.isDisposed = function () {
  17537. return this._isDisposed;
  17538. };
  17539. Object.defineProperty(Node.prototype, "parent", {
  17540. get: function () {
  17541. return this._parentNode;
  17542. },
  17543. /**
  17544. * Gets or sets the parent of the node
  17545. */
  17546. set: function (parent) {
  17547. if (this._parentNode === parent) {
  17548. return;
  17549. }
  17550. // Remove self from list of children of parent
  17551. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17552. var index = this._parentNode._children.indexOf(this);
  17553. if (index !== -1) {
  17554. this._parentNode._children.splice(index, 1);
  17555. }
  17556. }
  17557. // Store new parent
  17558. this._parentNode = parent;
  17559. // Add as child to new parent
  17560. if (this._parentNode) {
  17561. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17562. this._parentNode._children = new Array();
  17563. }
  17564. this._parentNode._children.push(this);
  17565. }
  17566. },
  17567. enumerable: true,
  17568. configurable: true
  17569. });
  17570. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17571. /**
  17572. * Gets or sets the animation properties override
  17573. */
  17574. get: function () {
  17575. if (!this._animationPropertiesOverride) {
  17576. return this._scene.animationPropertiesOverride;
  17577. }
  17578. return this._animationPropertiesOverride;
  17579. },
  17580. set: function (value) {
  17581. this._animationPropertiesOverride = value;
  17582. },
  17583. enumerable: true,
  17584. configurable: true
  17585. });
  17586. /**
  17587. * Gets a string idenfifying the name of the class
  17588. * @returns "Node" string
  17589. */
  17590. Node.prototype.getClassName = function () {
  17591. return "Node";
  17592. };
  17593. Object.defineProperty(Node.prototype, "onDispose", {
  17594. /**
  17595. * Sets a callback that will be raised when the node will be disposed
  17596. */
  17597. set: function (callback) {
  17598. if (this._onDisposeObserver) {
  17599. this.onDisposeObservable.remove(this._onDisposeObserver);
  17600. }
  17601. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17602. },
  17603. enumerable: true,
  17604. configurable: true
  17605. });
  17606. /**
  17607. * Gets the scene of the node
  17608. * @returns a {BABYLON.Scene}
  17609. */
  17610. Node.prototype.getScene = function () {
  17611. return this._scene;
  17612. };
  17613. /**
  17614. * Gets the engine of the node
  17615. * @returns a {BABYLON.Engine}
  17616. */
  17617. Node.prototype.getEngine = function () {
  17618. return this._scene.getEngine();
  17619. };
  17620. /**
  17621. * Attach a behavior to the node
  17622. * @see http://doc.babylonjs.com/features/behaviour
  17623. * @param behavior defines the behavior to attach
  17624. * @returns the current Node
  17625. */
  17626. Node.prototype.addBehavior = function (behavior) {
  17627. var _this = this;
  17628. var index = this._behaviors.indexOf(behavior);
  17629. if (index !== -1) {
  17630. return this;
  17631. }
  17632. behavior.init();
  17633. if (this._scene.isLoading) {
  17634. // We defer the attach when the scene will be loaded
  17635. this._scene.onDataLoadedObservable.addOnce(function () {
  17636. behavior.attach(_this);
  17637. });
  17638. }
  17639. else {
  17640. behavior.attach(this);
  17641. }
  17642. this._behaviors.push(behavior);
  17643. return this;
  17644. };
  17645. /**
  17646. * Remove an attached behavior
  17647. * @see http://doc.babylonjs.com/features/behaviour
  17648. * @param behavior defines the behavior to attach
  17649. * @returns the current Node
  17650. */
  17651. Node.prototype.removeBehavior = function (behavior) {
  17652. var index = this._behaviors.indexOf(behavior);
  17653. if (index === -1) {
  17654. return this;
  17655. }
  17656. this._behaviors[index].detach();
  17657. this._behaviors.splice(index, 1);
  17658. return this;
  17659. };
  17660. Object.defineProperty(Node.prototype, "behaviors", {
  17661. /**
  17662. * Gets the list of attached behaviors
  17663. * @see http://doc.babylonjs.com/features/behaviour
  17664. */
  17665. get: function () {
  17666. return this._behaviors;
  17667. },
  17668. enumerable: true,
  17669. configurable: true
  17670. });
  17671. /**
  17672. * Gets an attached behavior by name
  17673. * @param name defines the name of the behavior to look for
  17674. * @see http://doc.babylonjs.com/features/behaviour
  17675. * @returns null if behavior was not found else the requested behavior
  17676. */
  17677. Node.prototype.getBehaviorByName = function (name) {
  17678. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17679. var behavior = _a[_i];
  17680. if (behavior.name === name) {
  17681. return behavior;
  17682. }
  17683. }
  17684. return null;
  17685. };
  17686. /**
  17687. * Returns the world matrix of the node
  17688. * @returns a matrix containing the node's world matrix
  17689. */
  17690. Node.prototype.getWorldMatrix = function () {
  17691. return BABYLON.Matrix.Identity();
  17692. };
  17693. /** @hidden */
  17694. Node.prototype._getWorldMatrixDeterminant = function () {
  17695. return 1;
  17696. };
  17697. // override it in derived class if you add new variables to the cache
  17698. // and call the parent class method
  17699. /** @hidden */
  17700. Node.prototype._initCache = function () {
  17701. this._cache = {};
  17702. this._cache.parent = undefined;
  17703. };
  17704. /** @hidden */
  17705. Node.prototype.updateCache = function (force) {
  17706. if (!force && this.isSynchronized())
  17707. return;
  17708. this._cache.parent = this.parent;
  17709. this._updateCache();
  17710. };
  17711. // override it in derived class if you add new variables to the cache
  17712. // and call the parent class method if !ignoreParentClass
  17713. /** @hidden */
  17714. Node.prototype._updateCache = function (ignoreParentClass) {
  17715. };
  17716. // override it in derived class if you add new variables to the cache
  17717. /** @hidden */
  17718. Node.prototype._isSynchronized = function () {
  17719. return true;
  17720. };
  17721. /** @hidden */
  17722. Node.prototype._markSyncedWithParent = function () {
  17723. if (this.parent) {
  17724. this._parentRenderId = this.parent._childRenderId;
  17725. }
  17726. };
  17727. /** @hidden */
  17728. Node.prototype.isSynchronizedWithParent = function () {
  17729. if (!this.parent) {
  17730. return true;
  17731. }
  17732. if (this._parentRenderId !== this.parent._childRenderId) {
  17733. return false;
  17734. }
  17735. return this.parent.isSynchronized();
  17736. };
  17737. /** @hidden */
  17738. Node.prototype.isSynchronized = function (updateCache) {
  17739. var check = this.hasNewParent();
  17740. check = check || !this.isSynchronizedWithParent();
  17741. check = check || !this._isSynchronized();
  17742. if (updateCache)
  17743. this.updateCache(true);
  17744. return !check;
  17745. };
  17746. /** @hidden */
  17747. Node.prototype.hasNewParent = function (update) {
  17748. if (this._cache.parent === this.parent)
  17749. return false;
  17750. if (update)
  17751. this._cache.parent = this.parent;
  17752. return true;
  17753. };
  17754. /**
  17755. * Is this node ready to be used/rendered
  17756. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17757. * @return true if the node is ready
  17758. */
  17759. Node.prototype.isReady = function (completeCheck) {
  17760. if (completeCheck === void 0) { completeCheck = false; }
  17761. return this._isReady;
  17762. };
  17763. /**
  17764. * Is this node enabled?
  17765. * 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
  17766. * @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
  17767. * @return whether this node (and its parent) is enabled
  17768. */
  17769. Node.prototype.isEnabled = function (checkAncestors) {
  17770. if (checkAncestors === void 0) { checkAncestors = true; }
  17771. if (checkAncestors === false) {
  17772. return this._isEnabled;
  17773. }
  17774. if (this._isEnabled === false) {
  17775. return false;
  17776. }
  17777. if (this.parent !== undefined && this.parent !== null) {
  17778. return this.parent.isEnabled(checkAncestors);
  17779. }
  17780. return true;
  17781. };
  17782. /**
  17783. * Set the enabled state of this node
  17784. * @param value defines the new enabled state
  17785. */
  17786. Node.prototype.setEnabled = function (value) {
  17787. this._isEnabled = value;
  17788. };
  17789. /**
  17790. * Is this node a descendant of the given node?
  17791. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17792. * @param ancestor defines the parent node to inspect
  17793. * @returns a boolean indicating if this node is a descendant of the given node
  17794. */
  17795. Node.prototype.isDescendantOf = function (ancestor) {
  17796. if (this.parent) {
  17797. if (this.parent === ancestor) {
  17798. return true;
  17799. }
  17800. return this.parent.isDescendantOf(ancestor);
  17801. }
  17802. return false;
  17803. };
  17804. /** @hidden */
  17805. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17806. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17807. if (!this._children) {
  17808. return;
  17809. }
  17810. for (var index = 0; index < this._children.length; index++) {
  17811. var item = this._children[index];
  17812. if (!predicate || predicate(item)) {
  17813. results.push(item);
  17814. }
  17815. if (!directDescendantsOnly) {
  17816. item._getDescendants(results, false, predicate);
  17817. }
  17818. }
  17819. };
  17820. /**
  17821. * Will return all nodes that have this node as ascendant
  17822. * @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
  17823. * @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
  17824. * @return all children nodes of all types
  17825. */
  17826. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17827. var results = new Array();
  17828. this._getDescendants(results, directDescendantsOnly, predicate);
  17829. return results;
  17830. };
  17831. /**
  17832. * Get all child-meshes of this node
  17833. * @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
  17834. * @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
  17835. * @returns an array of {BABYLON.AbstractMesh}
  17836. */
  17837. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17838. var results = [];
  17839. this._getDescendants(results, directDescendantsOnly, function (node) {
  17840. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17841. });
  17842. return results;
  17843. };
  17844. /**
  17845. * Get all child-transformNodes of this node
  17846. * @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
  17847. * @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
  17848. * @returns an array of {BABYLON.TransformNode}
  17849. */
  17850. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17851. var results = [];
  17852. this._getDescendants(results, directDescendantsOnly, function (node) {
  17853. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17854. });
  17855. return results;
  17856. };
  17857. /**
  17858. * Get all direct children of this node
  17859. * @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
  17860. * @returns an array of {BABYLON.Node}
  17861. */
  17862. Node.prototype.getChildren = function (predicate) {
  17863. return this.getDescendants(true, predicate);
  17864. };
  17865. /** @hidden */
  17866. Node.prototype._setReady = function (state) {
  17867. if (state === this._isReady) {
  17868. return;
  17869. }
  17870. if (!state) {
  17871. this._isReady = false;
  17872. return;
  17873. }
  17874. if (this.onReady) {
  17875. this.onReady(this);
  17876. }
  17877. this._isReady = true;
  17878. };
  17879. /**
  17880. * Get an animation by name
  17881. * @param name defines the name of the animation to look for
  17882. * @returns null if not found else the requested animation
  17883. */
  17884. Node.prototype.getAnimationByName = function (name) {
  17885. for (var i = 0; i < this.animations.length; i++) {
  17886. var animation = this.animations[i];
  17887. if (animation.name === name) {
  17888. return animation;
  17889. }
  17890. }
  17891. return null;
  17892. };
  17893. /**
  17894. * Creates an animation range for this node
  17895. * @param name defines the name of the range
  17896. * @param from defines the starting key
  17897. * @param to defines the end key
  17898. */
  17899. Node.prototype.createAnimationRange = function (name, from, to) {
  17900. // check name not already in use
  17901. if (!this._ranges[name]) {
  17902. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17903. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17904. if (this.animations[i]) {
  17905. this.animations[i].createRange(name, from, to);
  17906. }
  17907. }
  17908. }
  17909. };
  17910. /**
  17911. * Delete a specific animation range
  17912. * @param name defines the name of the range to delete
  17913. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17914. */
  17915. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17916. if (deleteFrames === void 0) { deleteFrames = true; }
  17917. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17918. if (this.animations[i]) {
  17919. this.animations[i].deleteRange(name, deleteFrames);
  17920. }
  17921. }
  17922. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17923. };
  17924. /**
  17925. * Get an animation range by name
  17926. * @param name defines the name of the animation range to look for
  17927. * @returns null if not found else the requested animation range
  17928. */
  17929. Node.prototype.getAnimationRange = function (name) {
  17930. return this._ranges[name];
  17931. };
  17932. /**
  17933. * Will start the animation sequence
  17934. * @param name defines the range frames for animation sequence
  17935. * @param loop defines if the animation should loop (false by default)
  17936. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17937. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17938. * @returns the object created for this animation. If range does not exist, it will return null
  17939. */
  17940. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17941. var range = this.getAnimationRange(name);
  17942. if (!range) {
  17943. return null;
  17944. }
  17945. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17946. };
  17947. /**
  17948. * Serialize animation ranges into a JSON compatible object
  17949. * @returns serialization object
  17950. */
  17951. Node.prototype.serializeAnimationRanges = function () {
  17952. var serializationRanges = [];
  17953. for (var name in this._ranges) {
  17954. var localRange = this._ranges[name];
  17955. if (!localRange) {
  17956. continue;
  17957. }
  17958. var range = {};
  17959. range.name = name;
  17960. range.from = localRange.from;
  17961. range.to = localRange.to;
  17962. serializationRanges.push(range);
  17963. }
  17964. return serializationRanges;
  17965. };
  17966. /**
  17967. * Computes the world matrix of the node
  17968. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17969. * @returns the world matrix
  17970. */
  17971. Node.prototype.computeWorldMatrix = function (force) {
  17972. return BABYLON.Matrix.Identity();
  17973. };
  17974. /**
  17975. * Releases resources associated with this node.
  17976. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17977. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17978. */
  17979. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17980. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17981. if (!doNotRecurse) {
  17982. var nodes = this.getDescendants(true);
  17983. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17984. var node = nodes_1[_i];
  17985. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17986. }
  17987. }
  17988. else {
  17989. var transformNodes = this.getChildTransformNodes(true);
  17990. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17991. var transformNode = transformNodes_1[_a];
  17992. transformNode.parent = null;
  17993. transformNode.computeWorldMatrix(true);
  17994. }
  17995. }
  17996. this.parent = null;
  17997. // Callback
  17998. this.onDisposeObservable.notifyObservers(this);
  17999. this.onDisposeObservable.clear();
  18000. // Behaviors
  18001. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18002. var behavior = _c[_b];
  18003. behavior.detach();
  18004. }
  18005. this._behaviors = [];
  18006. this._isDisposed = true;
  18007. };
  18008. /**
  18009. * Parse animation range data from a serialization object and store them into a given node
  18010. * @param node defines where to store the animation ranges
  18011. * @param parsedNode defines the serialization object to read data from
  18012. * @param scene defines the hosting scene
  18013. */
  18014. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18015. if (parsedNode.ranges) {
  18016. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18017. var data = parsedNode.ranges[index];
  18018. node.createAnimationRange(data.name, data.from, data.to);
  18019. }
  18020. }
  18021. };
  18022. Node._NodeConstructors = {};
  18023. __decorate([
  18024. BABYLON.serialize()
  18025. ], Node.prototype, "name", void 0);
  18026. __decorate([
  18027. BABYLON.serialize()
  18028. ], Node.prototype, "id", void 0);
  18029. __decorate([
  18030. BABYLON.serialize()
  18031. ], Node.prototype, "uniqueId", void 0);
  18032. __decorate([
  18033. BABYLON.serialize()
  18034. ], Node.prototype, "state", void 0);
  18035. __decorate([
  18036. BABYLON.serialize()
  18037. ], Node.prototype, "metadata", void 0);
  18038. return Node;
  18039. }());
  18040. BABYLON.Node = Node;
  18041. })(BABYLON || (BABYLON = {}));
  18042. //# sourceMappingURL=babylon.node.js.map
  18043. var BABYLON;
  18044. (function (BABYLON) {
  18045. var BoundingSphere = /** @class */ (function () {
  18046. /**
  18047. * Creates a new bounding sphere
  18048. * @param min defines the minimum vector (in local space)
  18049. * @param max defines the maximum vector (in local space)
  18050. */
  18051. function BoundingSphere(min, max) {
  18052. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18053. this.reConstruct(min, max);
  18054. }
  18055. /**
  18056. * Recreates the entire bounding sphere from scratch
  18057. * @param min defines the new minimum vector (in local space)
  18058. * @param max defines the new maximum vector (in local space)
  18059. */
  18060. BoundingSphere.prototype.reConstruct = function (min, max) {
  18061. this.minimum = min.clone();
  18062. this.maximum = max.clone();
  18063. var distance = BABYLON.Vector3.Distance(min, max);
  18064. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18065. this.radius = distance * 0.5;
  18066. this.centerWorld = BABYLON.Vector3.Zero();
  18067. this._update(BABYLON.Matrix.Identity());
  18068. };
  18069. /**
  18070. * Scale the current bounding sphere by applying a scale factor
  18071. * @param factor defines the scale factor to apply
  18072. * @returns the current bounding box
  18073. */
  18074. BoundingSphere.prototype.scale = function (factor) {
  18075. var newRadius = this.radius * factor;
  18076. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  18077. var min = this.center.subtract(newRadiusVector);
  18078. var max = this.center.add(newRadiusVector);
  18079. this.reConstruct(min, max);
  18080. return this;
  18081. };
  18082. // Methods
  18083. /** @hidden */
  18084. BoundingSphere.prototype._update = function (world) {
  18085. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18086. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18087. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18088. };
  18089. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18090. for (var i = 0; i < 6; i++) {
  18091. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18092. return false;
  18093. }
  18094. return true;
  18095. };
  18096. BoundingSphere.prototype.intersectsPoint = function (point) {
  18097. var x = this.centerWorld.x - point.x;
  18098. var y = this.centerWorld.y - point.y;
  18099. var z = this.centerWorld.z - point.z;
  18100. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18101. if (this.radiusWorld < distance)
  18102. return false;
  18103. return true;
  18104. };
  18105. // Statics
  18106. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18107. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18108. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18109. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18110. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18111. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18112. return false;
  18113. return true;
  18114. };
  18115. return BoundingSphere;
  18116. }());
  18117. BABYLON.BoundingSphere = BoundingSphere;
  18118. })(BABYLON || (BABYLON = {}));
  18119. //# sourceMappingURL=babylon.boundingSphere.js.map
  18120. var BABYLON;
  18121. (function (BABYLON) {
  18122. var BoundingBox = /** @class */ (function () {
  18123. /**
  18124. * Creates a new bounding box
  18125. * @param min defines the minimum vector (in local space)
  18126. * @param max defines the maximum vector (in local space)
  18127. */
  18128. function BoundingBox(min, max) {
  18129. this.vectorsWorld = new Array();
  18130. this.reConstruct(min, max);
  18131. }
  18132. // Methods
  18133. /**
  18134. * Recreates the entire bounding box from scratch
  18135. * @param min defines the new minimum vector (in local space)
  18136. * @param max defines the new maximum vector (in local space)
  18137. */
  18138. BoundingBox.prototype.reConstruct = function (min, max) {
  18139. this.minimum = min.clone();
  18140. this.maximum = max.clone();
  18141. // Bounding vectors
  18142. this.vectors = new Array();
  18143. this.vectors.push(this.minimum.clone());
  18144. this.vectors.push(this.maximum.clone());
  18145. this.vectors.push(this.minimum.clone());
  18146. this.vectors[2].x = this.maximum.x;
  18147. this.vectors.push(this.minimum.clone());
  18148. this.vectors[3].y = this.maximum.y;
  18149. this.vectors.push(this.minimum.clone());
  18150. this.vectors[4].z = this.maximum.z;
  18151. this.vectors.push(this.maximum.clone());
  18152. this.vectors[5].z = this.minimum.z;
  18153. this.vectors.push(this.maximum.clone());
  18154. this.vectors[6].x = this.minimum.x;
  18155. this.vectors.push(this.maximum.clone());
  18156. this.vectors[7].y = this.minimum.y;
  18157. // OBB
  18158. this.center = this.maximum.add(this.minimum).scale(0.5);
  18159. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18160. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18161. // World
  18162. for (var index = 0; index < this.vectors.length; index++) {
  18163. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18164. }
  18165. this.minimumWorld = BABYLON.Vector3.Zero();
  18166. this.maximumWorld = BABYLON.Vector3.Zero();
  18167. this.centerWorld = BABYLON.Vector3.Zero();
  18168. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18169. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18170. };
  18171. /**
  18172. * Scale the current bounding box by applying a scale factor
  18173. * @param factor defines the scale factor to apply
  18174. * @returns the current bounding box
  18175. */
  18176. BoundingBox.prototype.scale = function (factor) {
  18177. var diff = this.maximum.subtract(this.minimum);
  18178. var distance = diff.length() * factor;
  18179. diff.normalize();
  18180. var newRadius = diff.scale(distance / 2);
  18181. var min = this.center.subtract(newRadius);
  18182. var max = this.center.add(newRadius);
  18183. this.reConstruct(min, max);
  18184. return this;
  18185. };
  18186. BoundingBox.prototype.getWorldMatrix = function () {
  18187. return this._worldMatrix;
  18188. };
  18189. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18190. this._worldMatrix.copyFrom(matrix);
  18191. return this;
  18192. };
  18193. /** @hidden */
  18194. BoundingBox.prototype._update = function (world) {
  18195. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18196. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18197. for (var index = 0; index < this.vectors.length; index++) {
  18198. var v = this.vectorsWorld[index];
  18199. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18200. if (v.x < this.minimumWorld.x)
  18201. this.minimumWorld.x = v.x;
  18202. if (v.y < this.minimumWorld.y)
  18203. this.minimumWorld.y = v.y;
  18204. if (v.z < this.minimumWorld.z)
  18205. this.minimumWorld.z = v.z;
  18206. if (v.x > this.maximumWorld.x)
  18207. this.maximumWorld.x = v.x;
  18208. if (v.y > this.maximumWorld.y)
  18209. this.maximumWorld.y = v.y;
  18210. if (v.z > this.maximumWorld.z)
  18211. this.maximumWorld.z = v.z;
  18212. }
  18213. // Extend
  18214. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18215. this.extendSizeWorld.scaleInPlace(0.5);
  18216. // OBB
  18217. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18218. this.centerWorld.scaleInPlace(0.5);
  18219. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18220. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18221. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18222. this._worldMatrix = world;
  18223. };
  18224. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18225. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18226. };
  18227. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18228. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18229. };
  18230. BoundingBox.prototype.intersectsPoint = function (point) {
  18231. var delta = -BABYLON.Epsilon;
  18232. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18233. return false;
  18234. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18235. return false;
  18236. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18237. return false;
  18238. return true;
  18239. };
  18240. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18241. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18242. };
  18243. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18244. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18245. return false;
  18246. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18247. return false;
  18248. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18249. return false;
  18250. return true;
  18251. };
  18252. // Statics
  18253. BoundingBox.Intersects = function (box0, box1) {
  18254. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18255. return false;
  18256. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18257. return false;
  18258. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18259. return false;
  18260. return true;
  18261. };
  18262. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18263. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18264. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18265. return (num <= (sphereRadius * sphereRadius));
  18266. };
  18267. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18268. for (var p = 0; p < 6; p++) {
  18269. for (var i = 0; i < 8; i++) {
  18270. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18271. return false;
  18272. }
  18273. }
  18274. }
  18275. return true;
  18276. };
  18277. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18278. for (var p = 0; p < 6; p++) {
  18279. var inCount = 8;
  18280. for (var i = 0; i < 8; i++) {
  18281. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18282. --inCount;
  18283. }
  18284. else {
  18285. break;
  18286. }
  18287. }
  18288. if (inCount === 0)
  18289. return false;
  18290. }
  18291. return true;
  18292. };
  18293. return BoundingBox;
  18294. }());
  18295. BABYLON.BoundingBox = BoundingBox;
  18296. })(BABYLON || (BABYLON = {}));
  18297. //# sourceMappingURL=babylon.boundingBox.js.map
  18298. var BABYLON;
  18299. (function (BABYLON) {
  18300. var computeBoxExtents = function (axis, box) {
  18301. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18302. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18303. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18304. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18305. var r = r0 + r1 + r2;
  18306. return {
  18307. min: p - r,
  18308. max: p + r
  18309. };
  18310. };
  18311. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18312. var axisOverlap = function (axis, box0, box1) {
  18313. var result0 = computeBoxExtents(axis, box0);
  18314. var result1 = computeBoxExtents(axis, box1);
  18315. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18316. };
  18317. var BoundingInfo = /** @class */ (function () {
  18318. function BoundingInfo(minimum, maximum) {
  18319. this.minimum = minimum;
  18320. this.maximum = maximum;
  18321. this._isLocked = false;
  18322. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18323. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18324. }
  18325. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18326. get: function () {
  18327. return this._isLocked;
  18328. },
  18329. set: function (value) {
  18330. this._isLocked = value;
  18331. },
  18332. enumerable: true,
  18333. configurable: true
  18334. });
  18335. // Methods
  18336. BoundingInfo.prototype.update = function (world) {
  18337. if (this._isLocked) {
  18338. return;
  18339. }
  18340. this.boundingBox._update(world);
  18341. this.boundingSphere._update(world);
  18342. };
  18343. /**
  18344. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18345. * @param center New center of the bounding info
  18346. * @param extend New extend of the bounding info
  18347. */
  18348. BoundingInfo.prototype.centerOn = function (center, extend) {
  18349. this.minimum = center.subtract(extend);
  18350. this.maximum = center.add(extend);
  18351. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18352. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18353. return this;
  18354. };
  18355. /**
  18356. * Scale the current bounding info by applying a scale factor
  18357. * @param factor defines the scale factor to apply
  18358. * @returns the current bounding info
  18359. */
  18360. BoundingInfo.prototype.scale = function (factor) {
  18361. this.boundingBox.scale(factor);
  18362. this.boundingSphere.scale(factor);
  18363. return this;
  18364. };
  18365. /**
  18366. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18367. * @param frustumPlanes defines the frustum to test
  18368. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18369. * @returns true if the bounding info is in the frustum planes
  18370. */
  18371. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18372. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18373. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18374. return false;
  18375. }
  18376. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18377. return true;
  18378. }
  18379. return this.boundingBox.isInFrustum(frustumPlanes);
  18380. };
  18381. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18382. /**
  18383. * Gets the world distance between the min and max points of the bounding box
  18384. */
  18385. get: function () {
  18386. var boundingBox = this.boundingBox;
  18387. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18388. return size.length();
  18389. },
  18390. enumerable: true,
  18391. configurable: true
  18392. });
  18393. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18394. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18395. };
  18396. /** @hidden */
  18397. BoundingInfo.prototype._checkCollision = function (collider) {
  18398. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18399. };
  18400. BoundingInfo.prototype.intersectsPoint = function (point) {
  18401. if (!this.boundingSphere.centerWorld) {
  18402. return false;
  18403. }
  18404. if (!this.boundingSphere.intersectsPoint(point)) {
  18405. return false;
  18406. }
  18407. if (!this.boundingBox.intersectsPoint(point)) {
  18408. return false;
  18409. }
  18410. return true;
  18411. };
  18412. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18413. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18414. return false;
  18415. }
  18416. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18417. return false;
  18418. }
  18419. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18420. return false;
  18421. }
  18422. if (!precise) {
  18423. return true;
  18424. }
  18425. var box0 = this.boundingBox;
  18426. var box1 = boundingInfo.boundingBox;
  18427. if (!axisOverlap(box0.directions[0], box0, box1))
  18428. return false;
  18429. if (!axisOverlap(box0.directions[1], box0, box1))
  18430. return false;
  18431. if (!axisOverlap(box0.directions[2], box0, box1))
  18432. return false;
  18433. if (!axisOverlap(box1.directions[0], box0, box1))
  18434. return false;
  18435. if (!axisOverlap(box1.directions[1], box0, box1))
  18436. return false;
  18437. if (!axisOverlap(box1.directions[2], box0, box1))
  18438. return false;
  18439. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18440. return false;
  18441. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18442. return false;
  18443. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18444. return false;
  18445. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18446. return false;
  18447. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18448. return false;
  18449. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18450. return false;
  18451. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18452. return false;
  18453. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18454. return false;
  18455. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18456. return false;
  18457. return true;
  18458. };
  18459. return BoundingInfo;
  18460. }());
  18461. BABYLON.BoundingInfo = BoundingInfo;
  18462. })(BABYLON || (BABYLON = {}));
  18463. //# sourceMappingURL=babylon.boundingInfo.js.map
  18464. var BABYLON;
  18465. (function (BABYLON) {
  18466. var TransformNode = /** @class */ (function (_super) {
  18467. __extends(TransformNode, _super);
  18468. function TransformNode(name, scene, isPure) {
  18469. if (scene === void 0) { scene = null; }
  18470. if (isPure === void 0) { isPure = true; }
  18471. var _this = _super.call(this, name, scene) || this;
  18472. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18473. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18474. _this._up = new BABYLON.Vector3(0, 1, 0);
  18475. _this._right = new BABYLON.Vector3(1, 0, 0);
  18476. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18477. // Properties
  18478. _this._rotation = BABYLON.Vector3.Zero();
  18479. _this._scaling = BABYLON.Vector3.One();
  18480. _this._isDirty = false;
  18481. /**
  18482. * Set the billboard mode. Default is 0.
  18483. *
  18484. * | Value | Type | Description |
  18485. * | --- | --- | --- |
  18486. * | 0 | BILLBOARDMODE_NONE | |
  18487. * | 1 | BILLBOARDMODE_X | |
  18488. * | 2 | BILLBOARDMODE_Y | |
  18489. * | 4 | BILLBOARDMODE_Z | |
  18490. * | 7 | BILLBOARDMODE_ALL | |
  18491. *
  18492. */
  18493. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18494. _this.scalingDeterminant = 1;
  18495. _this.infiniteDistance = false;
  18496. /**
  18497. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18498. * By default the system will update normals to compensate
  18499. */
  18500. _this.ignoreNonUniformScaling = false;
  18501. _this.position = BABYLON.Vector3.Zero();
  18502. _this._localWorld = BABYLON.Matrix.Zero();
  18503. /** @hidden */
  18504. _this._worldMatrix = BABYLON.Matrix.Zero();
  18505. /** @hidden */
  18506. _this._worldMatrixDeterminant = 0;
  18507. _this._absolutePosition = BABYLON.Vector3.Zero();
  18508. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18509. _this._postMultiplyPivotMatrix = false;
  18510. _this._isWorldMatrixFrozen = false;
  18511. /**
  18512. * An event triggered after the world matrix is updated
  18513. */
  18514. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18515. _this._nonUniformScaling = false;
  18516. if (isPure) {
  18517. _this.getScene().addTransformNode(_this);
  18518. }
  18519. return _this;
  18520. }
  18521. /**
  18522. * Gets a string identifying the name of the class
  18523. * @returns "TransformNode" string
  18524. */
  18525. TransformNode.prototype.getClassName = function () {
  18526. return "TransformNode";
  18527. };
  18528. Object.defineProperty(TransformNode.prototype, "rotation", {
  18529. /**
  18530. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18531. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18532. * Default : (0.0, 0.0, 0.0)
  18533. */
  18534. get: function () {
  18535. return this._rotation;
  18536. },
  18537. set: function (newRotation) {
  18538. this._rotation = newRotation;
  18539. },
  18540. enumerable: true,
  18541. configurable: true
  18542. });
  18543. Object.defineProperty(TransformNode.prototype, "scaling", {
  18544. /**
  18545. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18546. * Default : (1.0, 1.0, 1.0)
  18547. */
  18548. get: function () {
  18549. return this._scaling;
  18550. },
  18551. /**
  18552. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18553. * Default : (1.0, 1.0, 1.0)
  18554. */
  18555. set: function (newScaling) {
  18556. this._scaling = newScaling;
  18557. },
  18558. enumerable: true,
  18559. configurable: true
  18560. });
  18561. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18562. /**
  18563. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18564. * It's null by default.
  18565. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18566. */
  18567. get: function () {
  18568. return this._rotationQuaternion;
  18569. },
  18570. set: function (quaternion) {
  18571. this._rotationQuaternion = quaternion;
  18572. //reset the rotation vector.
  18573. if (quaternion && this.rotation.length()) {
  18574. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18575. }
  18576. },
  18577. enumerable: true,
  18578. configurable: true
  18579. });
  18580. Object.defineProperty(TransformNode.prototype, "forward", {
  18581. /**
  18582. * The forward direction of that transform in world space.
  18583. */
  18584. get: function () {
  18585. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18586. },
  18587. enumerable: true,
  18588. configurable: true
  18589. });
  18590. Object.defineProperty(TransformNode.prototype, "up", {
  18591. /**
  18592. * The up direction of that transform in world space.
  18593. */
  18594. get: function () {
  18595. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18596. },
  18597. enumerable: true,
  18598. configurable: true
  18599. });
  18600. Object.defineProperty(TransformNode.prototype, "right", {
  18601. /**
  18602. * The right direction of that transform in world space.
  18603. */
  18604. get: function () {
  18605. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18606. },
  18607. enumerable: true,
  18608. configurable: true
  18609. });
  18610. /**
  18611. * Returns the latest update of the World matrix
  18612. * Returns a Matrix.
  18613. */
  18614. TransformNode.prototype.getWorldMatrix = function () {
  18615. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18616. this.computeWorldMatrix();
  18617. }
  18618. return this._worldMatrix;
  18619. };
  18620. /** @hidden */
  18621. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18622. return this._worldMatrixDeterminant;
  18623. };
  18624. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18625. /**
  18626. * Returns directly the latest state of the mesh World matrix.
  18627. * A Matrix is returned.
  18628. */
  18629. get: function () {
  18630. return this._worldMatrix;
  18631. },
  18632. enumerable: true,
  18633. configurable: true
  18634. });
  18635. /**
  18636. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18637. * Returns the TransformNode.
  18638. */
  18639. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18640. this._poseMatrix.copyFrom(matrix);
  18641. return this;
  18642. };
  18643. /**
  18644. * Returns the mesh Pose matrix.
  18645. * Returned object : Matrix
  18646. */
  18647. TransformNode.prototype.getPoseMatrix = function () {
  18648. return this._poseMatrix;
  18649. };
  18650. /** @hidden */
  18651. TransformNode.prototype._isSynchronized = function () {
  18652. if (this._isDirty) {
  18653. return false;
  18654. }
  18655. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18656. return false;
  18657. if (this._cache.pivotMatrixUpdated) {
  18658. return false;
  18659. }
  18660. if (this.infiniteDistance) {
  18661. return false;
  18662. }
  18663. if (!this._cache.position.equals(this.position))
  18664. return false;
  18665. if (this._rotationQuaternion) {
  18666. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18667. return false;
  18668. }
  18669. if (!this._cache.rotation.equals(this.rotation))
  18670. return false;
  18671. if (!this._cache.scaling.equals(this.scaling))
  18672. return false;
  18673. return true;
  18674. };
  18675. /** @hidden */
  18676. TransformNode.prototype._initCache = function () {
  18677. _super.prototype._initCache.call(this);
  18678. this._cache.localMatrixUpdated = false;
  18679. this._cache.position = BABYLON.Vector3.Zero();
  18680. this._cache.scaling = BABYLON.Vector3.Zero();
  18681. this._cache.rotation = BABYLON.Vector3.Zero();
  18682. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18683. this._cache.billboardMode = -1;
  18684. };
  18685. TransformNode.prototype.markAsDirty = function (property) {
  18686. if (property === "rotation") {
  18687. this.rotationQuaternion = null;
  18688. }
  18689. this._currentRenderId = Number.MAX_VALUE;
  18690. this._isDirty = true;
  18691. return this;
  18692. };
  18693. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18694. /**
  18695. * Returns the current mesh absolute position.
  18696. * Returns a Vector3.
  18697. */
  18698. get: function () {
  18699. return this._absolutePosition;
  18700. },
  18701. enumerable: true,
  18702. configurable: true
  18703. });
  18704. /**
  18705. * Sets a new matrix to apply before all other transformation
  18706. * @param matrix defines the transform matrix
  18707. * @returns the current TransformNode
  18708. */
  18709. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18710. return this.setPivotMatrix(matrix, false);
  18711. };
  18712. /**
  18713. * Sets a new pivot matrix to the current node
  18714. * @param matrix defines the new pivot matrix to use
  18715. * @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
  18716. * @returns the current TransformNode
  18717. */
  18718. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18719. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18720. this._pivotMatrix = matrix.clone();
  18721. this._cache.pivotMatrixUpdated = true;
  18722. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18723. if (this._postMultiplyPivotMatrix) {
  18724. if (!this._pivotMatrixInverse) {
  18725. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18726. }
  18727. else {
  18728. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18729. }
  18730. }
  18731. return this;
  18732. };
  18733. /**
  18734. * Returns the mesh pivot matrix.
  18735. * Default : Identity.
  18736. * A Matrix is returned.
  18737. */
  18738. TransformNode.prototype.getPivotMatrix = function () {
  18739. return this._pivotMatrix;
  18740. };
  18741. /**
  18742. * Prevents the World matrix to be computed any longer.
  18743. * Returns the TransformNode.
  18744. */
  18745. TransformNode.prototype.freezeWorldMatrix = function () {
  18746. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18747. this.computeWorldMatrix(true);
  18748. this._isWorldMatrixFrozen = true;
  18749. return this;
  18750. };
  18751. /**
  18752. * Allows back the World matrix computation.
  18753. * Returns the TransformNode.
  18754. */
  18755. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18756. this._isWorldMatrixFrozen = false;
  18757. this.computeWorldMatrix(true);
  18758. return this;
  18759. };
  18760. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18761. /**
  18762. * True if the World matrix has been frozen.
  18763. * Returns a boolean.
  18764. */
  18765. get: function () {
  18766. return this._isWorldMatrixFrozen;
  18767. },
  18768. enumerable: true,
  18769. configurable: true
  18770. });
  18771. /**
  18772. * Retuns the mesh absolute position in the World.
  18773. * Returns a Vector3.
  18774. */
  18775. TransformNode.prototype.getAbsolutePosition = function () {
  18776. this.computeWorldMatrix();
  18777. return this._absolutePosition;
  18778. };
  18779. /**
  18780. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18781. * Returns the TransformNode.
  18782. */
  18783. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18784. if (!absolutePosition) {
  18785. return this;
  18786. }
  18787. var absolutePositionX;
  18788. var absolutePositionY;
  18789. var absolutePositionZ;
  18790. if (absolutePosition.x === undefined) {
  18791. if (arguments.length < 3) {
  18792. return this;
  18793. }
  18794. absolutePositionX = arguments[0];
  18795. absolutePositionY = arguments[1];
  18796. absolutePositionZ = arguments[2];
  18797. }
  18798. else {
  18799. absolutePositionX = absolutePosition.x;
  18800. absolutePositionY = absolutePosition.y;
  18801. absolutePositionZ = absolutePosition.z;
  18802. }
  18803. if (this.parent) {
  18804. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18805. invertParentWorldMatrix.invert();
  18806. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18807. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18808. }
  18809. else {
  18810. this.position.x = absolutePositionX;
  18811. this.position.y = absolutePositionY;
  18812. this.position.z = absolutePositionZ;
  18813. }
  18814. return this;
  18815. };
  18816. /**
  18817. * Sets the mesh position in its local space.
  18818. * Returns the TransformNode.
  18819. */
  18820. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18821. this.computeWorldMatrix();
  18822. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18823. return this;
  18824. };
  18825. /**
  18826. * Returns the mesh position in the local space from the current World matrix values.
  18827. * Returns a new Vector3.
  18828. */
  18829. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18830. this.computeWorldMatrix();
  18831. var invLocalWorldMatrix = this._localWorld.clone();
  18832. invLocalWorldMatrix.invert();
  18833. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18834. };
  18835. /**
  18836. * Translates the mesh along the passed Vector3 in its local space.
  18837. * Returns the TransformNode.
  18838. */
  18839. TransformNode.prototype.locallyTranslate = function (vector3) {
  18840. this.computeWorldMatrix(true);
  18841. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18842. return this;
  18843. };
  18844. /**
  18845. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18846. * @param targetPoint the position (must be in same space as current mesh) to look at
  18847. * @param yawCor optional yaw (y-axis) correction in radians
  18848. * @param pitchCor optional pitch (x-axis) correction in radians
  18849. * @param rollCor optional roll (z-axis) correction in radians
  18850. * @param space the choosen space of the target
  18851. * @returns the TransformNode.
  18852. */
  18853. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18854. if (yawCor === void 0) { yawCor = 0; }
  18855. if (pitchCor === void 0) { pitchCor = 0; }
  18856. if (rollCor === void 0) { rollCor = 0; }
  18857. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18858. var dv = TransformNode._lookAtVectorCache;
  18859. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18860. targetPoint.subtractToRef(pos, dv);
  18861. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18862. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18863. var pitch = Math.atan2(dv.y, len);
  18864. if (this.rotationQuaternion) {
  18865. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18866. }
  18867. else {
  18868. this.rotation.x = pitch + pitchCor;
  18869. this.rotation.y = yaw + yawCor;
  18870. this.rotation.z = rollCor;
  18871. }
  18872. return this;
  18873. };
  18874. /**
  18875. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18876. * This Vector3 is expressed in the World space.
  18877. */
  18878. TransformNode.prototype.getDirection = function (localAxis) {
  18879. var result = BABYLON.Vector3.Zero();
  18880. this.getDirectionToRef(localAxis, result);
  18881. return result;
  18882. };
  18883. /**
  18884. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18885. * localAxis is expressed in the mesh local space.
  18886. * result is computed in the Wordl space from the mesh World matrix.
  18887. * Returns the TransformNode.
  18888. */
  18889. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18890. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18891. return this;
  18892. };
  18893. /**
  18894. * Sets a new pivot point to the current node
  18895. * @param point defines the new pivot point to use
  18896. * @param space defines if the point is in world or local space (local by default)
  18897. * @returns the current TransformNode
  18898. */
  18899. TransformNode.prototype.setPivotPoint = function (point, space) {
  18900. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18901. if (this.getScene().getRenderId() == 0) {
  18902. this.computeWorldMatrix(true);
  18903. }
  18904. var wm = this.getWorldMatrix();
  18905. if (space == BABYLON.Space.WORLD) {
  18906. var tmat = BABYLON.Tmp.Matrix[0];
  18907. wm.invertToRef(tmat);
  18908. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18909. }
  18910. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18911. };
  18912. /**
  18913. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18914. */
  18915. TransformNode.prototype.getPivotPoint = function () {
  18916. var point = BABYLON.Vector3.Zero();
  18917. this.getPivotPointToRef(point);
  18918. return point;
  18919. };
  18920. /**
  18921. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18922. * Returns the TransformNode.
  18923. */
  18924. TransformNode.prototype.getPivotPointToRef = function (result) {
  18925. result.x = -this._pivotMatrix.m[12];
  18926. result.y = -this._pivotMatrix.m[13];
  18927. result.z = -this._pivotMatrix.m[14];
  18928. return this;
  18929. };
  18930. /**
  18931. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18932. */
  18933. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18934. var point = BABYLON.Vector3.Zero();
  18935. this.getAbsolutePivotPointToRef(point);
  18936. return point;
  18937. };
  18938. /**
  18939. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18940. * Returns the TransformNode.
  18941. */
  18942. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18943. result.x = this._pivotMatrix.m[12];
  18944. result.y = this._pivotMatrix.m[13];
  18945. result.z = this._pivotMatrix.m[14];
  18946. this.getPivotPointToRef(result);
  18947. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18948. return this;
  18949. };
  18950. /**
  18951. * Defines the passed node as the parent of the current node.
  18952. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18953. * Returns the TransformNode.
  18954. */
  18955. TransformNode.prototype.setParent = function (node) {
  18956. if (!node && !this.parent) {
  18957. return this;
  18958. }
  18959. if (!node) {
  18960. var rotation = BABYLON.Tmp.Quaternion[0];
  18961. var position = BABYLON.Tmp.Vector3[0];
  18962. var scale = BABYLON.Tmp.Vector3[1];
  18963. if (this.parent && this.parent.computeWorldMatrix) {
  18964. this.parent.computeWorldMatrix(true);
  18965. }
  18966. this.computeWorldMatrix(true);
  18967. this.getWorldMatrix().decompose(scale, rotation, position);
  18968. if (this.rotationQuaternion) {
  18969. this.rotationQuaternion.copyFrom(rotation);
  18970. }
  18971. else {
  18972. rotation.toEulerAnglesToRef(this.rotation);
  18973. }
  18974. this.scaling.x = scale.x;
  18975. this.scaling.y = scale.y;
  18976. this.scaling.z = scale.z;
  18977. this.position.x = position.x;
  18978. this.position.y = position.y;
  18979. this.position.z = position.z;
  18980. }
  18981. else {
  18982. var rotation = BABYLON.Tmp.Quaternion[0];
  18983. var position = BABYLON.Tmp.Vector3[0];
  18984. var scale = BABYLON.Tmp.Vector3[1];
  18985. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18986. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18987. this.computeWorldMatrix(true);
  18988. node.computeWorldMatrix(true);
  18989. node.getWorldMatrix().invertToRef(invParentMatrix);
  18990. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18991. diffMatrix.decompose(scale, rotation, position);
  18992. if (this.rotationQuaternion) {
  18993. this.rotationQuaternion.copyFrom(rotation);
  18994. }
  18995. else {
  18996. rotation.toEulerAnglesToRef(this.rotation);
  18997. }
  18998. this.position.x = position.x;
  18999. this.position.y = position.y;
  19000. this.position.z = position.z;
  19001. this.scaling.x = scale.x;
  19002. this.scaling.y = scale.y;
  19003. this.scaling.z = scale.z;
  19004. }
  19005. this.parent = node;
  19006. return this;
  19007. };
  19008. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19009. get: function () {
  19010. return this._nonUniformScaling;
  19011. },
  19012. enumerable: true,
  19013. configurable: true
  19014. });
  19015. /** @hidden */
  19016. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19017. if (this._nonUniformScaling === value) {
  19018. return false;
  19019. }
  19020. this._nonUniformScaling = value;
  19021. return true;
  19022. };
  19023. /**
  19024. * Attach the current TransformNode to another TransformNode associated with a bone
  19025. * @param bone Bone affecting the TransformNode
  19026. * @param affectedTransformNode TransformNode associated with the bone
  19027. */
  19028. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19029. this._transformToBoneReferal = affectedTransformNode;
  19030. this.parent = bone;
  19031. if (bone.getWorldMatrix().determinant() < 0) {
  19032. this.scalingDeterminant *= -1;
  19033. }
  19034. return this;
  19035. };
  19036. TransformNode.prototype.detachFromBone = function () {
  19037. if (!this.parent) {
  19038. return this;
  19039. }
  19040. if (this.parent.getWorldMatrix().determinant() < 0) {
  19041. this.scalingDeterminant *= -1;
  19042. }
  19043. this._transformToBoneReferal = null;
  19044. this.parent = null;
  19045. return this;
  19046. };
  19047. /**
  19048. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19049. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19050. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19051. * The passed axis is also normalized.
  19052. * Returns the TransformNode.
  19053. */
  19054. TransformNode.prototype.rotate = function (axis, amount, space) {
  19055. axis.normalize();
  19056. if (!this.rotationQuaternion) {
  19057. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19058. this.rotation = BABYLON.Vector3.Zero();
  19059. }
  19060. var rotationQuaternion;
  19061. if (!space || space === BABYLON.Space.LOCAL) {
  19062. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19063. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19064. }
  19065. else {
  19066. if (this.parent) {
  19067. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19068. invertParentWorldMatrix.invert();
  19069. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19070. }
  19071. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19072. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19073. }
  19074. return this;
  19075. };
  19076. /**
  19077. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19078. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19079. * The passed axis is also normalized.
  19080. * Returns the TransformNode.
  19081. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19082. */
  19083. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19084. axis.normalize();
  19085. if (!this.rotationQuaternion) {
  19086. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19087. this.rotation.copyFromFloats(0, 0, 0);
  19088. }
  19089. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19090. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19091. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19092. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19093. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19094. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19095. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19096. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19097. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19098. return this;
  19099. };
  19100. /**
  19101. * Translates the mesh along the axis vector for the passed distance in the given space.
  19102. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19103. * Returns the TransformNode.
  19104. */
  19105. TransformNode.prototype.translate = function (axis, distance, space) {
  19106. var displacementVector = axis.scale(distance);
  19107. if (!space || space === BABYLON.Space.LOCAL) {
  19108. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19109. this.setPositionWithLocalVector(tempV3);
  19110. }
  19111. else {
  19112. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19113. }
  19114. return this;
  19115. };
  19116. /**
  19117. * Adds a rotation step to the mesh current rotation.
  19118. * x, y, z are Euler angles expressed in radians.
  19119. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19120. * This means this rotation is made in the mesh local space only.
  19121. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19122. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19123. * ```javascript
  19124. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19125. * ```
  19126. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19127. * 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.
  19128. * Returns the TransformNode.
  19129. */
  19130. TransformNode.prototype.addRotation = function (x, y, z) {
  19131. var rotationQuaternion;
  19132. if (this.rotationQuaternion) {
  19133. rotationQuaternion = this.rotationQuaternion;
  19134. }
  19135. else {
  19136. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19137. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19138. }
  19139. var accumulation = BABYLON.Tmp.Quaternion[0];
  19140. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19141. rotationQuaternion.multiplyInPlace(accumulation);
  19142. if (!this.rotationQuaternion) {
  19143. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19144. }
  19145. return this;
  19146. };
  19147. /**
  19148. * Computes the mesh World matrix and returns it.
  19149. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19150. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19151. * If the parameter `force`is set to `true`, the actual computation is done.
  19152. * Returns the mesh World Matrix.
  19153. */
  19154. TransformNode.prototype.computeWorldMatrix = function (force) {
  19155. if (this._isWorldMatrixFrozen) {
  19156. return this._worldMatrix;
  19157. }
  19158. if (!force && this.isSynchronized(true)) {
  19159. this._currentRenderId = this.getScene().getRenderId();
  19160. return this._worldMatrix;
  19161. }
  19162. this._cache.position.copyFrom(this.position);
  19163. this._cache.scaling.copyFrom(this.scaling);
  19164. this._cache.pivotMatrixUpdated = false;
  19165. this._cache.billboardMode = this.billboardMode;
  19166. this._currentRenderId = this.getScene().getRenderId();
  19167. this._childRenderId = this.getScene().getRenderId();
  19168. this._isDirty = false;
  19169. // Scaling
  19170. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19171. // Rotation
  19172. //rotate, if quaternion is set and rotation was used
  19173. if (this.rotationQuaternion) {
  19174. var len = this.rotation.length();
  19175. if (len) {
  19176. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19177. this.rotation.copyFromFloats(0, 0, 0);
  19178. }
  19179. }
  19180. if (this.rotationQuaternion) {
  19181. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19182. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19183. }
  19184. else {
  19185. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19186. this._cache.rotation.copyFrom(this.rotation);
  19187. }
  19188. // Translation
  19189. var camera = this.getScene().activeCamera;
  19190. if (this.infiniteDistance && !this.parent && camera) {
  19191. var cameraWorldMatrix = camera.getWorldMatrix();
  19192. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19193. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19194. }
  19195. else {
  19196. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19197. }
  19198. // Composing transformations
  19199. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19200. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19201. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19202. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19203. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19204. // Need to decompose each rotation here
  19205. var currentPosition = BABYLON.Tmp.Vector3[3];
  19206. if (this.parent && this.parent.getWorldMatrix) {
  19207. if (this._transformToBoneReferal) {
  19208. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19209. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19210. }
  19211. else {
  19212. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19213. }
  19214. }
  19215. else {
  19216. currentPosition.copyFrom(this.position);
  19217. }
  19218. currentPosition.subtractInPlace(camera.globalPosition);
  19219. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19220. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19221. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19222. }
  19223. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19224. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19225. }
  19226. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19227. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19228. }
  19229. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19230. }
  19231. else {
  19232. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19233. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19234. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19235. }
  19236. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19237. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19238. }
  19239. // Post multiply inverse of pivotMatrix
  19240. if (this._postMultiplyPivotMatrix) {
  19241. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19242. }
  19243. // Local world
  19244. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19245. // Parent
  19246. if (this.parent && this.parent.getWorldMatrix) {
  19247. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19248. if (this._transformToBoneReferal) {
  19249. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19250. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19251. }
  19252. else {
  19253. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19254. }
  19255. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19256. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19257. this._worldMatrix.copyFrom(this._localWorld);
  19258. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19259. }
  19260. else {
  19261. if (this._transformToBoneReferal) {
  19262. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19263. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19264. }
  19265. else {
  19266. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19267. }
  19268. }
  19269. this._markSyncedWithParent();
  19270. }
  19271. else {
  19272. this._worldMatrix.copyFrom(this._localWorld);
  19273. }
  19274. // Normal matrix
  19275. if (!this.ignoreNonUniformScaling) {
  19276. if (this.scaling.isNonUniform) {
  19277. this._updateNonUniformScalingState(true);
  19278. }
  19279. else if (this.parent && this.parent._nonUniformScaling) {
  19280. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19281. }
  19282. else {
  19283. this._updateNonUniformScalingState(false);
  19284. }
  19285. }
  19286. else {
  19287. this._updateNonUniformScalingState(false);
  19288. }
  19289. this._afterComputeWorldMatrix();
  19290. // Absolute position
  19291. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19292. // Callbacks
  19293. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19294. if (!this._poseMatrix) {
  19295. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19296. }
  19297. // Cache the determinant
  19298. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19299. return this._worldMatrix;
  19300. };
  19301. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19302. };
  19303. /**
  19304. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19305. * @param func: callback function to add
  19306. *
  19307. * Returns the TransformNode.
  19308. */
  19309. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19310. this.onAfterWorldMatrixUpdateObservable.add(func);
  19311. return this;
  19312. };
  19313. /**
  19314. * Removes a registered callback function.
  19315. * Returns the TransformNode.
  19316. */
  19317. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19318. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19319. return this;
  19320. };
  19321. /**
  19322. * Clone the current transform node
  19323. * Returns the new transform node
  19324. * @param name Name of the new clone
  19325. * @param newParent New parent for the clone
  19326. * @param doNotCloneChildren Do not clone children hierarchy
  19327. */
  19328. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19329. var _this = this;
  19330. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19331. result.name = name;
  19332. result.id = name;
  19333. if (newParent) {
  19334. result.parent = newParent;
  19335. }
  19336. if (!doNotCloneChildren) {
  19337. // Children
  19338. var directDescendants = this.getDescendants(true);
  19339. for (var index = 0; index < directDescendants.length; index++) {
  19340. var child = directDescendants[index];
  19341. if (child.clone) {
  19342. child.clone(name + "." + child.name, result);
  19343. }
  19344. }
  19345. }
  19346. return result;
  19347. };
  19348. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19349. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19350. serializationObject.type = this.getClassName();
  19351. // Parent
  19352. if (this.parent) {
  19353. serializationObject.parentId = this.parent.id;
  19354. }
  19355. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19356. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19357. }
  19358. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19359. serializationObject.isEnabled = this.isEnabled();
  19360. // Parent
  19361. if (this.parent) {
  19362. serializationObject.parentId = this.parent.id;
  19363. }
  19364. return serializationObject;
  19365. };
  19366. // Statics
  19367. /**
  19368. * Returns a new TransformNode object parsed from the source provided.
  19369. * The parameter `parsedMesh` is the source.
  19370. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19371. */
  19372. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19373. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19374. if (BABYLON.Tags) {
  19375. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19376. }
  19377. if (parsedTransformNode.localMatrix) {
  19378. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19379. }
  19380. else if (parsedTransformNode.pivotMatrix) {
  19381. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19382. }
  19383. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19384. // Parent
  19385. if (parsedTransformNode.parentId) {
  19386. transformNode._waitingParentId = parsedTransformNode.parentId;
  19387. }
  19388. return transformNode;
  19389. };
  19390. /**
  19391. * Releases resources associated with this transform node.
  19392. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19393. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19394. */
  19395. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19396. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19397. // Animations
  19398. this.getScene().stopAnimation(this);
  19399. // Remove from scene
  19400. this.getScene().removeTransformNode(this);
  19401. this.onAfterWorldMatrixUpdateObservable.clear();
  19402. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19403. };
  19404. // Statics
  19405. TransformNode.BILLBOARDMODE_NONE = 0;
  19406. TransformNode.BILLBOARDMODE_X = 1;
  19407. TransformNode.BILLBOARDMODE_Y = 2;
  19408. TransformNode.BILLBOARDMODE_Z = 4;
  19409. TransformNode.BILLBOARDMODE_ALL = 7;
  19410. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19411. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19412. __decorate([
  19413. BABYLON.serializeAsVector3()
  19414. ], TransformNode.prototype, "_rotation", void 0);
  19415. __decorate([
  19416. BABYLON.serializeAsQuaternion()
  19417. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19418. __decorate([
  19419. BABYLON.serializeAsVector3()
  19420. ], TransformNode.prototype, "_scaling", void 0);
  19421. __decorate([
  19422. BABYLON.serialize()
  19423. ], TransformNode.prototype, "billboardMode", void 0);
  19424. __decorate([
  19425. BABYLON.serialize()
  19426. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19427. __decorate([
  19428. BABYLON.serialize()
  19429. ], TransformNode.prototype, "infiniteDistance", void 0);
  19430. __decorate([
  19431. BABYLON.serialize()
  19432. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19433. __decorate([
  19434. BABYLON.serializeAsVector3()
  19435. ], TransformNode.prototype, "position", void 0);
  19436. return TransformNode;
  19437. }(BABYLON.Node));
  19438. BABYLON.TransformNode = TransformNode;
  19439. })(BABYLON || (BABYLON = {}));
  19440. //# sourceMappingURL=babylon.transformNode.js.map
  19441. var BABYLON;
  19442. (function (BABYLON) {
  19443. /**
  19444. * Class used to store all common mesh properties
  19445. */
  19446. var AbstractMesh = /** @class */ (function (_super) {
  19447. __extends(AbstractMesh, _super);
  19448. // Constructor
  19449. /**
  19450. * Creates a new AbstractMesh
  19451. * @param name defines the name of the mesh
  19452. * @param scene defines the hosting scene
  19453. */
  19454. function AbstractMesh(name, scene) {
  19455. if (scene === void 0) { scene = null; }
  19456. var _this = _super.call(this, name, scene, false) || this;
  19457. _this._facetNb = 0; // facet number
  19458. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19459. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19460. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19461. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19462. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19463. _this._subDiv = {
  19464. max: 1,
  19465. X: 1,
  19466. Y: 1,
  19467. Z: 1
  19468. };
  19469. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19470. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19471. /** Gets ot sets the culling strategy to use to find visible meshes */
  19472. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19473. // Events
  19474. /**
  19475. * An event triggered when this mesh collides with another one
  19476. */
  19477. _this.onCollideObservable = new BABYLON.Observable();
  19478. /**
  19479. * An event triggered when the collision's position changes
  19480. */
  19481. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19482. /**
  19483. * An event triggered when material is changed
  19484. */
  19485. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19486. // Properties
  19487. /**
  19488. * Gets or sets the orientation for POV movement & rotation
  19489. */
  19490. _this.definedFacingForward = true;
  19491. /**
  19492. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19493. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19494. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19495. * @see http://doc.babylonjs.com/features/occlusionquery
  19496. */
  19497. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19498. /**
  19499. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19500. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19501. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19502. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19503. * @see http://doc.babylonjs.com/features/occlusionquery
  19504. */
  19505. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19506. /**
  19507. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19508. * The default value is -1 which means don't break the query and wait till the result
  19509. * @see http://doc.babylonjs.com/features/occlusionquery
  19510. */
  19511. _this.occlusionRetryCount = -1;
  19512. /** @hidden */
  19513. _this._occlusionInternalRetryCounter = 0;
  19514. /** @hidden */
  19515. _this._isOccluded = false;
  19516. /** @hidden */
  19517. _this._isOcclusionQueryInProgress = false;
  19518. _this._visibility = 1.0;
  19519. /** Gets or sets the alpha index used to sort transparent meshes
  19520. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19521. */
  19522. _this.alphaIndex = Number.MAX_VALUE;
  19523. /**
  19524. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19525. */
  19526. _this.isVisible = true;
  19527. /**
  19528. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19529. */
  19530. _this.isPickable = true;
  19531. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19532. _this.showSubMeshesBoundingBox = false;
  19533. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19534. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19535. */
  19536. _this.isBlocker = false;
  19537. /**
  19538. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19539. */
  19540. _this.enablePointerMoveEvents = false;
  19541. /**
  19542. * Specifies the rendering group id for this mesh (0 by default)
  19543. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19544. */
  19545. _this.renderingGroupId = 0;
  19546. _this._receiveShadows = false;
  19547. /**
  19548. * Gets or sets a boolean indicating if the outline must be rendered as well
  19549. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19550. */
  19551. _this.renderOutline = false;
  19552. /** Defines color to use when rendering outline */
  19553. _this.outlineColor = BABYLON.Color3.Red();
  19554. /** Define width to use when rendering outline */
  19555. _this.outlineWidth = 0.02;
  19556. /**
  19557. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19558. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19559. */
  19560. _this.renderOverlay = false;
  19561. /** Defines color to use when rendering overlay */
  19562. _this.overlayColor = BABYLON.Color3.Red();
  19563. /** Defines alpha to use when rendering overlay */
  19564. _this.overlayAlpha = 0.5;
  19565. _this._hasVertexAlpha = false;
  19566. _this._useVertexColors = true;
  19567. _this._computeBonesUsingShaders = true;
  19568. _this._numBoneInfluencers = 4;
  19569. _this._applyFog = true;
  19570. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19571. _this.useOctreeForRenderingSelection = true;
  19572. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19573. _this.useOctreeForPicking = true;
  19574. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19575. _this.useOctreeForCollisions = true;
  19576. _this._layerMask = 0x0FFFFFFF;
  19577. /**
  19578. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19579. */
  19580. _this.alwaysSelectAsActiveMesh = false;
  19581. /**
  19582. * Gets or sets the current action manager
  19583. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19584. */
  19585. _this.actionManager = null;
  19586. /**
  19587. * Gets or sets impostor used for physic simulation
  19588. * @see http://doc.babylonjs.com/features/physics_engine
  19589. */
  19590. _this.physicsImpostor = null;
  19591. // Collisions
  19592. _this._checkCollisions = false;
  19593. _this._collisionMask = -1;
  19594. _this._collisionGroup = -1;
  19595. /**
  19596. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19597. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19598. */
  19599. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19600. /**
  19601. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19602. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19603. */
  19604. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19605. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19606. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19607. // Edges
  19608. /**
  19609. * Defines edge width used when edgesRenderer is enabled
  19610. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19611. */
  19612. _this.edgesWidth = 1;
  19613. /**
  19614. * Defines edge color used when edgesRenderer is enabled
  19615. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19616. */
  19617. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19618. // Cache
  19619. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19620. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19621. /** @hidden */
  19622. _this._renderId = 0;
  19623. /** @hidden */
  19624. _this._intersectionsInProgress = new Array();
  19625. /** @hidden */
  19626. _this._unIndexed = false;
  19627. /** @hidden */
  19628. _this._lightSources = new Array();
  19629. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19630. if (collidedMesh === void 0) { collidedMesh = null; }
  19631. //TODO move this to the collision coordinator!
  19632. if (_this.getScene().workerCollisions)
  19633. newPosition.multiplyInPlace(_this._collider._radius);
  19634. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19635. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19636. _this.position.addInPlace(_this._diffPositionForCollisions);
  19637. }
  19638. if (collidedMesh) {
  19639. _this.onCollideObservable.notifyObservers(collidedMesh);
  19640. }
  19641. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19642. };
  19643. _this.getScene().addMesh(_this);
  19644. _this._resyncLightSources();
  19645. return _this;
  19646. }
  19647. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19648. /**
  19649. * No billboard
  19650. */
  19651. get: function () {
  19652. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19653. },
  19654. enumerable: true,
  19655. configurable: true
  19656. });
  19657. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19658. /** Billboard on X axis */
  19659. get: function () {
  19660. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19661. },
  19662. enumerable: true,
  19663. configurable: true
  19664. });
  19665. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19666. /** Billboard on Y axis */
  19667. get: function () {
  19668. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19669. },
  19670. enumerable: true,
  19671. configurable: true
  19672. });
  19673. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19674. /** Billboard on Z axis */
  19675. get: function () {
  19676. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19677. },
  19678. enumerable: true,
  19679. configurable: true
  19680. });
  19681. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19682. /** Billboard on all axes */
  19683. get: function () {
  19684. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19685. },
  19686. enumerable: true,
  19687. configurable: true
  19688. });
  19689. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19690. /**
  19691. * Gets the number of facets in the mesh
  19692. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19693. */
  19694. get: function () {
  19695. return this._facetNb;
  19696. },
  19697. enumerable: true,
  19698. configurable: true
  19699. });
  19700. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19701. /**
  19702. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19703. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19704. */
  19705. get: function () {
  19706. return this._partitioningSubdivisions;
  19707. },
  19708. set: function (nb) {
  19709. this._partitioningSubdivisions = nb;
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19715. /**
  19716. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19717. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19718. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19719. */
  19720. get: function () {
  19721. return this._partitioningBBoxRatio;
  19722. },
  19723. set: function (ratio) {
  19724. this._partitioningBBoxRatio = ratio;
  19725. },
  19726. enumerable: true,
  19727. configurable: true
  19728. });
  19729. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19730. /**
  19731. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19732. * Works only for updatable meshes.
  19733. * Doesn't work with multi-materials
  19734. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19735. */
  19736. get: function () {
  19737. return this._facetDepthSort;
  19738. },
  19739. set: function (sort) {
  19740. this._facetDepthSort = sort;
  19741. },
  19742. enumerable: true,
  19743. configurable: true
  19744. });
  19745. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19746. /**
  19747. * The location (Vector3) where the facet depth sort must be computed from.
  19748. * By default, the active camera position.
  19749. * Used only when facet depth sort is enabled
  19750. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19751. */
  19752. get: function () {
  19753. return this._facetDepthSortFrom;
  19754. },
  19755. set: function (location) {
  19756. this._facetDepthSortFrom = location;
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19762. /**
  19763. * gets a boolean indicating if facetData is enabled
  19764. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19765. */
  19766. get: function () {
  19767. return this._facetDataEnabled;
  19768. },
  19769. enumerable: true,
  19770. configurable: true
  19771. });
  19772. /** @hidden */
  19773. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19774. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19775. return false;
  19776. }
  19777. this._markSubMeshesAsMiscDirty();
  19778. return true;
  19779. };
  19780. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19781. /** Set a function to call when this mesh collides with another one */
  19782. set: function (callback) {
  19783. if (this._onCollideObserver) {
  19784. this.onCollideObservable.remove(this._onCollideObserver);
  19785. }
  19786. this._onCollideObserver = this.onCollideObservable.add(callback);
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19792. /** Set a function to call when the collision's position changes */
  19793. set: function (callback) {
  19794. if (this._onCollisionPositionChangeObserver) {
  19795. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19796. }
  19797. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19798. },
  19799. enumerable: true,
  19800. configurable: true
  19801. });
  19802. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19803. /**
  19804. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19805. * @see http://doc.babylonjs.com/features/occlusionquery
  19806. */
  19807. get: function () {
  19808. return this._isOccluded;
  19809. },
  19810. set: function (value) {
  19811. this._isOccluded = value;
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19817. /**
  19818. * Flag to check the progress status of the query
  19819. * @see http://doc.babylonjs.com/features/occlusionquery
  19820. */
  19821. get: function () {
  19822. return this._isOcclusionQueryInProgress;
  19823. },
  19824. enumerable: true,
  19825. configurable: true
  19826. });
  19827. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19828. /**
  19829. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19830. */
  19831. get: function () {
  19832. return this._visibility;
  19833. },
  19834. /**
  19835. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19836. */
  19837. set: function (value) {
  19838. if (this._visibility === value) {
  19839. return;
  19840. }
  19841. this._visibility = value;
  19842. this._markSubMeshesAsMiscDirty();
  19843. },
  19844. enumerable: true,
  19845. configurable: true
  19846. });
  19847. Object.defineProperty(AbstractMesh.prototype, "material", {
  19848. /** Gets or sets current material */
  19849. get: function () {
  19850. return this._material;
  19851. },
  19852. set: function (value) {
  19853. if (this._material === value) {
  19854. return;
  19855. }
  19856. this._material = value;
  19857. if (this.onMaterialChangedObservable.hasObservers) {
  19858. this.onMaterialChangedObservable.notifyObservers(this);
  19859. }
  19860. if (!this.subMeshes) {
  19861. return;
  19862. }
  19863. this._unBindEffect();
  19864. },
  19865. enumerable: true,
  19866. configurable: true
  19867. });
  19868. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19869. /**
  19870. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19871. * @see http://doc.babylonjs.com/babylon101/shadows
  19872. */
  19873. get: function () {
  19874. return this._receiveShadows;
  19875. },
  19876. set: function (value) {
  19877. if (this._receiveShadows === value) {
  19878. return;
  19879. }
  19880. this._receiveShadows = value;
  19881. this._markSubMeshesAsLightDirty();
  19882. },
  19883. enumerable: true,
  19884. configurable: true
  19885. });
  19886. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19887. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19888. get: function () {
  19889. return this._hasVertexAlpha;
  19890. },
  19891. set: function (value) {
  19892. if (this._hasVertexAlpha === value) {
  19893. return;
  19894. }
  19895. this._hasVertexAlpha = value;
  19896. this._markSubMeshesAsAttributesDirty();
  19897. this._markSubMeshesAsMiscDirty();
  19898. },
  19899. enumerable: true,
  19900. configurable: true
  19901. });
  19902. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19903. /** 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) */
  19904. get: function () {
  19905. return this._useVertexColors;
  19906. },
  19907. set: function (value) {
  19908. if (this._useVertexColors === value) {
  19909. return;
  19910. }
  19911. this._useVertexColors = value;
  19912. this._markSubMeshesAsAttributesDirty();
  19913. },
  19914. enumerable: true,
  19915. configurable: true
  19916. });
  19917. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19918. /**
  19919. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19920. */
  19921. get: function () {
  19922. return this._computeBonesUsingShaders;
  19923. },
  19924. set: function (value) {
  19925. if (this._computeBonesUsingShaders === value) {
  19926. return;
  19927. }
  19928. this._computeBonesUsingShaders = value;
  19929. this._markSubMeshesAsAttributesDirty();
  19930. },
  19931. enumerable: true,
  19932. configurable: true
  19933. });
  19934. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19935. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19936. get: function () {
  19937. return this._numBoneInfluencers;
  19938. },
  19939. set: function (value) {
  19940. if (this._numBoneInfluencers === value) {
  19941. return;
  19942. }
  19943. this._numBoneInfluencers = value;
  19944. this._markSubMeshesAsAttributesDirty();
  19945. },
  19946. enumerable: true,
  19947. configurable: true
  19948. });
  19949. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19950. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19951. get: function () {
  19952. return this._applyFog;
  19953. },
  19954. set: function (value) {
  19955. if (this._applyFog === value) {
  19956. return;
  19957. }
  19958. this._applyFog = value;
  19959. this._markSubMeshesAsMiscDirty();
  19960. },
  19961. enumerable: true,
  19962. configurable: true
  19963. });
  19964. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19965. /**
  19966. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19967. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19968. */
  19969. get: function () {
  19970. return this._layerMask;
  19971. },
  19972. set: function (value) {
  19973. if (value === this._layerMask) {
  19974. return;
  19975. }
  19976. this._layerMask = value;
  19977. this._resyncLightSources();
  19978. },
  19979. enumerable: true,
  19980. configurable: true
  19981. });
  19982. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19983. /**
  19984. * Gets or sets a collision mask used to mask collisions (default is -1).
  19985. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19986. */
  19987. get: function () {
  19988. return this._collisionMask;
  19989. },
  19990. set: function (mask) {
  19991. this._collisionMask = !isNaN(mask) ? mask : -1;
  19992. },
  19993. enumerable: true,
  19994. configurable: true
  19995. });
  19996. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19997. /**
  19998. * Gets or sets the current collision group mask (-1 by default).
  19999. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20000. */
  20001. get: function () {
  20002. return this._collisionGroup;
  20003. },
  20004. set: function (mask) {
  20005. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20006. },
  20007. enumerable: true,
  20008. configurable: true
  20009. });
  20010. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20011. /** @hidden */
  20012. get: function () {
  20013. return null;
  20014. },
  20015. enumerable: true,
  20016. configurable: true
  20017. });
  20018. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20019. get: function () {
  20020. return this._skeleton;
  20021. },
  20022. /**
  20023. * Gets or sets a skeleton to apply skining transformations
  20024. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20025. */
  20026. set: function (value) {
  20027. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20028. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20029. }
  20030. if (value && value.needInitialSkinMatrix) {
  20031. value._registerMeshWithPoseMatrix(this);
  20032. }
  20033. this._skeleton = value;
  20034. if (!this._skeleton) {
  20035. this._bonesTransformMatrices = null;
  20036. }
  20037. this._markSubMeshesAsAttributesDirty();
  20038. },
  20039. enumerable: true,
  20040. configurable: true
  20041. });
  20042. /**
  20043. * Returns the string "AbstractMesh"
  20044. * @returns "AbstractMesh"
  20045. */
  20046. AbstractMesh.prototype.getClassName = function () {
  20047. return "AbstractMesh";
  20048. };
  20049. /**
  20050. * Gets a string representation of the current mesh
  20051. * @param fullDetails defines a boolean indicating if full details must be included
  20052. * @returns a string representation of the current mesh
  20053. */
  20054. AbstractMesh.prototype.toString = function (fullDetails) {
  20055. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20056. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20057. if (this._skeleton) {
  20058. ret += ", skeleton: " + this._skeleton.name;
  20059. }
  20060. if (fullDetails) {
  20061. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20062. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20063. }
  20064. return ret;
  20065. };
  20066. /** @hidden */
  20067. AbstractMesh.prototype._rebuild = function () {
  20068. if (this._occlusionQuery) {
  20069. this._occlusionQuery = null;
  20070. }
  20071. if (this._edgesRenderer) {
  20072. this._edgesRenderer._rebuild();
  20073. }
  20074. if (!this.subMeshes) {
  20075. return;
  20076. }
  20077. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20078. var subMesh = _a[_i];
  20079. subMesh._rebuild();
  20080. }
  20081. };
  20082. /** @hidden */
  20083. AbstractMesh.prototype._resyncLightSources = function () {
  20084. this._lightSources.length = 0;
  20085. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20086. var light = _a[_i];
  20087. if (!light.isEnabled()) {
  20088. continue;
  20089. }
  20090. if (light.canAffectMesh(this)) {
  20091. this._lightSources.push(light);
  20092. }
  20093. }
  20094. this._markSubMeshesAsLightDirty();
  20095. };
  20096. /** @hidden */
  20097. AbstractMesh.prototype._resyncLighSource = function (light) {
  20098. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20099. var index = this._lightSources.indexOf(light);
  20100. if (index === -1) {
  20101. if (!isIn) {
  20102. return;
  20103. }
  20104. this._lightSources.push(light);
  20105. }
  20106. else {
  20107. if (isIn) {
  20108. return;
  20109. }
  20110. this._lightSources.splice(index, 1);
  20111. }
  20112. this._markSubMeshesAsLightDirty();
  20113. };
  20114. /** @hidden */
  20115. AbstractMesh.prototype._unBindEffect = function () {
  20116. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20117. var subMesh = _a[_i];
  20118. subMesh.setEffect(null);
  20119. }
  20120. };
  20121. /** @hidden */
  20122. AbstractMesh.prototype._removeLightSource = function (light) {
  20123. var index = this._lightSources.indexOf(light);
  20124. if (index === -1) {
  20125. return;
  20126. }
  20127. this._lightSources.splice(index, 1);
  20128. this._markSubMeshesAsLightDirty();
  20129. };
  20130. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20131. if (!this.subMeshes) {
  20132. return;
  20133. }
  20134. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20135. var subMesh = _a[_i];
  20136. if (subMesh._materialDefines) {
  20137. func(subMesh._materialDefines);
  20138. }
  20139. }
  20140. };
  20141. /** @hidden */
  20142. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20143. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20144. };
  20145. /** @hidden */
  20146. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20147. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20148. };
  20149. /** @hidden */
  20150. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20151. if (!this.subMeshes) {
  20152. return;
  20153. }
  20154. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20155. var subMesh = _a[_i];
  20156. var material = subMesh.getMaterial();
  20157. if (material) {
  20158. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20159. }
  20160. }
  20161. };
  20162. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20163. /**
  20164. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20165. */
  20166. get: function () {
  20167. return this._scaling;
  20168. },
  20169. set: function (newScaling) {
  20170. this._scaling = newScaling;
  20171. if (this.physicsImpostor) {
  20172. this.physicsImpostor.forceUpdate();
  20173. }
  20174. },
  20175. enumerable: true,
  20176. configurable: true
  20177. });
  20178. // Methods
  20179. /**
  20180. * Disables the mesh edge rendering mode
  20181. * @returns the currentAbstractMesh
  20182. */
  20183. AbstractMesh.prototype.disableEdgesRendering = function () {
  20184. if (this._edgesRenderer) {
  20185. this._edgesRenderer.dispose();
  20186. this._edgesRenderer = null;
  20187. }
  20188. return this;
  20189. };
  20190. /**
  20191. * Enables the edge rendering mode on the mesh.
  20192. * This mode makes the mesh edges visible
  20193. * @param epsilon defines the maximal distance between two angles to detect a face
  20194. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20195. * @returns the currentAbstractMesh
  20196. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20197. */
  20198. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20199. if (epsilon === void 0) { epsilon = 0.95; }
  20200. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20201. this.disableEdgesRendering();
  20202. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20203. return this;
  20204. };
  20205. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20206. /**
  20207. * Gets the edgesRenderer associated with the mesh
  20208. */
  20209. get: function () {
  20210. return this._edgesRenderer;
  20211. },
  20212. enumerable: true,
  20213. configurable: true
  20214. });
  20215. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20216. /**
  20217. * Returns true if the mesh is blocked. Implemented by child classes
  20218. */
  20219. get: function () {
  20220. return false;
  20221. },
  20222. enumerable: true,
  20223. configurable: true
  20224. });
  20225. /**
  20226. * Returns the mesh itself by default. Implemented by child classes
  20227. * @param camera defines the camera to use to pick the right LOD level
  20228. * @returns the currentAbstractMesh
  20229. */
  20230. AbstractMesh.prototype.getLOD = function (camera) {
  20231. return this;
  20232. };
  20233. /**
  20234. * Returns 0 by default. Implemented by child classes
  20235. * @returns an integer
  20236. */
  20237. AbstractMesh.prototype.getTotalVertices = function () {
  20238. return 0;
  20239. };
  20240. /**
  20241. * Returns null by default. Implemented by child classes
  20242. * @returns null
  20243. */
  20244. AbstractMesh.prototype.getIndices = function () {
  20245. return null;
  20246. };
  20247. /**
  20248. * Returns the array of the requested vertex data kind. Implemented by child classes
  20249. * @param kind defines the vertex data kind to use
  20250. * @returns null
  20251. */
  20252. AbstractMesh.prototype.getVerticesData = function (kind) {
  20253. return null;
  20254. };
  20255. /**
  20256. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20257. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20258. * Note that a new underlying VertexBuffer object is created each call.
  20259. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20260. * @param kind defines vertex data kind:
  20261. * * BABYLON.VertexBuffer.PositionKind
  20262. * * BABYLON.VertexBuffer.UVKind
  20263. * * BABYLON.VertexBuffer.UV2Kind
  20264. * * BABYLON.VertexBuffer.UV3Kind
  20265. * * BABYLON.VertexBuffer.UV4Kind
  20266. * * BABYLON.VertexBuffer.UV5Kind
  20267. * * BABYLON.VertexBuffer.UV6Kind
  20268. * * BABYLON.VertexBuffer.ColorKind
  20269. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20270. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20271. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20272. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20273. * @param data defines the data source
  20274. * @param updatable defines if the data must be flagged as updatable (or static)
  20275. * @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
  20276. * @returns the current mesh
  20277. */
  20278. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20279. return this;
  20280. };
  20281. /**
  20282. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20283. * If the mesh has no geometry, it is simply returned as it is.
  20284. * @param kind defines vertex data kind:
  20285. * * BABYLON.VertexBuffer.PositionKind
  20286. * * BABYLON.VertexBuffer.UVKind
  20287. * * BABYLON.VertexBuffer.UV2Kind
  20288. * * BABYLON.VertexBuffer.UV3Kind
  20289. * * BABYLON.VertexBuffer.UV4Kind
  20290. * * BABYLON.VertexBuffer.UV5Kind
  20291. * * BABYLON.VertexBuffer.UV6Kind
  20292. * * BABYLON.VertexBuffer.ColorKind
  20293. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20294. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20295. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20296. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20297. * @param data defines the data source
  20298. * @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
  20299. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20300. * @returns the current mesh
  20301. */
  20302. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20303. return this;
  20304. };
  20305. /**
  20306. * Sets the mesh indices,
  20307. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20308. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20309. * @param totalVertices Defines the total number of vertices
  20310. * @returns the current mesh
  20311. */
  20312. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20313. return this;
  20314. };
  20315. /**
  20316. * Gets a boolean indicating if specific vertex data is present
  20317. * @param kind defines the vertex data kind to use
  20318. * @returns true is data kind is present
  20319. */
  20320. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20321. return false;
  20322. };
  20323. /**
  20324. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20325. * @returns a BoundingInfo
  20326. */
  20327. AbstractMesh.prototype.getBoundingInfo = function () {
  20328. if (this._masterMesh) {
  20329. return this._masterMesh.getBoundingInfo();
  20330. }
  20331. if (!this._boundingInfo) {
  20332. // this._boundingInfo is being created here
  20333. this._updateBoundingInfo();
  20334. }
  20335. // cannot be null.
  20336. return this._boundingInfo;
  20337. };
  20338. /**
  20339. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20340. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20341. * @returns the current mesh
  20342. */
  20343. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20344. if (includeDescendants === void 0) { includeDescendants = true; }
  20345. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20346. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20347. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20348. if (maxDimension === 0) {
  20349. return this;
  20350. }
  20351. var scale = 1 / maxDimension;
  20352. this.scaling.scaleInPlace(scale);
  20353. return this;
  20354. };
  20355. /**
  20356. * Overwrite the current bounding info
  20357. * @param boundingInfo defines the new bounding info
  20358. * @returns the current mesh
  20359. */
  20360. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20361. this._boundingInfo = boundingInfo;
  20362. return this;
  20363. };
  20364. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20365. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20366. get: function () {
  20367. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20368. },
  20369. enumerable: true,
  20370. configurable: true
  20371. });
  20372. /** @hidden */
  20373. AbstractMesh.prototype._preActivate = function () {
  20374. };
  20375. /** @hidden */
  20376. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20377. };
  20378. /** @hidden */
  20379. AbstractMesh.prototype._activate = function (renderId) {
  20380. this._renderId = renderId;
  20381. };
  20382. /**
  20383. * Gets the current world matrix
  20384. * @returns a Matrix
  20385. */
  20386. AbstractMesh.prototype.getWorldMatrix = function () {
  20387. if (this._masterMesh) {
  20388. return this._masterMesh.getWorldMatrix();
  20389. }
  20390. return _super.prototype.getWorldMatrix.call(this);
  20391. };
  20392. /** @hidden */
  20393. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20394. if (this._masterMesh) {
  20395. return this._masterMesh._getWorldMatrixDeterminant();
  20396. }
  20397. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20398. };
  20399. // ================================== Point of View Movement =================================
  20400. /**
  20401. * Perform relative position change from the point of view of behind the front of the mesh.
  20402. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20403. * Supports definition of mesh facing forward or backward
  20404. * @param amountRight defines the distance on the right axis
  20405. * @param amountUp defines the distance on the up axis
  20406. * @param amountForward defines the distance on the forward axis
  20407. * @returns the current mesh
  20408. */
  20409. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20410. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20411. return this;
  20412. };
  20413. /**
  20414. * Calculate relative position change from the point of view of behind the front of the mesh.
  20415. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20416. * Supports definition of mesh facing forward or backward
  20417. * @param amountRight defines the distance on the right axis
  20418. * @param amountUp defines the distance on the up axis
  20419. * @param amountForward defines the distance on the forward axis
  20420. * @returns the new displacement vector
  20421. */
  20422. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20423. var rotMatrix = new BABYLON.Matrix();
  20424. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20425. rotQuaternion.toRotationMatrix(rotMatrix);
  20426. var translationDelta = BABYLON.Vector3.Zero();
  20427. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20428. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20429. return translationDelta;
  20430. };
  20431. // ================================== Point of View Rotation =================================
  20432. /**
  20433. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20434. * Supports definition of mesh facing forward or backward
  20435. * @param flipBack defines the flip
  20436. * @param twirlClockwise defines the twirl
  20437. * @param tiltRight defines the tilt
  20438. * @returns the current mesh
  20439. */
  20440. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20441. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20442. return this;
  20443. };
  20444. /**
  20445. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20446. * Supports definition of mesh facing forward or backward.
  20447. * @param flipBack defines the flip
  20448. * @param twirlClockwise defines the twirl
  20449. * @param tiltRight defines the tilt
  20450. * @returns the new rotation vector
  20451. */
  20452. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20453. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20454. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20455. };
  20456. /**
  20457. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20458. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20459. * @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
  20460. * @returns the new bounding vectors
  20461. */
  20462. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20463. if (includeDescendants === void 0) { includeDescendants = true; }
  20464. if (predicate === void 0) { predicate = null; }
  20465. // Ensures that all world matrix will be recomputed.
  20466. this.getScene().incrementRenderId();
  20467. this.computeWorldMatrix(true);
  20468. var min;
  20469. var max;
  20470. var boundingInfo = this.getBoundingInfo();
  20471. if (!this.subMeshes) {
  20472. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20473. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20474. }
  20475. else {
  20476. min = boundingInfo.boundingBox.minimumWorld;
  20477. max = boundingInfo.boundingBox.maximumWorld;
  20478. }
  20479. if (includeDescendants) {
  20480. var descendants = this.getDescendants(false);
  20481. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20482. var descendant = descendants_1[_i];
  20483. var childMesh = descendant;
  20484. childMesh.computeWorldMatrix(true);
  20485. // Filters meshes based on custom predicate function.
  20486. if (predicate && !predicate(childMesh)) {
  20487. continue;
  20488. }
  20489. //make sure we have the needed params to get mix and max
  20490. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20491. continue;
  20492. }
  20493. var childBoundingInfo = childMesh.getBoundingInfo();
  20494. var boundingBox = childBoundingInfo.boundingBox;
  20495. var minBox = boundingBox.minimumWorld;
  20496. var maxBox = boundingBox.maximumWorld;
  20497. BABYLON.Tools.CheckExtends(minBox, min, max);
  20498. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20499. }
  20500. }
  20501. return {
  20502. min: min,
  20503. max: max
  20504. };
  20505. };
  20506. /** @hidden */
  20507. AbstractMesh.prototype._updateBoundingInfo = function () {
  20508. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20509. this._boundingInfo.update(this.worldMatrixFromCache);
  20510. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20511. return this;
  20512. };
  20513. /** @hidden */
  20514. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20515. if (!this.subMeshes) {
  20516. return this;
  20517. }
  20518. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20519. var subMesh = this.subMeshes[subIndex];
  20520. if (!subMesh.IsGlobal) {
  20521. subMesh.updateBoundingInfo(matrix);
  20522. }
  20523. }
  20524. return this;
  20525. };
  20526. /** @hidden */
  20527. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20528. // Bounding info
  20529. this._updateBoundingInfo();
  20530. };
  20531. /**
  20532. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20533. * A mesh is in the frustum if its bounding box intersects the frustum
  20534. * @param frustumPlanes defines the frustum to test
  20535. * @returns true if the mesh is in the frustum planes
  20536. */
  20537. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20538. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20539. };
  20540. /**
  20541. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20542. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20543. * @param frustumPlanes defines the frustum to test
  20544. * @returns true if the mesh is completely in the frustum planes
  20545. */
  20546. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20547. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20548. };
  20549. /**
  20550. * True if the mesh intersects another mesh or a SolidParticle object
  20551. * @param mesh defines a target mesh or SolidParticle to test
  20552. * @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)
  20553. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20554. * @returns true if there is an intersection
  20555. */
  20556. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20557. if (precise === void 0) { precise = false; }
  20558. if (!this._boundingInfo || !mesh._boundingInfo) {
  20559. return false;
  20560. }
  20561. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20562. return true;
  20563. }
  20564. if (includeDescendants) {
  20565. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20566. var child = _a[_i];
  20567. if (child.intersectsMesh(mesh, precise, true)) {
  20568. return true;
  20569. }
  20570. }
  20571. }
  20572. return false;
  20573. };
  20574. /**
  20575. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20576. * @param point defines the point to test
  20577. * @returns true if there is an intersection
  20578. */
  20579. AbstractMesh.prototype.intersectsPoint = function (point) {
  20580. if (!this._boundingInfo) {
  20581. return false;
  20582. }
  20583. return this._boundingInfo.intersectsPoint(point);
  20584. };
  20585. /**
  20586. * Gets the current physics impostor
  20587. * @see http://doc.babylonjs.com/features/physics_engine
  20588. * @returns a physics impostor or null
  20589. */
  20590. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20591. return this.physicsImpostor;
  20592. };
  20593. /**
  20594. * Gets the position of the current mesh in camera space
  20595. * @param camera defines the camera to use
  20596. * @returns a position
  20597. */
  20598. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20599. if (camera === void 0) { camera = null; }
  20600. if (!camera) {
  20601. camera = this.getScene().activeCamera;
  20602. }
  20603. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20604. };
  20605. /**
  20606. * Returns the distance from the mesh to the active camera
  20607. * @param camera defines the camera to use
  20608. * @returns the distance
  20609. */
  20610. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20611. if (camera === void 0) { camera = null; }
  20612. if (!camera) {
  20613. camera = this.getScene().activeCamera;
  20614. }
  20615. return this.absolutePosition.subtract(camera.position).length();
  20616. };
  20617. /**
  20618. * Apply a physic impulse to the mesh
  20619. * @param force defines the force to apply
  20620. * @param contactPoint defines where to apply the force
  20621. * @returns the current mesh
  20622. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20623. */
  20624. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20625. if (!this.physicsImpostor) {
  20626. return this;
  20627. }
  20628. this.physicsImpostor.applyImpulse(force, contactPoint);
  20629. return this;
  20630. };
  20631. /**
  20632. * Creates a physic joint between two meshes
  20633. * @param otherMesh defines the other mesh to use
  20634. * @param pivot1 defines the pivot to use on this mesh
  20635. * @param pivot2 defines the pivot to use on the other mesh
  20636. * @param options defines additional options (can be plugin dependent)
  20637. * @returns the current mesh
  20638. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20639. */
  20640. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20641. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20642. return this;
  20643. }
  20644. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20645. mainPivot: pivot1,
  20646. connectedPivot: pivot2,
  20647. nativeParams: options
  20648. });
  20649. return this;
  20650. };
  20651. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20652. // Collisions
  20653. /**
  20654. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20655. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20656. */
  20657. get: function () {
  20658. return this._checkCollisions;
  20659. },
  20660. set: function (collisionEnabled) {
  20661. this._checkCollisions = collisionEnabled;
  20662. if (this.getScene().workerCollisions) {
  20663. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20664. }
  20665. },
  20666. enumerable: true,
  20667. configurable: true
  20668. });
  20669. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20670. /**
  20671. * Gets Collider object used to compute collisions (not physics)
  20672. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20673. */
  20674. get: function () {
  20675. return this._collider;
  20676. },
  20677. enumerable: true,
  20678. configurable: true
  20679. });
  20680. /**
  20681. * Move the mesh using collision engine
  20682. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20683. * @param displacement defines the requested displacement vector
  20684. * @returns the current mesh
  20685. */
  20686. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20687. var globalPosition = this.getAbsolutePosition();
  20688. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20689. if (!this._collider) {
  20690. this._collider = new BABYLON.Collider();
  20691. }
  20692. this._collider._radius = this.ellipsoid;
  20693. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20694. return this;
  20695. };
  20696. // Submeshes octree
  20697. /**
  20698. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20699. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20700. * @param maxCapacity defines the maximum size of each block (64 by default)
  20701. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20702. * @returns the new octree
  20703. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20704. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20705. */
  20706. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20707. if (maxCapacity === void 0) { maxCapacity = 64; }
  20708. if (maxDepth === void 0) { maxDepth = 2; }
  20709. if (!this._submeshesOctree) {
  20710. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20711. }
  20712. this.computeWorldMatrix(true);
  20713. var boundingInfo = this.getBoundingInfo();
  20714. // Update octree
  20715. var bbox = boundingInfo.boundingBox;
  20716. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20717. return this._submeshesOctree;
  20718. };
  20719. // Collisions
  20720. /** @hidden */
  20721. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20722. this._generatePointsArray();
  20723. if (!this._positions) {
  20724. return this;
  20725. }
  20726. // Transformation
  20727. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20728. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20729. subMesh._lastColliderWorldVertices = [];
  20730. subMesh._trianglePlanes = [];
  20731. var start = subMesh.verticesStart;
  20732. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20733. for (var i = start; i < end; i++) {
  20734. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20735. }
  20736. }
  20737. // Collide
  20738. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20739. if (collider.collisionFound) {
  20740. collider.collidedMesh = this;
  20741. }
  20742. return this;
  20743. };
  20744. /** @hidden */
  20745. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20746. var subMeshes;
  20747. var len;
  20748. // Octrees
  20749. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20750. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20751. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20752. len = intersections.length;
  20753. subMeshes = intersections.data;
  20754. }
  20755. else {
  20756. subMeshes = this.subMeshes;
  20757. len = subMeshes.length;
  20758. }
  20759. for (var index = 0; index < len; index++) {
  20760. var subMesh = subMeshes[index];
  20761. // Bounding test
  20762. if (len > 1 && !subMesh._checkCollision(collider))
  20763. continue;
  20764. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20765. }
  20766. return this;
  20767. };
  20768. /** @hidden */
  20769. AbstractMesh.prototype._checkCollision = function (collider) {
  20770. // Bounding box test
  20771. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20772. return this;
  20773. // Transformation matrix
  20774. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20775. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20776. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20777. return this;
  20778. };
  20779. // Picking
  20780. /** @hidden */
  20781. AbstractMesh.prototype._generatePointsArray = function () {
  20782. return false;
  20783. };
  20784. /**
  20785. * Checks if the passed Ray intersects with the mesh
  20786. * @param ray defines the ray to use
  20787. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20788. * @returns the picking info
  20789. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20790. */
  20791. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20792. var pickingInfo = new BABYLON.PickingInfo();
  20793. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20794. return pickingInfo;
  20795. }
  20796. if (!this._generatePointsArray()) {
  20797. return pickingInfo;
  20798. }
  20799. var intersectInfo = null;
  20800. // Octrees
  20801. var subMeshes;
  20802. var len;
  20803. if (this._submeshesOctree && this.useOctreeForPicking) {
  20804. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20805. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20806. len = intersections.length;
  20807. subMeshes = intersections.data;
  20808. }
  20809. else {
  20810. subMeshes = this.subMeshes;
  20811. len = subMeshes.length;
  20812. }
  20813. for (var index = 0; index < len; index++) {
  20814. var subMesh = subMeshes[index];
  20815. // Bounding test
  20816. if (len > 1 && !subMesh.canIntersects(ray))
  20817. continue;
  20818. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20819. if (currentIntersectInfo) {
  20820. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20821. intersectInfo = currentIntersectInfo;
  20822. intersectInfo.subMeshId = index;
  20823. if (fastCheck) {
  20824. break;
  20825. }
  20826. }
  20827. }
  20828. }
  20829. if (intersectInfo) {
  20830. // Get picked point
  20831. var world = this.getWorldMatrix();
  20832. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20833. var direction = ray.direction.clone();
  20834. direction = direction.scale(intersectInfo.distance);
  20835. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20836. var pickedPoint = worldOrigin.add(worldDirection);
  20837. // Return result
  20838. pickingInfo.hit = true;
  20839. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20840. pickingInfo.pickedPoint = pickedPoint;
  20841. pickingInfo.pickedMesh = this;
  20842. pickingInfo.bu = intersectInfo.bu || 0;
  20843. pickingInfo.bv = intersectInfo.bv || 0;
  20844. pickingInfo.faceId = intersectInfo.faceId;
  20845. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20846. return pickingInfo;
  20847. }
  20848. return pickingInfo;
  20849. };
  20850. /**
  20851. * Clones the current mesh
  20852. * @param name defines the mesh name
  20853. * @param newParent defines the new mesh parent
  20854. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20855. * @returns the new mesh
  20856. */
  20857. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20858. return null;
  20859. };
  20860. /**
  20861. * Disposes all the submeshes of the current meshnp
  20862. * @returns the current mesh
  20863. */
  20864. AbstractMesh.prototype.releaseSubMeshes = function () {
  20865. if (this.subMeshes) {
  20866. while (this.subMeshes.length) {
  20867. this.subMeshes[0].dispose();
  20868. }
  20869. }
  20870. else {
  20871. this.subMeshes = new Array();
  20872. }
  20873. return this;
  20874. };
  20875. /**
  20876. * Releases resources associated with this abstract mesh.
  20877. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20878. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20879. */
  20880. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20881. var _this = this;
  20882. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20883. var index;
  20884. // Smart Array Retainers.
  20885. this.getScene().freeActiveMeshes();
  20886. this.getScene().freeRenderingGroups();
  20887. // Action manager
  20888. if (this.actionManager !== undefined && this.actionManager !== null) {
  20889. this.actionManager.dispose();
  20890. this.actionManager = null;
  20891. }
  20892. // Skeleton
  20893. this._skeleton = null;
  20894. // Physics
  20895. if (this.physicsImpostor) {
  20896. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20897. }
  20898. // Intersections in progress
  20899. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20900. var other = this._intersectionsInProgress[index];
  20901. var pos = other._intersectionsInProgress.indexOf(this);
  20902. other._intersectionsInProgress.splice(pos, 1);
  20903. }
  20904. this._intersectionsInProgress = [];
  20905. // Lights
  20906. var lights = this.getScene().lights;
  20907. lights.forEach(function (light) {
  20908. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20909. if (meshIndex !== -1) {
  20910. light.includedOnlyMeshes.splice(meshIndex, 1);
  20911. }
  20912. meshIndex = light.excludedMeshes.indexOf(_this);
  20913. if (meshIndex !== -1) {
  20914. light.excludedMeshes.splice(meshIndex, 1);
  20915. }
  20916. // Shadow generators
  20917. var generator = light.getShadowGenerator();
  20918. if (generator) {
  20919. var shadowMap = generator.getShadowMap();
  20920. if (shadowMap && shadowMap.renderList) {
  20921. meshIndex = shadowMap.renderList.indexOf(_this);
  20922. if (meshIndex !== -1) {
  20923. shadowMap.renderList.splice(meshIndex, 1);
  20924. }
  20925. }
  20926. }
  20927. });
  20928. // Edges
  20929. if (this._edgesRenderer) {
  20930. this._edgesRenderer.dispose();
  20931. this._edgesRenderer = null;
  20932. }
  20933. // SubMeshes
  20934. if (this.getClassName() !== "InstancedMesh") {
  20935. this.releaseSubMeshes();
  20936. }
  20937. // Octree
  20938. var sceneOctree = this.getScene().selectionOctree;
  20939. if (sceneOctree !== undefined && sceneOctree !== null) {
  20940. var index = sceneOctree.dynamicContent.indexOf(this);
  20941. if (index !== -1) {
  20942. sceneOctree.dynamicContent.splice(index, 1);
  20943. }
  20944. }
  20945. // Query
  20946. var engine = this.getScene().getEngine();
  20947. if (this._occlusionQuery) {
  20948. this._isOcclusionQueryInProgress = false;
  20949. engine.deleteQuery(this._occlusionQuery);
  20950. this._occlusionQuery = null;
  20951. }
  20952. // Engine
  20953. engine.wipeCaches();
  20954. // Remove from scene
  20955. this.getScene().removeMesh(this);
  20956. if (disposeMaterialAndTextures) {
  20957. if (this.material) {
  20958. this.material.dispose(false, true);
  20959. }
  20960. }
  20961. if (!doNotRecurse) {
  20962. // Particles
  20963. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20964. if (this.getScene().particleSystems[index].emitter === this) {
  20965. this.getScene().particleSystems[index].dispose();
  20966. index--;
  20967. }
  20968. }
  20969. }
  20970. // facet data
  20971. if (this._facetDataEnabled) {
  20972. this.disableFacetData();
  20973. }
  20974. this.onAfterWorldMatrixUpdateObservable.clear();
  20975. this.onCollideObservable.clear();
  20976. this.onCollisionPositionChangeObservable.clear();
  20977. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20978. };
  20979. /**
  20980. * Adds the passed mesh as a child to the current mesh
  20981. * @param mesh defines the child mesh
  20982. * @returns the current mesh
  20983. */
  20984. AbstractMesh.prototype.addChild = function (mesh) {
  20985. mesh.setParent(this);
  20986. return this;
  20987. };
  20988. /**
  20989. * Removes the passed mesh from the current mesh children list
  20990. * @param mesh defines the child mesh
  20991. * @returns the current mesh
  20992. */
  20993. AbstractMesh.prototype.removeChild = function (mesh) {
  20994. mesh.setParent(null);
  20995. return this;
  20996. };
  20997. // Facet data
  20998. /** @hidden */
  20999. AbstractMesh.prototype._initFacetData = function () {
  21000. if (!this._facetNormals) {
  21001. this._facetNormals = new Array();
  21002. }
  21003. if (!this._facetPositions) {
  21004. this._facetPositions = new Array();
  21005. }
  21006. if (!this._facetPartitioning) {
  21007. this._facetPartitioning = new Array();
  21008. }
  21009. this._facetNb = (this.getIndices().length / 3) | 0;
  21010. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21011. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21012. for (var f = 0; f < this._facetNb; f++) {
  21013. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21014. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21015. }
  21016. this._facetDataEnabled = true;
  21017. return this;
  21018. };
  21019. /**
  21020. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21021. * This method can be called within the render loop.
  21022. * 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
  21023. * @returns the current mesh
  21024. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21025. */
  21026. AbstractMesh.prototype.updateFacetData = function () {
  21027. if (!this._facetDataEnabled) {
  21028. this._initFacetData();
  21029. }
  21030. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21031. var indices = this.getIndices();
  21032. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21033. var bInfo = this.getBoundingInfo();
  21034. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21035. // init arrays, matrix and sort function on first call
  21036. this._facetDepthSortEnabled = true;
  21037. if (indices instanceof Uint16Array) {
  21038. this._depthSortedIndices = new Uint16Array(indices);
  21039. }
  21040. else if (indices instanceof Uint32Array) {
  21041. this._depthSortedIndices = new Uint32Array(indices);
  21042. }
  21043. else {
  21044. var needs32bits = false;
  21045. for (var i = 0; i < indices.length; i++) {
  21046. if (indices[i] > 65535) {
  21047. needs32bits = true;
  21048. break;
  21049. }
  21050. }
  21051. if (needs32bits) {
  21052. this._depthSortedIndices = new Uint32Array(indices);
  21053. }
  21054. else {
  21055. this._depthSortedIndices = new Uint16Array(indices);
  21056. }
  21057. }
  21058. this._facetDepthSortFunction = function (f1, f2) {
  21059. return (f2.sqDistance - f1.sqDistance);
  21060. };
  21061. if (!this._facetDepthSortFrom) {
  21062. var camera = this.getScene().activeCamera;
  21063. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21064. }
  21065. this._depthSortedFacets = [];
  21066. for (var f = 0; f < this._facetNb; f++) {
  21067. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21068. this._depthSortedFacets.push(depthSortedFacet);
  21069. }
  21070. this._invertedMatrix = BABYLON.Matrix.Identity();
  21071. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21072. }
  21073. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21074. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21075. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21076. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21077. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21078. this._subDiv.max = this._partitioningSubdivisions;
  21079. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21080. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21081. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21082. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21083. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21084. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21085. // set the parameters for ComputeNormals()
  21086. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21087. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21088. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21089. this._facetParameters.bInfo = bInfo;
  21090. this._facetParameters.bbSize = this._bbSize;
  21091. this._facetParameters.subDiv = this._subDiv;
  21092. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21093. this._facetParameters.depthSort = this._facetDepthSort;
  21094. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21095. this.computeWorldMatrix(true);
  21096. this._worldMatrix.invertToRef(this._invertedMatrix);
  21097. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21098. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21099. }
  21100. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21101. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21102. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21103. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21104. var l = (this._depthSortedIndices.length / 3) | 0;
  21105. for (var f = 0; f < l; f++) {
  21106. var sind = this._depthSortedFacets[f].ind;
  21107. this._depthSortedIndices[f * 3] = indices[sind];
  21108. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21109. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21110. }
  21111. this.updateIndices(this._depthSortedIndices);
  21112. }
  21113. return this;
  21114. };
  21115. /**
  21116. * Returns the facetLocalNormals array.
  21117. * The normals are expressed in the mesh local spac
  21118. * @returns an array of Vector3
  21119. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21120. */
  21121. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21122. if (!this._facetNormals) {
  21123. this.updateFacetData();
  21124. }
  21125. return this._facetNormals;
  21126. };
  21127. /**
  21128. * Returns the facetLocalPositions array.
  21129. * The facet positions are expressed in the mesh local space
  21130. * @returns an array of Vector3
  21131. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21132. */
  21133. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21134. if (!this._facetPositions) {
  21135. this.updateFacetData();
  21136. }
  21137. return this._facetPositions;
  21138. };
  21139. /**
  21140. * Returns the facetLocalPartioning array
  21141. * @returns an array of array of numbers
  21142. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21143. */
  21144. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21145. if (!this._facetPartitioning) {
  21146. this.updateFacetData();
  21147. }
  21148. return this._facetPartitioning;
  21149. };
  21150. /**
  21151. * Returns the i-th facet position in the world system.
  21152. * This method allocates a new Vector3 per call
  21153. * @param i defines the facet index
  21154. * @returns a new Vector3
  21155. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21156. */
  21157. AbstractMesh.prototype.getFacetPosition = function (i) {
  21158. var pos = BABYLON.Vector3.Zero();
  21159. this.getFacetPositionToRef(i, pos);
  21160. return pos;
  21161. };
  21162. /**
  21163. * Sets the reference Vector3 with the i-th facet position in the world system
  21164. * @param i defines the facet index
  21165. * @param ref defines the target vector
  21166. * @returns the current mesh
  21167. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21168. */
  21169. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21170. var localPos = (this.getFacetLocalPositions())[i];
  21171. var world = this.getWorldMatrix();
  21172. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21173. return this;
  21174. };
  21175. /**
  21176. * Returns the i-th facet normal in the world system.
  21177. * This method allocates a new Vector3 per call
  21178. * @param i defines the facet index
  21179. * @returns a new Vector3
  21180. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21181. */
  21182. AbstractMesh.prototype.getFacetNormal = function (i) {
  21183. var norm = BABYLON.Vector3.Zero();
  21184. this.getFacetNormalToRef(i, norm);
  21185. return norm;
  21186. };
  21187. /**
  21188. * Sets the reference Vector3 with the i-th facet normal in the world system
  21189. * @param i defines the facet index
  21190. * @param ref defines the target vector
  21191. * @returns the current mesh
  21192. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21193. */
  21194. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21195. var localNorm = (this.getFacetLocalNormals())[i];
  21196. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21197. return this;
  21198. };
  21199. /**
  21200. * 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)
  21201. * @param x defines x coordinate
  21202. * @param y defines y coordinate
  21203. * @param z defines z coordinate
  21204. * @returns the array of facet indexes
  21205. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21206. */
  21207. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21208. var bInfo = this.getBoundingInfo();
  21209. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21210. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21211. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21212. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21213. return null;
  21214. }
  21215. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21216. };
  21217. /**
  21218. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21219. * @param projected sets as the (x,y,z) world projection on the facet
  21220. * @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
  21221. * @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
  21222. * @param x defines x coordinate
  21223. * @param y defines y coordinate
  21224. * @param z defines z coordinate
  21225. * @returns the face index if found (or null instead)
  21226. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21227. */
  21228. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21229. if (checkFace === void 0) { checkFace = false; }
  21230. if (facing === void 0) { facing = true; }
  21231. var world = this.getWorldMatrix();
  21232. var invMat = BABYLON.Tmp.Matrix[5];
  21233. world.invertToRef(invMat);
  21234. var invVect = BABYLON.Tmp.Vector3[8];
  21235. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21236. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21237. if (projected) {
  21238. // tranform the local computed projected vector to world coordinates
  21239. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21240. }
  21241. return closest;
  21242. };
  21243. /**
  21244. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21245. * @param projected sets as the (x,y,z) local projection on the facet
  21246. * @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
  21247. * @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
  21248. * @param x defines x coordinate
  21249. * @param y defines y coordinate
  21250. * @param z defines z coordinate
  21251. * @returns the face index if found (or null instead)
  21252. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21253. */
  21254. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21255. if (checkFace === void 0) { checkFace = false; }
  21256. if (facing === void 0) { facing = true; }
  21257. var closest = null;
  21258. var tmpx = 0.0;
  21259. var tmpy = 0.0;
  21260. var tmpz = 0.0;
  21261. var d = 0.0; // tmp dot facet normal * facet position
  21262. var t0 = 0.0;
  21263. var projx = 0.0;
  21264. var projy = 0.0;
  21265. var projz = 0.0;
  21266. // Get all the facets in the same partitioning block than (x, y, z)
  21267. var facetPositions = this.getFacetLocalPositions();
  21268. var facetNormals = this.getFacetLocalNormals();
  21269. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21270. if (!facetsInBlock) {
  21271. return null;
  21272. }
  21273. // Get the closest facet to (x, y, z)
  21274. var shortest = Number.MAX_VALUE; // init distance vars
  21275. var tmpDistance = shortest;
  21276. var fib; // current facet in the block
  21277. var norm; // current facet normal
  21278. var p0; // current facet barycenter position
  21279. // loop on all the facets in the current partitioning block
  21280. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21281. fib = facetsInBlock[idx];
  21282. norm = facetNormals[fib];
  21283. p0 = facetPositions[fib];
  21284. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21285. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21286. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21287. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21288. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21289. projx = x + norm.x * t0;
  21290. projy = y + norm.y * t0;
  21291. projz = z + norm.z * t0;
  21292. tmpx = projx - x;
  21293. tmpy = projy - y;
  21294. tmpz = projz - z;
  21295. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21296. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21297. shortest = tmpDistance;
  21298. closest = fib;
  21299. if (projected) {
  21300. projected.x = projx;
  21301. projected.y = projy;
  21302. projected.z = projz;
  21303. }
  21304. }
  21305. }
  21306. }
  21307. return closest;
  21308. };
  21309. /**
  21310. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21311. * @returns the parameters
  21312. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21313. */
  21314. AbstractMesh.prototype.getFacetDataParameters = function () {
  21315. return this._facetParameters;
  21316. };
  21317. /**
  21318. * Disables the feature FacetData and frees the related memory
  21319. * @returns the current mesh
  21320. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21321. */
  21322. AbstractMesh.prototype.disableFacetData = function () {
  21323. if (this._facetDataEnabled) {
  21324. this._facetDataEnabled = false;
  21325. this._facetPositions = new Array();
  21326. this._facetNormals = new Array();
  21327. this._facetPartitioning = new Array();
  21328. this._facetParameters = null;
  21329. this._depthSortedIndices = new Uint32Array(0);
  21330. }
  21331. return this;
  21332. };
  21333. /**
  21334. * Updates the AbstractMesh indices array
  21335. * @param indices defines the data source
  21336. * @returns the current mesh
  21337. */
  21338. AbstractMesh.prototype.updateIndices = function (indices) {
  21339. return this;
  21340. };
  21341. /**
  21342. * Creates new normals data for the mesh
  21343. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21344. * @returns the current mesh
  21345. */
  21346. AbstractMesh.prototype.createNormals = function (updatable) {
  21347. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21348. var indices = this.getIndices();
  21349. var normals;
  21350. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21351. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21352. }
  21353. else {
  21354. normals = [];
  21355. }
  21356. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21357. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21358. return this;
  21359. };
  21360. /**
  21361. * Align the mesh with a normal
  21362. * @param normal defines the normal to use
  21363. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21364. * @returns the current mesh
  21365. */
  21366. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21367. if (!upDirection) {
  21368. upDirection = BABYLON.Axis.Y;
  21369. }
  21370. var axisX = BABYLON.Tmp.Vector3[0];
  21371. var axisZ = BABYLON.Tmp.Vector3[1];
  21372. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21373. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21374. if (this.rotationQuaternion) {
  21375. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21376. }
  21377. else {
  21378. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21379. }
  21380. return this;
  21381. };
  21382. /** @hidden */
  21383. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21384. this._isOccluded = false;
  21385. };
  21386. /** No occlusion */
  21387. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21388. /** Occlusion set to optimisitic */
  21389. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21390. /** Occlusion set to strict */
  21391. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21392. /** Use an accurante occlusion algorithm */
  21393. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21394. /** Use a conservative occlusion algorithm */
  21395. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21396. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21397. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21398. /** Culling strategy with bounding sphere only and then frustum culling */
  21399. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21400. return AbstractMesh;
  21401. }(BABYLON.TransformNode));
  21402. BABYLON.AbstractMesh = AbstractMesh;
  21403. })(BABYLON || (BABYLON = {}));
  21404. //# sourceMappingURL=babylon.abstractMesh.js.map
  21405. var BABYLON;
  21406. (function (BABYLON) {
  21407. /**
  21408. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21409. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21410. * 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.
  21411. */
  21412. var Light = /** @class */ (function (_super) {
  21413. __extends(Light, _super);
  21414. /**
  21415. * Creates a Light object in the scene.
  21416. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21417. * @param name The firendly name of the light
  21418. * @param scene The scene the light belongs too
  21419. */
  21420. function Light(name, scene) {
  21421. var _this = _super.call(this, name, scene) || this;
  21422. /**
  21423. * Diffuse gives the basic color to an object.
  21424. */
  21425. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21426. /**
  21427. * Specular produces a highlight color on an object.
  21428. * Note: This is note affecting PBR materials.
  21429. */
  21430. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21431. /**
  21432. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21433. * falling off base on range or angle.
  21434. * This can be set to any values in Light.FALLOFF_x.
  21435. *
  21436. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21437. * other types of materials.
  21438. */
  21439. _this.falloffType = Light.FALLOFF_DEFAULT;
  21440. /**
  21441. * Strength of the light.
  21442. * Note: By default it is define in the framework own unit.
  21443. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21444. */
  21445. _this.intensity = 1.0;
  21446. _this._range = Number.MAX_VALUE;
  21447. _this._inverseSquaredRange = 0;
  21448. /**
  21449. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21450. * of light.
  21451. */
  21452. _this._photometricScale = 1.0;
  21453. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21454. _this._radius = 0.00001;
  21455. /**
  21456. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21457. * exceeding the number allowed of the materials.
  21458. */
  21459. _this.renderPriority = 0;
  21460. _this._shadowEnabled = true;
  21461. _this._excludeWithLayerMask = 0;
  21462. _this._includeOnlyWithLayerMask = 0;
  21463. _this._lightmapMode = 0;
  21464. /**
  21465. * @hidden Internal use only.
  21466. */
  21467. _this._excludedMeshesIds = new Array();
  21468. /**
  21469. * @hidden Internal use only.
  21470. */
  21471. _this._includedOnlyMeshesIds = new Array();
  21472. _this.getScene().addLight(_this);
  21473. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21474. _this._buildUniformLayout();
  21475. _this.includedOnlyMeshes = new Array();
  21476. _this.excludedMeshes = new Array();
  21477. _this._resyncMeshes();
  21478. return _this;
  21479. }
  21480. Object.defineProperty(Light.prototype, "range", {
  21481. /**
  21482. * Defines how far from the source the light is impacting in scene units.
  21483. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21484. */
  21485. get: function () {
  21486. return this._range;
  21487. },
  21488. /**
  21489. * Defines how far from the source the light is impacting in scene units.
  21490. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21491. */
  21492. set: function (value) {
  21493. this._range = value;
  21494. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21495. },
  21496. enumerable: true,
  21497. configurable: true
  21498. });
  21499. Object.defineProperty(Light.prototype, "intensityMode", {
  21500. /**
  21501. * Gets the photometric scale used to interpret the intensity.
  21502. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21503. */
  21504. get: function () {
  21505. return this._intensityMode;
  21506. },
  21507. /**
  21508. * Sets the photometric scale used to interpret the intensity.
  21509. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21510. */
  21511. set: function (value) {
  21512. this._intensityMode = value;
  21513. this._computePhotometricScale();
  21514. },
  21515. enumerable: true,
  21516. configurable: true
  21517. });
  21518. ;
  21519. ;
  21520. Object.defineProperty(Light.prototype, "radius", {
  21521. /**
  21522. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21523. */
  21524. get: function () {
  21525. return this._radius;
  21526. },
  21527. /**
  21528. * sets the light radius used by PBR Materials to simulate soft area lights.
  21529. */
  21530. set: function (value) {
  21531. this._radius = value;
  21532. this._computePhotometricScale();
  21533. },
  21534. enumerable: true,
  21535. configurable: true
  21536. });
  21537. ;
  21538. ;
  21539. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21540. /**
  21541. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21542. * the current shadow generator.
  21543. */
  21544. get: function () {
  21545. return this._shadowEnabled;
  21546. },
  21547. /**
  21548. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21549. * the current shadow generator.
  21550. */
  21551. set: function (value) {
  21552. if (this._shadowEnabled === value) {
  21553. return;
  21554. }
  21555. this._shadowEnabled = value;
  21556. this._markMeshesAsLightDirty();
  21557. },
  21558. enumerable: true,
  21559. configurable: true
  21560. });
  21561. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21562. /**
  21563. * Gets the only meshes impacted by this light.
  21564. */
  21565. get: function () {
  21566. return this._includedOnlyMeshes;
  21567. },
  21568. /**
  21569. * Sets the only meshes impacted by this light.
  21570. */
  21571. set: function (value) {
  21572. this._includedOnlyMeshes = value;
  21573. this._hookArrayForIncludedOnly(value);
  21574. },
  21575. enumerable: true,
  21576. configurable: true
  21577. });
  21578. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21579. /**
  21580. * Gets the meshes not impacted by this light.
  21581. */
  21582. get: function () {
  21583. return this._excludedMeshes;
  21584. },
  21585. /**
  21586. * Sets the meshes not impacted by this light.
  21587. */
  21588. set: function (value) {
  21589. this._excludedMeshes = value;
  21590. this._hookArrayForExcluded(value);
  21591. },
  21592. enumerable: true,
  21593. configurable: true
  21594. });
  21595. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21596. /**
  21597. * Gets the layer id use to find what meshes are not impacted by the light.
  21598. * Inactive if 0
  21599. */
  21600. get: function () {
  21601. return this._excludeWithLayerMask;
  21602. },
  21603. /**
  21604. * Sets the layer id use to find what meshes are not impacted by the light.
  21605. * Inactive if 0
  21606. */
  21607. set: function (value) {
  21608. this._excludeWithLayerMask = value;
  21609. this._resyncMeshes();
  21610. },
  21611. enumerable: true,
  21612. configurable: true
  21613. });
  21614. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21615. /**
  21616. * Gets the layer id use to find what meshes are impacted by the light.
  21617. * Inactive if 0
  21618. */
  21619. get: function () {
  21620. return this._includeOnlyWithLayerMask;
  21621. },
  21622. /**
  21623. * Sets the layer id use to find what meshes are impacted by the light.
  21624. * Inactive if 0
  21625. */
  21626. set: function (value) {
  21627. this._includeOnlyWithLayerMask = value;
  21628. this._resyncMeshes();
  21629. },
  21630. enumerable: true,
  21631. configurable: true
  21632. });
  21633. Object.defineProperty(Light.prototype, "lightmapMode", {
  21634. /**
  21635. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21636. */
  21637. get: function () {
  21638. return this._lightmapMode;
  21639. },
  21640. /**
  21641. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21642. */
  21643. set: function (value) {
  21644. if (this._lightmapMode === value) {
  21645. return;
  21646. }
  21647. this._lightmapMode = value;
  21648. this._markMeshesAsLightDirty();
  21649. },
  21650. enumerable: true,
  21651. configurable: true
  21652. });
  21653. /**
  21654. * Returns the string "Light".
  21655. * @returns the class name
  21656. */
  21657. Light.prototype.getClassName = function () {
  21658. return "Light";
  21659. };
  21660. /**
  21661. * Converts the light information to a readable string for debug purpose.
  21662. * @param fullDetails Supports for multiple levels of logging within scene loading
  21663. * @returns the human readable light info
  21664. */
  21665. Light.prototype.toString = function (fullDetails) {
  21666. var ret = "Name: " + this.name;
  21667. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21668. if (this.animations) {
  21669. for (var i = 0; i < this.animations.length; i++) {
  21670. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21671. }
  21672. }
  21673. if (fullDetails) {
  21674. }
  21675. return ret;
  21676. };
  21677. /**
  21678. * Set the enabled state of this node.
  21679. * @param value - the new enabled state
  21680. */
  21681. Light.prototype.setEnabled = function (value) {
  21682. _super.prototype.setEnabled.call(this, value);
  21683. this._resyncMeshes();
  21684. };
  21685. /**
  21686. * Returns the Light associated shadow generator if any.
  21687. * @return the associated shadow generator.
  21688. */
  21689. Light.prototype.getShadowGenerator = function () {
  21690. return this._shadowGenerator;
  21691. };
  21692. /**
  21693. * Returns a Vector3, the absolute light position in the World.
  21694. * @returns the world space position of the light
  21695. */
  21696. Light.prototype.getAbsolutePosition = function () {
  21697. return BABYLON.Vector3.Zero();
  21698. };
  21699. /**
  21700. * Specifies if the light will affect the passed mesh.
  21701. * @param mesh The mesh to test against the light
  21702. * @return true the mesh is affected otherwise, false.
  21703. */
  21704. Light.prototype.canAffectMesh = function (mesh) {
  21705. if (!mesh) {
  21706. return true;
  21707. }
  21708. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21709. return false;
  21710. }
  21711. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21712. return false;
  21713. }
  21714. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21715. return false;
  21716. }
  21717. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21718. return false;
  21719. }
  21720. return true;
  21721. };
  21722. /**
  21723. * Computes and Returns the light World matrix.
  21724. * @returns the world matrix
  21725. */
  21726. Light.prototype.getWorldMatrix = function () {
  21727. this._currentRenderId = this.getScene().getRenderId();
  21728. this._childRenderId = this._currentRenderId;
  21729. var worldMatrix = this._getWorldMatrix();
  21730. if (this.parent && this.parent.getWorldMatrix) {
  21731. if (!this._parentedWorldMatrix) {
  21732. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21733. }
  21734. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21735. this._markSyncedWithParent();
  21736. return this._parentedWorldMatrix;
  21737. }
  21738. return worldMatrix;
  21739. };
  21740. /**
  21741. * Sort function to order lights for rendering.
  21742. * @param a First Light object to compare to second.
  21743. * @param b Second Light object to compare first.
  21744. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21745. */
  21746. Light.CompareLightsPriority = function (a, b) {
  21747. //shadow-casting lights have priority over non-shadow-casting lights
  21748. //the renderPrioirty is a secondary sort criterion
  21749. if (a.shadowEnabled !== b.shadowEnabled) {
  21750. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21751. }
  21752. return b.renderPriority - a.renderPriority;
  21753. };
  21754. /**
  21755. * Releases resources associated with this node.
  21756. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21757. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21758. */
  21759. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21760. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21761. if (this._shadowGenerator) {
  21762. this._shadowGenerator.dispose();
  21763. this._shadowGenerator = null;
  21764. }
  21765. // Animations
  21766. this.getScene().stopAnimation(this);
  21767. // Remove from meshes
  21768. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21769. var mesh = _a[_i];
  21770. mesh._removeLightSource(this);
  21771. }
  21772. this._uniformBuffer.dispose();
  21773. // Remove from scene
  21774. this.getScene().removeLight(this);
  21775. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21776. };
  21777. /**
  21778. * Returns the light type ID (integer).
  21779. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21780. */
  21781. Light.prototype.getTypeID = function () {
  21782. return 0;
  21783. };
  21784. /**
  21785. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21786. * @returns the scaled intensity in intensity mode unit
  21787. */
  21788. Light.prototype.getScaledIntensity = function () {
  21789. return this._photometricScale * this.intensity;
  21790. };
  21791. /**
  21792. * Returns a new Light object, named "name", from the current one.
  21793. * @param name The name of the cloned light
  21794. * @returns the new created light
  21795. */
  21796. Light.prototype.clone = function (name) {
  21797. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21798. if (!constructor) {
  21799. return null;
  21800. }
  21801. return BABYLON.SerializationHelper.Clone(constructor, this);
  21802. };
  21803. /**
  21804. * Serializes the current light into a Serialization object.
  21805. * @returns the serialized object.
  21806. */
  21807. Light.prototype.serialize = function () {
  21808. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21809. // Type
  21810. serializationObject.type = this.getTypeID();
  21811. // Parent
  21812. if (this.parent) {
  21813. serializationObject.parentId = this.parent.id;
  21814. }
  21815. // Inclusion / exclusions
  21816. if (this.excludedMeshes.length > 0) {
  21817. serializationObject.excludedMeshesIds = [];
  21818. this.excludedMeshes.forEach(function (mesh) {
  21819. serializationObject.excludedMeshesIds.push(mesh.id);
  21820. });
  21821. }
  21822. if (this.includedOnlyMeshes.length > 0) {
  21823. serializationObject.includedOnlyMeshesIds = [];
  21824. this.includedOnlyMeshes.forEach(function (mesh) {
  21825. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21826. });
  21827. }
  21828. // Animations
  21829. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21830. serializationObject.ranges = this.serializeAnimationRanges();
  21831. return serializationObject;
  21832. };
  21833. /**
  21834. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21835. * This new light is named "name" and added to the passed scene.
  21836. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21837. * @param name The friendly name of the light
  21838. * @param scene The scene the new light will belong to
  21839. * @returns the constructor function
  21840. */
  21841. Light.GetConstructorFromName = function (type, name, scene) {
  21842. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21843. if (constructorFunc) {
  21844. return constructorFunc;
  21845. }
  21846. // Default to no light for none present once.
  21847. return null;
  21848. };
  21849. /**
  21850. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21851. * @param parsedLight The JSON representation of the light
  21852. * @param scene The scene to create the parsed light in
  21853. * @returns the created light after parsing
  21854. */
  21855. Light.Parse = function (parsedLight, scene) {
  21856. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21857. if (!constructor) {
  21858. return null;
  21859. }
  21860. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21861. // Inclusion / exclusions
  21862. if (parsedLight.excludedMeshesIds) {
  21863. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21864. }
  21865. if (parsedLight.includedOnlyMeshesIds) {
  21866. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21867. }
  21868. // Parent
  21869. if (parsedLight.parentId) {
  21870. light._waitingParentId = parsedLight.parentId;
  21871. }
  21872. // Animations
  21873. if (parsedLight.animations) {
  21874. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21875. var parsedAnimation = parsedLight.animations[animationIndex];
  21876. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21877. }
  21878. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21879. }
  21880. if (parsedLight.autoAnimate) {
  21881. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21882. }
  21883. return light;
  21884. };
  21885. Light.prototype._hookArrayForExcluded = function (array) {
  21886. var _this = this;
  21887. var oldPush = array.push;
  21888. array.push = function () {
  21889. var items = [];
  21890. for (var _i = 0; _i < arguments.length; _i++) {
  21891. items[_i] = arguments[_i];
  21892. }
  21893. var result = oldPush.apply(array, items);
  21894. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21895. var item = items_1[_a];
  21896. item._resyncLighSource(_this);
  21897. }
  21898. return result;
  21899. };
  21900. var oldSplice = array.splice;
  21901. array.splice = function (index, deleteCount) {
  21902. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21903. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21904. var item = deleted_1[_i];
  21905. item._resyncLighSource(_this);
  21906. }
  21907. return deleted;
  21908. };
  21909. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21910. var item = array_1[_i];
  21911. item._resyncLighSource(this);
  21912. }
  21913. };
  21914. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21915. var _this = this;
  21916. var oldPush = array.push;
  21917. array.push = function () {
  21918. var items = [];
  21919. for (var _i = 0; _i < arguments.length; _i++) {
  21920. items[_i] = arguments[_i];
  21921. }
  21922. var result = oldPush.apply(array, items);
  21923. _this._resyncMeshes();
  21924. return result;
  21925. };
  21926. var oldSplice = array.splice;
  21927. array.splice = function (index, deleteCount) {
  21928. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21929. _this._resyncMeshes();
  21930. return deleted;
  21931. };
  21932. this._resyncMeshes();
  21933. };
  21934. Light.prototype._resyncMeshes = function () {
  21935. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21936. var mesh = _a[_i];
  21937. mesh._resyncLighSource(this);
  21938. }
  21939. };
  21940. /**
  21941. * Forces the meshes to update their light related information in their rendering used effects
  21942. * @hidden Internal Use Only
  21943. */
  21944. Light.prototype._markMeshesAsLightDirty = function () {
  21945. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21946. var mesh = _a[_i];
  21947. if (mesh._lightSources.indexOf(this) !== -1) {
  21948. mesh._markSubMeshesAsLightDirty();
  21949. }
  21950. }
  21951. };
  21952. /**
  21953. * Recomputes the cached photometric scale if needed.
  21954. */
  21955. Light.prototype._computePhotometricScale = function () {
  21956. this._photometricScale = this._getPhotometricScale();
  21957. this.getScene().resetCachedMaterial();
  21958. };
  21959. /**
  21960. * Returns the Photometric Scale according to the light type and intensity mode.
  21961. */
  21962. Light.prototype._getPhotometricScale = function () {
  21963. var photometricScale = 0.0;
  21964. var lightTypeID = this.getTypeID();
  21965. //get photometric mode
  21966. var photometricMode = this.intensityMode;
  21967. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21968. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21969. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21970. }
  21971. else {
  21972. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21973. }
  21974. }
  21975. //compute photometric scale
  21976. switch (lightTypeID) {
  21977. case Light.LIGHTTYPEID_POINTLIGHT:
  21978. case Light.LIGHTTYPEID_SPOTLIGHT:
  21979. switch (photometricMode) {
  21980. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21981. photometricScale = 1.0 / (4.0 * Math.PI);
  21982. break;
  21983. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21984. photometricScale = 1.0;
  21985. break;
  21986. case Light.INTENSITYMODE_LUMINANCE:
  21987. photometricScale = this.radius * this.radius;
  21988. break;
  21989. }
  21990. break;
  21991. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21992. switch (photometricMode) {
  21993. case Light.INTENSITYMODE_ILLUMINANCE:
  21994. photometricScale = 1.0;
  21995. break;
  21996. case Light.INTENSITYMODE_LUMINANCE:
  21997. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21998. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21999. var apexAngleRadians = this.radius;
  22000. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22001. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22002. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22003. photometricScale = solidAngle;
  22004. break;
  22005. }
  22006. break;
  22007. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22008. // No fall off in hemisperic light.
  22009. photometricScale = 1.0;
  22010. break;
  22011. }
  22012. return photometricScale;
  22013. };
  22014. /**
  22015. * Reorder the light in the scene according to their defined priority.
  22016. * @hidden Internal Use Only
  22017. */
  22018. Light.prototype._reorderLightsInScene = function () {
  22019. var scene = this.getScene();
  22020. if (this._renderPriority != 0) {
  22021. scene.requireLightSorting = true;
  22022. }
  22023. this.getScene().sortLightsByPriority();
  22024. };
  22025. /**
  22026. * Falloff Default: light is falling off following the material specification:
  22027. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22028. */
  22029. Light.FALLOFF_DEFAULT = 0;
  22030. /**
  22031. * Falloff Physical: light is falling off following the inverse squared distance law.
  22032. */
  22033. Light.FALLOFF_PHYSICAL = 1;
  22034. /**
  22035. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22036. * to enhance interoperability with other engines.
  22037. */
  22038. Light.FALLOFF_GLTF = 2;
  22039. /**
  22040. * Falloff Standard: light is falling off like in the standard material
  22041. * to enhance interoperability with other materials.
  22042. */
  22043. Light.FALLOFF_STANDARD = 3;
  22044. //lightmapMode Consts
  22045. /**
  22046. * If every light affecting the material is in this lightmapMode,
  22047. * material.lightmapTexture adds or multiplies
  22048. * (depends on material.useLightmapAsShadowmap)
  22049. * after every other light calculations.
  22050. */
  22051. Light.LIGHTMAP_DEFAULT = 0;
  22052. /**
  22053. * material.lightmapTexture as only diffuse lighting from this light
  22054. * adds only specular lighting from this light
  22055. * adds dynamic shadows
  22056. */
  22057. Light.LIGHTMAP_SPECULAR = 1;
  22058. /**
  22059. * material.lightmapTexture as only lighting
  22060. * no light calculation from this light
  22061. * only adds dynamic shadows from this light
  22062. */
  22063. Light.LIGHTMAP_SHADOWSONLY = 2;
  22064. // Intensity Mode Consts
  22065. /**
  22066. * Each light type uses the default quantity according to its type:
  22067. * point/spot lights use luminous intensity
  22068. * directional lights use illuminance
  22069. */
  22070. Light.INTENSITYMODE_AUTOMATIC = 0;
  22071. /**
  22072. * lumen (lm)
  22073. */
  22074. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22075. /**
  22076. * candela (lm/sr)
  22077. */
  22078. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22079. /**
  22080. * lux (lm/m^2)
  22081. */
  22082. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22083. /**
  22084. * nit (cd/m^2)
  22085. */
  22086. Light.INTENSITYMODE_LUMINANCE = 4;
  22087. // Light types ids const.
  22088. /**
  22089. * Light type const id of the point light.
  22090. */
  22091. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22092. /**
  22093. * Light type const id of the directional light.
  22094. */
  22095. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22096. /**
  22097. * Light type const id of the spot light.
  22098. */
  22099. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22100. /**
  22101. * Light type const id of the hemispheric light.
  22102. */
  22103. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22104. __decorate([
  22105. BABYLON.serializeAsColor3()
  22106. ], Light.prototype, "diffuse", void 0);
  22107. __decorate([
  22108. BABYLON.serializeAsColor3()
  22109. ], Light.prototype, "specular", void 0);
  22110. __decorate([
  22111. BABYLON.serialize()
  22112. ], Light.prototype, "falloffType", void 0);
  22113. __decorate([
  22114. BABYLON.serialize()
  22115. ], Light.prototype, "intensity", void 0);
  22116. __decorate([
  22117. BABYLON.serialize()
  22118. ], Light.prototype, "range", null);
  22119. __decorate([
  22120. BABYLON.serialize()
  22121. ], Light.prototype, "intensityMode", null);
  22122. __decorate([
  22123. BABYLON.serialize()
  22124. ], Light.prototype, "radius", null);
  22125. __decorate([
  22126. BABYLON.serialize()
  22127. ], Light.prototype, "_renderPriority", void 0);
  22128. __decorate([
  22129. BABYLON.expandToProperty("_reorderLightsInScene")
  22130. ], Light.prototype, "renderPriority", void 0);
  22131. __decorate([
  22132. BABYLON.serialize("shadowEnabled")
  22133. ], Light.prototype, "_shadowEnabled", void 0);
  22134. __decorate([
  22135. BABYLON.serialize("excludeWithLayerMask")
  22136. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22137. __decorate([
  22138. BABYLON.serialize("includeOnlyWithLayerMask")
  22139. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22140. __decorate([
  22141. BABYLON.serialize("lightmapMode")
  22142. ], Light.prototype, "_lightmapMode", void 0);
  22143. return Light;
  22144. }(BABYLON.Node));
  22145. BABYLON.Light = Light;
  22146. })(BABYLON || (BABYLON = {}));
  22147. //# sourceMappingURL=babylon.light.js.map
  22148. var BABYLON;
  22149. (function (BABYLON) {
  22150. var Camera = /** @class */ (function (_super) {
  22151. __extends(Camera, _super);
  22152. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22153. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22154. var _this = _super.call(this, name, scene) || this;
  22155. /**
  22156. * The vector the camera should consider as up.
  22157. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22158. */
  22159. _this.upVector = BABYLON.Vector3.Up();
  22160. _this.orthoLeft = null;
  22161. _this.orthoRight = null;
  22162. _this.orthoBottom = null;
  22163. _this.orthoTop = null;
  22164. /**
  22165. * FOV is set in Radians. (default is 0.8)
  22166. */
  22167. _this.fov = 0.8;
  22168. _this.minZ = 1;
  22169. _this.maxZ = 10000.0;
  22170. _this.inertia = 0.9;
  22171. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22172. _this.isIntermediate = false;
  22173. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22174. /**
  22175. * Restricts the camera to viewing objects with the same layerMask.
  22176. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22177. */
  22178. _this.layerMask = 0x0FFFFFFF;
  22179. /**
  22180. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22181. */
  22182. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22183. // Camera rig members
  22184. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22185. /** @hidden */
  22186. _this._rigCameras = new Array();
  22187. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22188. /** @hidden */
  22189. _this._skipRendering = false;
  22190. _this.customRenderTargets = new Array();
  22191. // Observables
  22192. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22193. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22194. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22195. _this.onRestoreStateObservable = new BABYLON.Observable();
  22196. // Cache
  22197. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22198. _this._projectionMatrix = new BABYLON.Matrix();
  22199. _this._doNotComputeProjectionMatrix = false;
  22200. _this._worldMatrix = BABYLON.Matrix.Identity();
  22201. _this._postProcesses = new Array();
  22202. _this._transformMatrix = BABYLON.Matrix.Zero();
  22203. _this._activeMeshes = new BABYLON.SmartArray(256);
  22204. _this._globalPosition = BABYLON.Vector3.Zero();
  22205. _this._refreshFrustumPlanes = true;
  22206. _this.getScene().addCamera(_this);
  22207. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22208. _this.getScene().activeCamera = _this;
  22209. }
  22210. _this.position = position;
  22211. return _this;
  22212. }
  22213. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22214. get: function () {
  22215. return Camera._PERSPECTIVE_CAMERA;
  22216. },
  22217. enumerable: true,
  22218. configurable: true
  22219. });
  22220. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22221. get: function () {
  22222. return Camera._ORTHOGRAPHIC_CAMERA;
  22223. },
  22224. enumerable: true,
  22225. configurable: true
  22226. });
  22227. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22228. /**
  22229. * This is the default FOV mode for perspective cameras.
  22230. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22231. *
  22232. */
  22233. get: function () {
  22234. return Camera._FOVMODE_VERTICAL_FIXED;
  22235. },
  22236. enumerable: true,
  22237. configurable: true
  22238. });
  22239. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22240. /**
  22241. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22242. *
  22243. */
  22244. get: function () {
  22245. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22246. },
  22247. enumerable: true,
  22248. configurable: true
  22249. });
  22250. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22251. get: function () {
  22252. return Camera._RIG_MODE_NONE;
  22253. },
  22254. enumerable: true,
  22255. configurable: true
  22256. });
  22257. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22258. get: function () {
  22259. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22265. get: function () {
  22266. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22272. get: function () {
  22273. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22274. },
  22275. enumerable: true,
  22276. configurable: true
  22277. });
  22278. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22279. get: function () {
  22280. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22281. },
  22282. enumerable: true,
  22283. configurable: true
  22284. });
  22285. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22286. get: function () {
  22287. return Camera._RIG_MODE_VR;
  22288. },
  22289. enumerable: true,
  22290. configurable: true
  22291. });
  22292. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22293. get: function () {
  22294. return Camera._RIG_MODE_WEBVR;
  22295. },
  22296. enumerable: true,
  22297. configurable: true
  22298. });
  22299. /**
  22300. * Store current camera state (fov, position, etc..)
  22301. */
  22302. Camera.prototype.storeState = function () {
  22303. this._stateStored = true;
  22304. this._storedFov = this.fov;
  22305. return this;
  22306. };
  22307. /**
  22308. * Restores the camera state values if it has been stored. You must call storeState() first
  22309. */
  22310. Camera.prototype._restoreStateValues = function () {
  22311. if (!this._stateStored) {
  22312. return false;
  22313. }
  22314. this.fov = this._storedFov;
  22315. return true;
  22316. };
  22317. /**
  22318. * Restored camera state. You must call storeState() first
  22319. */
  22320. Camera.prototype.restoreState = function () {
  22321. if (this._restoreStateValues()) {
  22322. this.onRestoreStateObservable.notifyObservers(this);
  22323. return true;
  22324. }
  22325. return false;
  22326. };
  22327. Camera.prototype.getClassName = function () {
  22328. return "Camera";
  22329. };
  22330. /**
  22331. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22332. */
  22333. Camera.prototype.toString = function (fullDetails) {
  22334. var ret = "Name: " + this.name;
  22335. ret += ", type: " + this.getClassName();
  22336. if (this.animations) {
  22337. for (var i = 0; i < this.animations.length; i++) {
  22338. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22339. }
  22340. }
  22341. if (fullDetails) {
  22342. }
  22343. return ret;
  22344. };
  22345. Object.defineProperty(Camera.prototype, "globalPosition", {
  22346. get: function () {
  22347. return this._globalPosition;
  22348. },
  22349. enumerable: true,
  22350. configurable: true
  22351. });
  22352. Camera.prototype.getActiveMeshes = function () {
  22353. return this._activeMeshes;
  22354. };
  22355. Camera.prototype.isActiveMesh = function (mesh) {
  22356. return (this._activeMeshes.indexOf(mesh) !== -1);
  22357. };
  22358. /**
  22359. * Is this camera ready to be used/rendered
  22360. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22361. * @return true if the camera is ready
  22362. */
  22363. Camera.prototype.isReady = function (completeCheck) {
  22364. if (completeCheck === void 0) { completeCheck = false; }
  22365. if (completeCheck) {
  22366. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22367. var pp = _a[_i];
  22368. if (pp && !pp.isReady()) {
  22369. return false;
  22370. }
  22371. }
  22372. }
  22373. return _super.prototype.isReady.call(this, completeCheck);
  22374. };
  22375. //Cache
  22376. /** @hidden */
  22377. Camera.prototype._initCache = function () {
  22378. _super.prototype._initCache.call(this);
  22379. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22380. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22381. this._cache.mode = undefined;
  22382. this._cache.minZ = undefined;
  22383. this._cache.maxZ = undefined;
  22384. this._cache.fov = undefined;
  22385. this._cache.fovMode = undefined;
  22386. this._cache.aspectRatio = undefined;
  22387. this._cache.orthoLeft = undefined;
  22388. this._cache.orthoRight = undefined;
  22389. this._cache.orthoBottom = undefined;
  22390. this._cache.orthoTop = undefined;
  22391. this._cache.renderWidth = undefined;
  22392. this._cache.renderHeight = undefined;
  22393. };
  22394. /** @hidden */
  22395. Camera.prototype._updateCache = function (ignoreParentClass) {
  22396. if (!ignoreParentClass) {
  22397. _super.prototype._updateCache.call(this);
  22398. }
  22399. this._cache.position.copyFrom(this.position);
  22400. this._cache.upVector.copyFrom(this.upVector);
  22401. };
  22402. // Synchronized
  22403. /** @hidden */
  22404. Camera.prototype._isSynchronized = function () {
  22405. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22406. };
  22407. /** @hidden */
  22408. Camera.prototype._isSynchronizedViewMatrix = function () {
  22409. if (!_super.prototype._isSynchronized.call(this))
  22410. return false;
  22411. return this._cache.position.equals(this.position)
  22412. && this._cache.upVector.equals(this.upVector)
  22413. && this.isSynchronizedWithParent();
  22414. };
  22415. /** @hidden */
  22416. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22417. var check = this._cache.mode === this.mode
  22418. && this._cache.minZ === this.minZ
  22419. && this._cache.maxZ === this.maxZ;
  22420. if (!check) {
  22421. return false;
  22422. }
  22423. var engine = this.getEngine();
  22424. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22425. check = this._cache.fov === this.fov
  22426. && this._cache.fovMode === this.fovMode
  22427. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22428. }
  22429. else {
  22430. check = this._cache.orthoLeft === this.orthoLeft
  22431. && this._cache.orthoRight === this.orthoRight
  22432. && this._cache.orthoBottom === this.orthoBottom
  22433. && this._cache.orthoTop === this.orthoTop
  22434. && this._cache.renderWidth === engine.getRenderWidth()
  22435. && this._cache.renderHeight === engine.getRenderHeight();
  22436. }
  22437. return check;
  22438. };
  22439. // Controls
  22440. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22441. };
  22442. Camera.prototype.detachControl = function (element) {
  22443. };
  22444. Camera.prototype.update = function () {
  22445. this._checkInputs();
  22446. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22447. this._updateRigCameras();
  22448. }
  22449. };
  22450. /** @hidden */
  22451. Camera.prototype._checkInputs = function () {
  22452. this.onAfterCheckInputsObservable.notifyObservers(this);
  22453. };
  22454. Object.defineProperty(Camera.prototype, "rigCameras", {
  22455. get: function () {
  22456. return this._rigCameras;
  22457. },
  22458. enumerable: true,
  22459. configurable: true
  22460. });
  22461. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22462. get: function () {
  22463. return this._rigPostProcess;
  22464. },
  22465. enumerable: true,
  22466. configurable: true
  22467. });
  22468. /**
  22469. * Internal, gets the first post proces.
  22470. * @returns the first post process to be run on this camera.
  22471. */
  22472. Camera.prototype._getFirstPostProcess = function () {
  22473. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22474. if (this._postProcesses[ppIndex] !== null) {
  22475. return this._postProcesses[ppIndex];
  22476. }
  22477. }
  22478. return null;
  22479. };
  22480. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22481. // invalidate framebuffer
  22482. var firstPostProcess = this._getFirstPostProcess();
  22483. if (firstPostProcess) {
  22484. firstPostProcess.markTextureDirty();
  22485. }
  22486. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22487. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22488. var cam = this._rigCameras[i];
  22489. var rigPostProcess = cam._rigPostProcess;
  22490. // for VR rig, there does not have to be a post process
  22491. if (rigPostProcess) {
  22492. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22493. if (isPass) {
  22494. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22495. cam.isIntermediate = this._postProcesses.length === 0;
  22496. }
  22497. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22498. rigPostProcess.markTextureDirty();
  22499. }
  22500. else {
  22501. cam._postProcesses = this._postProcesses.slice(0);
  22502. }
  22503. }
  22504. };
  22505. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22506. if (insertAt === void 0) { insertAt = null; }
  22507. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22508. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22509. return 0;
  22510. }
  22511. if (insertAt == null || insertAt < 0) {
  22512. this._postProcesses.push(postProcess);
  22513. }
  22514. else if (this._postProcesses[insertAt] === null) {
  22515. this._postProcesses[insertAt] = postProcess;
  22516. }
  22517. else {
  22518. this._postProcesses.splice(insertAt, 0, postProcess);
  22519. }
  22520. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22521. return this._postProcesses.indexOf(postProcess);
  22522. };
  22523. Camera.prototype.detachPostProcess = function (postProcess) {
  22524. var idx = this._postProcesses.indexOf(postProcess);
  22525. if (idx !== -1) {
  22526. this._postProcesses[idx] = null;
  22527. }
  22528. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22529. };
  22530. Camera.prototype.getWorldMatrix = function () {
  22531. if (this._isSynchronizedViewMatrix()) {
  22532. return this._worldMatrix;
  22533. }
  22534. // Getting the the view matrix will also compute the world matrix.
  22535. this.getViewMatrix();
  22536. return this._worldMatrix;
  22537. };
  22538. /** @hidden */
  22539. Camera.prototype._getViewMatrix = function () {
  22540. return BABYLON.Matrix.Identity();
  22541. };
  22542. Camera.prototype.getViewMatrix = function (force) {
  22543. if (!force && this._isSynchronizedViewMatrix()) {
  22544. return this._computedViewMatrix;
  22545. }
  22546. this.updateCache();
  22547. this._computedViewMatrix = this._getViewMatrix();
  22548. this._currentRenderId = this.getScene().getRenderId();
  22549. this._childRenderId = this._currentRenderId;
  22550. this._refreshFrustumPlanes = true;
  22551. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22552. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22553. }
  22554. this.onViewMatrixChangedObservable.notifyObservers(this);
  22555. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22556. return this._computedViewMatrix;
  22557. };
  22558. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22559. this._doNotComputeProjectionMatrix = true;
  22560. if (projection !== undefined) {
  22561. this._projectionMatrix = projection;
  22562. }
  22563. };
  22564. ;
  22565. Camera.prototype.unfreezeProjectionMatrix = function () {
  22566. this._doNotComputeProjectionMatrix = false;
  22567. };
  22568. ;
  22569. Camera.prototype.getProjectionMatrix = function (force) {
  22570. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22571. return this._projectionMatrix;
  22572. }
  22573. // Cache
  22574. this._cache.mode = this.mode;
  22575. this._cache.minZ = this.minZ;
  22576. this._cache.maxZ = this.maxZ;
  22577. // Matrix
  22578. this._refreshFrustumPlanes = true;
  22579. var engine = this.getEngine();
  22580. var scene = this.getScene();
  22581. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22582. this._cache.fov = this.fov;
  22583. this._cache.fovMode = this.fovMode;
  22584. this._cache.aspectRatio = engine.getAspectRatio(this);
  22585. if (this.minZ <= 0) {
  22586. this.minZ = 0.1;
  22587. }
  22588. if (scene.useRightHandedSystem) {
  22589. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22590. }
  22591. else {
  22592. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22593. }
  22594. }
  22595. else {
  22596. var halfWidth = engine.getRenderWidth() / 2.0;
  22597. var halfHeight = engine.getRenderHeight() / 2.0;
  22598. if (scene.useRightHandedSystem) {
  22599. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22600. }
  22601. else {
  22602. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22603. }
  22604. this._cache.orthoLeft = this.orthoLeft;
  22605. this._cache.orthoRight = this.orthoRight;
  22606. this._cache.orthoBottom = this.orthoBottom;
  22607. this._cache.orthoTop = this.orthoTop;
  22608. this._cache.renderWidth = engine.getRenderWidth();
  22609. this._cache.renderHeight = engine.getRenderHeight();
  22610. }
  22611. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22612. return this._projectionMatrix;
  22613. };
  22614. /**
  22615. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22616. * @returns a Matrix
  22617. */
  22618. Camera.prototype.getTransformationMatrix = function () {
  22619. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22620. return this._transformMatrix;
  22621. };
  22622. Camera.prototype.updateFrustumPlanes = function () {
  22623. if (!this._refreshFrustumPlanes) {
  22624. return;
  22625. }
  22626. this.getTransformationMatrix();
  22627. if (!this._frustumPlanes) {
  22628. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22629. }
  22630. else {
  22631. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22632. }
  22633. this._refreshFrustumPlanes = false;
  22634. };
  22635. Camera.prototype.isInFrustum = function (target) {
  22636. this.updateFrustumPlanes();
  22637. return target.isInFrustum(this._frustumPlanes);
  22638. };
  22639. Camera.prototype.isCompletelyInFrustum = function (target) {
  22640. this.updateFrustumPlanes();
  22641. return target.isCompletelyInFrustum(this._frustumPlanes);
  22642. };
  22643. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22644. if (length === void 0) { length = 100; }
  22645. if (!transform) {
  22646. transform = this.getWorldMatrix();
  22647. }
  22648. if (!origin) {
  22649. origin = this.position;
  22650. }
  22651. var forward = new BABYLON.Vector3(0, 0, 1);
  22652. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22653. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22654. return new BABYLON.Ray(origin, direction, length);
  22655. };
  22656. /**
  22657. * Releases resources associated with this node.
  22658. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22659. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22660. */
  22661. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22662. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22663. // Observables
  22664. this.onViewMatrixChangedObservable.clear();
  22665. this.onProjectionMatrixChangedObservable.clear();
  22666. this.onAfterCheckInputsObservable.clear();
  22667. this.onRestoreStateObservable.clear();
  22668. // Inputs
  22669. if (this.inputs) {
  22670. this.inputs.clear();
  22671. }
  22672. // Animations
  22673. this.getScene().stopAnimation(this);
  22674. // Remove from scene
  22675. this.getScene().removeCamera(this);
  22676. while (this._rigCameras.length > 0) {
  22677. var camera = this._rigCameras.pop();
  22678. if (camera) {
  22679. camera.dispose();
  22680. }
  22681. }
  22682. // Postprocesses
  22683. if (this._rigPostProcess) {
  22684. this._rigPostProcess.dispose(this);
  22685. this._rigPostProcess = null;
  22686. this._postProcesses = [];
  22687. }
  22688. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22689. this._rigPostProcess = null;
  22690. this._postProcesses = [];
  22691. }
  22692. else {
  22693. var i = this._postProcesses.length;
  22694. while (--i >= 0) {
  22695. var postProcess = this._postProcesses[i];
  22696. if (postProcess) {
  22697. postProcess.dispose(this);
  22698. }
  22699. }
  22700. }
  22701. // Render targets
  22702. var i = this.customRenderTargets.length;
  22703. while (--i >= 0) {
  22704. this.customRenderTargets[i].dispose();
  22705. }
  22706. this.customRenderTargets = [];
  22707. // Active Meshes
  22708. this._activeMeshes.dispose();
  22709. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22710. };
  22711. Object.defineProperty(Camera.prototype, "leftCamera", {
  22712. // ---- Camera rigs section ----
  22713. get: function () {
  22714. if (this._rigCameras.length < 1) {
  22715. return null;
  22716. }
  22717. return this._rigCameras[0];
  22718. },
  22719. enumerable: true,
  22720. configurable: true
  22721. });
  22722. Object.defineProperty(Camera.prototype, "rightCamera", {
  22723. get: function () {
  22724. if (this._rigCameras.length < 2) {
  22725. return null;
  22726. }
  22727. return this._rigCameras[1];
  22728. },
  22729. enumerable: true,
  22730. configurable: true
  22731. });
  22732. Camera.prototype.getLeftTarget = function () {
  22733. if (this._rigCameras.length < 1) {
  22734. return null;
  22735. }
  22736. return this._rigCameras[0].getTarget();
  22737. };
  22738. Camera.prototype.getRightTarget = function () {
  22739. if (this._rigCameras.length < 2) {
  22740. return null;
  22741. }
  22742. return this._rigCameras[1].getTarget();
  22743. };
  22744. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22745. if (this.cameraRigMode === mode) {
  22746. return;
  22747. }
  22748. while (this._rigCameras.length > 0) {
  22749. var camera = this._rigCameras.pop();
  22750. if (camera) {
  22751. camera.dispose();
  22752. }
  22753. }
  22754. this.cameraRigMode = mode;
  22755. this._cameraRigParams = {};
  22756. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22757. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22758. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22759. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22760. // create the rig cameras, unless none
  22761. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22762. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22763. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22764. if (leftCamera && rightCamera) {
  22765. this._rigCameras.push(leftCamera);
  22766. this._rigCameras.push(rightCamera);
  22767. }
  22768. }
  22769. switch (this.cameraRigMode) {
  22770. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22771. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22772. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22773. break;
  22774. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22775. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22776. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22777. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22778. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22779. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22780. break;
  22781. case Camera.RIG_MODE_VR:
  22782. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22783. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22784. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22785. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22786. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22787. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22788. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22789. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22790. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22791. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22792. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22793. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22794. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22795. if (metrics.compensateDistortion) {
  22796. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22797. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22798. }
  22799. break;
  22800. case Camera.RIG_MODE_WEBVR:
  22801. if (rigParams.vrDisplay) {
  22802. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22803. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22804. //Left eye
  22805. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22806. this._rigCameras[0].setCameraRigParameter("left", true);
  22807. //leaving this for future reference
  22808. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22809. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22810. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22811. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22812. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22813. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22814. this._rigCameras[0].parent = this;
  22815. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22816. //Right eye
  22817. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22818. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22819. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22820. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22821. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22822. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22823. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22824. this._rigCameras[1].parent = this;
  22825. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22826. if (Camera.UseAlternateWebVRRendering) {
  22827. this._rigCameras[1]._skipRendering = true;
  22828. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22829. }
  22830. }
  22831. break;
  22832. }
  22833. this._cascadePostProcessesToRigCams();
  22834. this.update();
  22835. };
  22836. Camera.prototype._getVRProjectionMatrix = function () {
  22837. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22838. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22839. return this._projectionMatrix;
  22840. };
  22841. Camera.prototype._updateCameraRotationMatrix = function () {
  22842. //Here for WebVR
  22843. };
  22844. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22845. //Here for WebVR
  22846. };
  22847. /**
  22848. * This function MUST be overwritten by the different WebVR cameras available.
  22849. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22850. */
  22851. Camera.prototype._getWebVRProjectionMatrix = function () {
  22852. return BABYLON.Matrix.Identity();
  22853. };
  22854. /**
  22855. * This function MUST be overwritten by the different WebVR cameras available.
  22856. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22857. */
  22858. Camera.prototype._getWebVRViewMatrix = function () {
  22859. return BABYLON.Matrix.Identity();
  22860. };
  22861. Camera.prototype.setCameraRigParameter = function (name, value) {
  22862. if (!this._cameraRigParams) {
  22863. this._cameraRigParams = {};
  22864. }
  22865. this._cameraRigParams[name] = value;
  22866. //provisionnally:
  22867. if (name === "interaxialDistance") {
  22868. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22869. }
  22870. };
  22871. /**
  22872. * needs to be overridden by children so sub has required properties to be copied
  22873. */
  22874. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22875. return null;
  22876. };
  22877. /**
  22878. * May need to be overridden by children
  22879. * @hidden
  22880. */
  22881. Camera.prototype._updateRigCameras = function () {
  22882. for (var i = 0; i < this._rigCameras.length; i++) {
  22883. this._rigCameras[i].minZ = this.minZ;
  22884. this._rigCameras[i].maxZ = this.maxZ;
  22885. this._rigCameras[i].fov = this.fov;
  22886. }
  22887. // only update viewport when ANAGLYPH
  22888. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22889. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22890. }
  22891. };
  22892. /** @hidden */
  22893. Camera.prototype._setupInputs = function () {
  22894. };
  22895. Camera.prototype.serialize = function () {
  22896. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22897. // Type
  22898. serializationObject.type = this.getClassName();
  22899. // Parent
  22900. if (this.parent) {
  22901. serializationObject.parentId = this.parent.id;
  22902. }
  22903. if (this.inputs) {
  22904. this.inputs.serialize(serializationObject);
  22905. }
  22906. // Animations
  22907. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22908. serializationObject.ranges = this.serializeAnimationRanges();
  22909. return serializationObject;
  22910. };
  22911. Camera.prototype.clone = function (name) {
  22912. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22913. };
  22914. Camera.prototype.getDirection = function (localAxis) {
  22915. var result = BABYLON.Vector3.Zero();
  22916. this.getDirectionToRef(localAxis, result);
  22917. return result;
  22918. };
  22919. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22920. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22921. };
  22922. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22923. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22924. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22925. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22926. interaxial_distance: interaxial_distance,
  22927. isStereoscopicSideBySide: isStereoscopicSideBySide
  22928. });
  22929. if (constructorFunc) {
  22930. return constructorFunc;
  22931. }
  22932. // Default to universal camera
  22933. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22934. };
  22935. Camera.prototype.computeWorldMatrix = function () {
  22936. return this.getWorldMatrix();
  22937. };
  22938. Camera.Parse = function (parsedCamera, scene) {
  22939. var type = parsedCamera.type;
  22940. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22941. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22942. // Parent
  22943. if (parsedCamera.parentId) {
  22944. camera._waitingParentId = parsedCamera.parentId;
  22945. }
  22946. //If camera has an input manager, let it parse inputs settings
  22947. if (camera.inputs) {
  22948. camera.inputs.parse(parsedCamera);
  22949. camera._setupInputs();
  22950. }
  22951. if (camera.setPosition) { // need to force position
  22952. camera.position.copyFromFloats(0, 0, 0);
  22953. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22954. }
  22955. // Target
  22956. if (parsedCamera.target) {
  22957. if (camera.setTarget) {
  22958. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22959. }
  22960. }
  22961. // Apply 3d rig, when found
  22962. if (parsedCamera.cameraRigMode) {
  22963. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22964. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22965. }
  22966. // Animations
  22967. if (parsedCamera.animations) {
  22968. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22969. var parsedAnimation = parsedCamera.animations[animationIndex];
  22970. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22971. }
  22972. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22973. }
  22974. if (parsedCamera.autoAnimate) {
  22975. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22976. }
  22977. return camera;
  22978. };
  22979. // Statics
  22980. Camera._PERSPECTIVE_CAMERA = 0;
  22981. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22982. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22983. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22984. Camera._RIG_MODE_NONE = 0;
  22985. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22986. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22987. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22988. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22989. Camera._RIG_MODE_VR = 20;
  22990. Camera._RIG_MODE_WEBVR = 21;
  22991. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22992. Camera.UseAlternateWebVRRendering = false;
  22993. __decorate([
  22994. BABYLON.serializeAsVector3()
  22995. ], Camera.prototype, "position", void 0);
  22996. __decorate([
  22997. BABYLON.serializeAsVector3()
  22998. ], Camera.prototype, "upVector", void 0);
  22999. __decorate([
  23000. BABYLON.serialize()
  23001. ], Camera.prototype, "orthoLeft", void 0);
  23002. __decorate([
  23003. BABYLON.serialize()
  23004. ], Camera.prototype, "orthoRight", void 0);
  23005. __decorate([
  23006. BABYLON.serialize()
  23007. ], Camera.prototype, "orthoBottom", void 0);
  23008. __decorate([
  23009. BABYLON.serialize()
  23010. ], Camera.prototype, "orthoTop", void 0);
  23011. __decorate([
  23012. BABYLON.serialize()
  23013. ], Camera.prototype, "fov", void 0);
  23014. __decorate([
  23015. BABYLON.serialize()
  23016. ], Camera.prototype, "minZ", void 0);
  23017. __decorate([
  23018. BABYLON.serialize()
  23019. ], Camera.prototype, "maxZ", void 0);
  23020. __decorate([
  23021. BABYLON.serialize()
  23022. ], Camera.prototype, "inertia", void 0);
  23023. __decorate([
  23024. BABYLON.serialize()
  23025. ], Camera.prototype, "mode", void 0);
  23026. __decorate([
  23027. BABYLON.serialize()
  23028. ], Camera.prototype, "layerMask", void 0);
  23029. __decorate([
  23030. BABYLON.serialize()
  23031. ], Camera.prototype, "fovMode", void 0);
  23032. __decorate([
  23033. BABYLON.serialize()
  23034. ], Camera.prototype, "cameraRigMode", void 0);
  23035. __decorate([
  23036. BABYLON.serialize()
  23037. ], Camera.prototype, "interaxialDistance", void 0);
  23038. __decorate([
  23039. BABYLON.serialize()
  23040. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23041. return Camera;
  23042. }(BABYLON.Node));
  23043. BABYLON.Camera = Camera;
  23044. })(BABYLON || (BABYLON = {}));
  23045. //# sourceMappingURL=babylon.camera.js.map
  23046. var BABYLON;
  23047. (function (BABYLON) {
  23048. var RenderingManager = /** @class */ (function () {
  23049. function RenderingManager(scene) {
  23050. /**
  23051. * @hidden
  23052. */
  23053. this._useSceneAutoClearSetup = false;
  23054. this._renderingGroups = new Array();
  23055. this._autoClearDepthStencil = {};
  23056. this._customOpaqueSortCompareFn = {};
  23057. this._customAlphaTestSortCompareFn = {};
  23058. this._customTransparentSortCompareFn = {};
  23059. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23060. this._scene = scene;
  23061. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23062. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23063. }
  23064. }
  23065. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23066. if (depth === void 0) { depth = true; }
  23067. if (stencil === void 0) { stencil = true; }
  23068. if (this._depthStencilBufferAlreadyCleaned) {
  23069. return;
  23070. }
  23071. this._scene.getEngine().clear(null, false, depth, stencil);
  23072. this._depthStencilBufferAlreadyCleaned = true;
  23073. };
  23074. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23075. // Update the observable context (not null as it only goes away on dispose)
  23076. var info = this._renderingGroupInfo;
  23077. info.scene = this._scene;
  23078. info.camera = this._scene.activeCamera;
  23079. // Dispatch sprites
  23080. if (renderSprites) {
  23081. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23082. var manager = this._scene.spriteManagers[index];
  23083. this.dispatchSprites(manager);
  23084. }
  23085. }
  23086. // Render
  23087. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23088. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23089. var renderingGroup = this._renderingGroups[index];
  23090. if (!renderingGroup)
  23091. continue;
  23092. var renderingGroupMask = Math.pow(2, index);
  23093. info.renderingGroupId = index;
  23094. // Before Observable
  23095. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23096. // Clear depth/stencil if needed
  23097. if (RenderingManager.AUTOCLEAR) {
  23098. var autoClear = this._useSceneAutoClearSetup ?
  23099. this._scene.getAutoClearDepthStencilSetup(index) :
  23100. this._autoClearDepthStencil[index];
  23101. if (autoClear && autoClear.autoClear) {
  23102. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23103. }
  23104. }
  23105. // Render
  23106. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23107. var step = _a[_i];
  23108. step.action(index);
  23109. }
  23110. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23111. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23112. var step = _c[_b];
  23113. step.action(index);
  23114. }
  23115. // After Observable
  23116. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23117. }
  23118. };
  23119. RenderingManager.prototype.reset = function () {
  23120. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23121. var renderingGroup = this._renderingGroups[index];
  23122. if (renderingGroup) {
  23123. renderingGroup.prepare();
  23124. }
  23125. }
  23126. };
  23127. RenderingManager.prototype.dispose = function () {
  23128. this.freeRenderingGroups();
  23129. this._renderingGroups.length = 0;
  23130. this._renderingGroupInfo = null;
  23131. };
  23132. /**
  23133. * Clear the info related to rendering groups preventing retention points during dispose.
  23134. */
  23135. RenderingManager.prototype.freeRenderingGroups = function () {
  23136. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23137. var renderingGroup = this._renderingGroups[index];
  23138. if (renderingGroup) {
  23139. renderingGroup.dispose();
  23140. }
  23141. }
  23142. };
  23143. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23144. if (this._renderingGroups[renderingGroupId] === undefined) {
  23145. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23146. }
  23147. };
  23148. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23149. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23150. this._prepareRenderingGroup(renderingGroupId);
  23151. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23152. };
  23153. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23154. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23155. this._prepareRenderingGroup(renderingGroupId);
  23156. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23157. };
  23158. /**
  23159. * @param subMesh The submesh to dispatch
  23160. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23161. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23162. */
  23163. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23164. if (mesh === undefined) {
  23165. mesh = subMesh.getMesh();
  23166. }
  23167. var renderingGroupId = mesh.renderingGroupId || 0;
  23168. this._prepareRenderingGroup(renderingGroupId);
  23169. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23170. };
  23171. /**
  23172. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23173. * This allowed control for front to back rendering or reversly depending of the special needs.
  23174. *
  23175. * @param renderingGroupId The rendering group id corresponding to its index
  23176. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23177. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23178. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23179. */
  23180. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23181. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23182. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23183. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23184. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23185. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23186. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23187. if (this._renderingGroups[renderingGroupId]) {
  23188. var group = this._renderingGroups[renderingGroupId];
  23189. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23190. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23191. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23192. }
  23193. };
  23194. /**
  23195. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23196. *
  23197. * @param renderingGroupId The rendering group id corresponding to its index
  23198. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23199. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23200. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23201. */
  23202. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23203. if (depth === void 0) { depth = true; }
  23204. if (stencil === void 0) { stencil = true; }
  23205. this._autoClearDepthStencil[renderingGroupId] = {
  23206. autoClear: autoClearDepthStencil,
  23207. depth: depth,
  23208. stencil: stencil
  23209. };
  23210. };
  23211. /**
  23212. * Gets the current auto clear configuration for one rendering group of the rendering
  23213. * manager.
  23214. * @param index the rendering group index to get the information for
  23215. * @returns The auto clear setup for the requested rendering group
  23216. */
  23217. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23218. return this._autoClearDepthStencil[index];
  23219. };
  23220. /**
  23221. * The max id used for rendering groups (not included)
  23222. */
  23223. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23224. /**
  23225. * The min id used for rendering groups (included)
  23226. */
  23227. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23228. /**
  23229. * Used to globally prevent autoclearing scenes.
  23230. */
  23231. RenderingManager.AUTOCLEAR = true;
  23232. return RenderingManager;
  23233. }());
  23234. BABYLON.RenderingManager = RenderingManager;
  23235. })(BABYLON || (BABYLON = {}));
  23236. //# sourceMappingURL=babylon.renderingManager.js.map
  23237. var BABYLON;
  23238. (function (BABYLON) {
  23239. var RenderingGroup = /** @class */ (function () {
  23240. /**
  23241. * Creates a new rendering group.
  23242. * @param index The rendering group index
  23243. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23244. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23245. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23246. */
  23247. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23248. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23249. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23250. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23251. this.index = index;
  23252. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23253. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23254. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23255. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23256. this._particleSystems = new BABYLON.SmartArray(256);
  23257. this._spriteManagers = new BABYLON.SmartArray(256);
  23258. this._edgesRenderers = new BABYLON.SmartArray(16);
  23259. this._scene = scene;
  23260. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23261. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23262. this.transparentSortCompareFn = transparentSortCompareFn;
  23263. }
  23264. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23265. /**
  23266. * Set the opaque sort comparison function.
  23267. * If null the sub meshes will be render in the order they were created
  23268. */
  23269. set: function (value) {
  23270. this._opaqueSortCompareFn = value;
  23271. if (value) {
  23272. this._renderOpaque = this.renderOpaqueSorted;
  23273. }
  23274. else {
  23275. this._renderOpaque = RenderingGroup.renderUnsorted;
  23276. }
  23277. },
  23278. enumerable: true,
  23279. configurable: true
  23280. });
  23281. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23282. /**
  23283. * Set the alpha test sort comparison function.
  23284. * If null the sub meshes will be render in the order they were created
  23285. */
  23286. set: function (value) {
  23287. this._alphaTestSortCompareFn = value;
  23288. if (value) {
  23289. this._renderAlphaTest = this.renderAlphaTestSorted;
  23290. }
  23291. else {
  23292. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23293. }
  23294. },
  23295. enumerable: true,
  23296. configurable: true
  23297. });
  23298. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23299. /**
  23300. * Set the transparent sort comparison function.
  23301. * If null the sub meshes will be render in the order they were created
  23302. */
  23303. set: function (value) {
  23304. if (value) {
  23305. this._transparentSortCompareFn = value;
  23306. }
  23307. else {
  23308. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23309. }
  23310. this._renderTransparent = this.renderTransparentSorted;
  23311. },
  23312. enumerable: true,
  23313. configurable: true
  23314. });
  23315. /**
  23316. * Render all the sub meshes contained in the group.
  23317. * @param customRenderFunction Used to override the default render behaviour of the group.
  23318. * @returns true if rendered some submeshes.
  23319. */
  23320. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23321. if (customRenderFunction) {
  23322. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23323. return;
  23324. }
  23325. var engine = this._scene.getEngine();
  23326. // Depth only
  23327. if (this._depthOnlySubMeshes.length !== 0) {
  23328. engine.setColorWrite(false);
  23329. this._renderAlphaTest(this._depthOnlySubMeshes);
  23330. engine.setColorWrite(true);
  23331. }
  23332. // Opaque
  23333. if (this._opaqueSubMeshes.length !== 0) {
  23334. this._renderOpaque(this._opaqueSubMeshes);
  23335. }
  23336. // Alpha test
  23337. if (this._alphaTestSubMeshes.length !== 0) {
  23338. this._renderAlphaTest(this._alphaTestSubMeshes);
  23339. }
  23340. var stencilState = engine.getStencilBuffer();
  23341. engine.setStencilBuffer(false);
  23342. // Sprites
  23343. if (renderSprites) {
  23344. this._renderSprites();
  23345. }
  23346. // Particles
  23347. if (renderParticles) {
  23348. this._renderParticles(activeMeshes);
  23349. }
  23350. if (this.onBeforeTransparentRendering) {
  23351. this.onBeforeTransparentRendering();
  23352. }
  23353. // Transparent
  23354. if (this._transparentSubMeshes.length !== 0) {
  23355. this._renderTransparent(this._transparentSubMeshes);
  23356. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23357. }
  23358. // Set back stencil to false in case it changes before the edge renderer.
  23359. engine.setStencilBuffer(false);
  23360. // Edges
  23361. if (this._edgesRenderers.length) {
  23362. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23363. this._edgesRenderers.data[edgesRendererIndex].render();
  23364. }
  23365. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23366. }
  23367. // Restore Stencil state.
  23368. engine.setStencilBuffer(stencilState);
  23369. };
  23370. /**
  23371. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23372. * @param subMeshes The submeshes to render
  23373. */
  23374. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23375. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23376. };
  23377. /**
  23378. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23379. * @param subMeshes The submeshes to render
  23380. */
  23381. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23382. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23383. };
  23384. /**
  23385. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23386. * @param subMeshes The submeshes to render
  23387. */
  23388. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23389. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23390. };
  23391. /**
  23392. * Renders the submeshes in a specified order.
  23393. * @param subMeshes The submeshes to sort before render
  23394. * @param sortCompareFn The comparison function use to sort
  23395. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23396. * @param transparent Specifies to activate blending if true
  23397. */
  23398. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23399. var subIndex = 0;
  23400. var subMesh;
  23401. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23402. for (; subIndex < subMeshes.length; subIndex++) {
  23403. subMesh = subMeshes.data[subIndex];
  23404. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23405. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23406. }
  23407. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23408. if (sortCompareFn) {
  23409. sortedArray.sort(sortCompareFn);
  23410. }
  23411. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23412. subMesh = sortedArray[subIndex];
  23413. if (transparent) {
  23414. var material = subMesh.getMaterial();
  23415. if (material && material.needDepthPrePass) {
  23416. var engine = material.getScene().getEngine();
  23417. engine.setColorWrite(false);
  23418. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23419. subMesh.render(false);
  23420. engine.setColorWrite(true);
  23421. }
  23422. }
  23423. subMesh.render(transparent);
  23424. }
  23425. };
  23426. /**
  23427. * Renders the submeshes in the order they were dispatched (no sort applied).
  23428. * @param subMeshes The submeshes to render
  23429. */
  23430. RenderingGroup.renderUnsorted = function (subMeshes) {
  23431. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23432. var submesh = subMeshes.data[subIndex];
  23433. submesh.render(false);
  23434. }
  23435. };
  23436. /**
  23437. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23438. * are rendered back to front if in the same alpha index.
  23439. *
  23440. * @param a The first submesh
  23441. * @param b The second submesh
  23442. * @returns The result of the comparison
  23443. */
  23444. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23445. // Alpha index first
  23446. if (a._alphaIndex > b._alphaIndex) {
  23447. return 1;
  23448. }
  23449. if (a._alphaIndex < b._alphaIndex) {
  23450. return -1;
  23451. }
  23452. // Then distance to camera
  23453. return RenderingGroup.backToFrontSortCompare(a, b);
  23454. };
  23455. /**
  23456. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23457. * are rendered back to front.
  23458. *
  23459. * @param a The first submesh
  23460. * @param b The second submesh
  23461. * @returns The result of the comparison
  23462. */
  23463. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23464. // Then distance to camera
  23465. if (a._distanceToCamera < b._distanceToCamera) {
  23466. return 1;
  23467. }
  23468. if (a._distanceToCamera > b._distanceToCamera) {
  23469. return -1;
  23470. }
  23471. return 0;
  23472. };
  23473. /**
  23474. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23475. * are rendered front to back (prevent overdraw).
  23476. *
  23477. * @param a The first submesh
  23478. * @param b The second submesh
  23479. * @returns The result of the comparison
  23480. */
  23481. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23482. // Then distance to camera
  23483. if (a._distanceToCamera < b._distanceToCamera) {
  23484. return -1;
  23485. }
  23486. if (a._distanceToCamera > b._distanceToCamera) {
  23487. return 1;
  23488. }
  23489. return 0;
  23490. };
  23491. /**
  23492. * Resets the different lists of submeshes to prepare a new frame.
  23493. */
  23494. RenderingGroup.prototype.prepare = function () {
  23495. this._opaqueSubMeshes.reset();
  23496. this._transparentSubMeshes.reset();
  23497. this._alphaTestSubMeshes.reset();
  23498. this._depthOnlySubMeshes.reset();
  23499. this._particleSystems.reset();
  23500. this._spriteManagers.reset();
  23501. this._edgesRenderers.reset();
  23502. };
  23503. RenderingGroup.prototype.dispose = function () {
  23504. this._opaqueSubMeshes.dispose();
  23505. this._transparentSubMeshes.dispose();
  23506. this._alphaTestSubMeshes.dispose();
  23507. this._depthOnlySubMeshes.dispose();
  23508. this._particleSystems.dispose();
  23509. this._spriteManagers.dispose();
  23510. this._edgesRenderers.dispose();
  23511. };
  23512. /**
  23513. * Inserts the submesh in its correct queue depending on its material.
  23514. * @param subMesh The submesh to dispatch
  23515. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23516. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23517. */
  23518. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23519. // Get mesh and materials if not provided
  23520. if (mesh === undefined) {
  23521. mesh = subMesh.getMesh();
  23522. }
  23523. if (material === undefined) {
  23524. material = subMesh.getMaterial();
  23525. }
  23526. if (material === null || material === undefined) {
  23527. return;
  23528. }
  23529. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23530. this._transparentSubMeshes.push(subMesh);
  23531. }
  23532. else if (material.needAlphaTesting()) { // Alpha test
  23533. if (material.needDepthPrePass) {
  23534. this._depthOnlySubMeshes.push(subMesh);
  23535. }
  23536. this._alphaTestSubMeshes.push(subMesh);
  23537. }
  23538. else {
  23539. if (material.needDepthPrePass) {
  23540. this._depthOnlySubMeshes.push(subMesh);
  23541. }
  23542. this._opaqueSubMeshes.push(subMesh); // Opaque
  23543. }
  23544. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23545. this._edgesRenderers.push(mesh._edgesRenderer);
  23546. }
  23547. };
  23548. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23549. this._spriteManagers.push(spriteManager);
  23550. };
  23551. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23552. this._particleSystems.push(particleSystem);
  23553. };
  23554. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23555. if (this._particleSystems.length === 0) {
  23556. return;
  23557. }
  23558. // Particles
  23559. var activeCamera = this._scene.activeCamera;
  23560. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23561. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23562. var particleSystem = this._particleSystems.data[particleIndex];
  23563. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23564. continue;
  23565. }
  23566. var emitter = particleSystem.emitter;
  23567. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23568. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23569. }
  23570. }
  23571. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23572. };
  23573. RenderingGroup.prototype._renderSprites = function () {
  23574. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23575. return;
  23576. }
  23577. // Sprites
  23578. var activeCamera = this._scene.activeCamera;
  23579. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23580. for (var id = 0; id < this._spriteManagers.length; id++) {
  23581. var spriteManager = this._spriteManagers.data[id];
  23582. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23583. spriteManager.render();
  23584. }
  23585. }
  23586. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23587. };
  23588. return RenderingGroup;
  23589. }());
  23590. BABYLON.RenderingGroup = RenderingGroup;
  23591. })(BABYLON || (BABYLON = {}));
  23592. //# sourceMappingURL=babylon.renderingGroup.js.map
  23593. var BABYLON;
  23594. (function (BABYLON) {
  23595. /**
  23596. * Groups all the scene component constants in one place to ease maintenance.
  23597. * @hidden
  23598. */
  23599. var SceneComponentConstants = /** @class */ (function () {
  23600. function SceneComponentConstants() {
  23601. }
  23602. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23603. SceneComponentConstants.NAME_LAYER = "Layer";
  23604. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23605. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23606. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23607. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23608. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23609. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23610. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23611. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23612. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23613. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23614. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23615. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23616. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23617. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23618. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23619. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23620. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23621. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23622. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23623. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23624. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23625. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23626. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23627. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 0;
  23628. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 1;
  23629. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 2;
  23630. SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER = 0;
  23631. return SceneComponentConstants;
  23632. }());
  23633. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23634. /**
  23635. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23636. * @hidden
  23637. */
  23638. var Stage = /** @class */ (function (_super) {
  23639. __extends(Stage, _super);
  23640. /**
  23641. * Hide ctor from the rest of the world.
  23642. * @param items The items to add.
  23643. */
  23644. function Stage(items) {
  23645. return _super.apply(this, items) || this;
  23646. }
  23647. /**
  23648. * Creates a new Stage.
  23649. * @returns A new instance of a Stage
  23650. */
  23651. Stage.Create = function () {
  23652. return Object.create(Stage.prototype);
  23653. };
  23654. /**
  23655. * Registers a step in an ordered way in the targeted stage.
  23656. * @param index Defines the position to register the step in
  23657. * @param component Defines the component attached to the step
  23658. * @param action Defines the action to launch during the step
  23659. */
  23660. Stage.prototype.registerStep = function (index, component, action) {
  23661. var i = 0;
  23662. var maxIndex = Number.MAX_VALUE;
  23663. for (; i < this.length && i < maxIndex; i++) {
  23664. var step = this[i];
  23665. maxIndex = step.index;
  23666. }
  23667. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23668. };
  23669. /**
  23670. * Clears all the steps from the stage.
  23671. */
  23672. Stage.prototype.clear = function () {
  23673. this.length = 0;
  23674. };
  23675. return Stage;
  23676. }(Array));
  23677. BABYLON.Stage = Stage;
  23678. })(BABYLON || (BABYLON = {}));
  23679. //# sourceMappingURL=babylon.sceneComponent.js.map
  23680. var BABYLON;
  23681. (function (BABYLON) {
  23682. /**
  23683. * Base class of the scene acting as a container for the different elements composing a scene.
  23684. * This class is dynamically extended by the different components of the scene increasing
  23685. * flexibility and reducing coupling
  23686. */
  23687. var AbstractScene = /** @class */ (function () {
  23688. function AbstractScene() {
  23689. /** All of the cameras added to this scene
  23690. * @see http://doc.babylonjs.com/babylon101/cameras
  23691. */
  23692. this.cameras = new Array();
  23693. /**
  23694. * All of the lights added to this scene
  23695. * @see http://doc.babylonjs.com/babylon101/lights
  23696. */
  23697. this.lights = new Array();
  23698. /**
  23699. * All of the (abstract) meshes added to this scene
  23700. */
  23701. this.meshes = new Array();
  23702. /**
  23703. * The list of skeletons added to the scene
  23704. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23705. */
  23706. this.skeletons = new Array();
  23707. /**
  23708. * All of the particle systems added to this scene
  23709. * @see http://doc.babylonjs.com/babylon101/particles
  23710. */
  23711. this.particleSystems = new Array();
  23712. /**
  23713. * Gets a list of Animations associated with the scene
  23714. */
  23715. this.animations = [];
  23716. /**
  23717. * All of the animation groups added to this scene
  23718. * @see http://doc.babylonjs.com/how_to/group
  23719. */
  23720. this.animationGroups = new Array();
  23721. /**
  23722. * All of the multi-materials added to this scene
  23723. * @see http://doc.babylonjs.com/how_to/multi_materials
  23724. */
  23725. this.multiMaterials = new Array();
  23726. /**
  23727. * All of the materials added to this scene
  23728. * @see http://doc.babylonjs.com/babylon101/materials
  23729. */
  23730. this.materials = new Array();
  23731. /**
  23732. * The list of morph target managers added to the scene
  23733. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23734. */
  23735. this.morphTargetManagers = new Array();
  23736. /**
  23737. * The list of geometries used in the scene.
  23738. */
  23739. this.geometries = new Array();
  23740. /**
  23741. * All of the tranform nodes added to this scene
  23742. * @see http://doc.babylonjs.com/how_to/transformnode
  23743. */
  23744. this.transformNodes = new Array();
  23745. /**
  23746. * ActionManagers available on the scene.
  23747. */
  23748. this.actionManagers = new Array();
  23749. /**
  23750. * Sounds to keep.
  23751. */
  23752. this.sounds = new Array();
  23753. /**
  23754. * Textures to keep.
  23755. */
  23756. this.textures = new Array();
  23757. }
  23758. /**
  23759. * Adds a parser in the list of available ones
  23760. * @param name Defines the name of the parser
  23761. * @param parser Defines the parser to add
  23762. */
  23763. AbstractScene.AddParser = function (name, parser) {
  23764. this._BabylonFileParsers[name] = parser;
  23765. };
  23766. /**
  23767. * Gets a general parser from the list of avaialble ones
  23768. * @param name Defines the name of the parser
  23769. * @returns the requested parser or null
  23770. */
  23771. AbstractScene.GetParser = function (name) {
  23772. if (this._BabylonFileParsers[name]) {
  23773. return this._BabylonFileParsers[name];
  23774. }
  23775. return null;
  23776. };
  23777. /**
  23778. * Adds n individual parser in the list of available ones
  23779. * @param name Defines the name of the parser
  23780. * @param parser Defines the parser to add
  23781. */
  23782. AbstractScene.AddIndividualParser = function (name, parser) {
  23783. this._IndividualBabylonFileParsers[name] = parser;
  23784. };
  23785. /**
  23786. * Gets an individual parser from the list of avaialble ones
  23787. * @param name Defines the name of the parser
  23788. * @returns the requested parser or null
  23789. */
  23790. AbstractScene.GetIndividualParser = function (name) {
  23791. if (this._IndividualBabylonFileParsers[name]) {
  23792. return this._IndividualBabylonFileParsers[name];
  23793. }
  23794. return null;
  23795. };
  23796. /**
  23797. * Parser json data and populate both a scene and its associated container object
  23798. * @param jsonData Defines the data to parse
  23799. * @param scene Defines the scene to parse the data for
  23800. * @param container Defines the container attached to the parsing sequence
  23801. * @param rootUrl Defines the root url of the data
  23802. */
  23803. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23804. for (var parserName in this._BabylonFileParsers) {
  23805. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23806. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23807. }
  23808. }
  23809. };
  23810. /**
  23811. * Stores the list of available parsers in the application.
  23812. */
  23813. AbstractScene._BabylonFileParsers = {};
  23814. /**
  23815. * Stores the list of available individual parsers in the application.
  23816. */
  23817. AbstractScene._IndividualBabylonFileParsers = {};
  23818. return AbstractScene;
  23819. }());
  23820. BABYLON.AbstractScene = AbstractScene;
  23821. })(BABYLON || (BABYLON = {}));
  23822. //# sourceMappingURL=babylon.abstractScene.js.map
  23823. var BABYLON;
  23824. (function (BABYLON) {
  23825. /** @hidden */
  23826. var ClickInfo = /** @class */ (function () {
  23827. function ClickInfo() {
  23828. this._singleClick = false;
  23829. this._doubleClick = false;
  23830. this._hasSwiped = false;
  23831. this._ignore = false;
  23832. }
  23833. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23834. get: function () {
  23835. return this._singleClick;
  23836. },
  23837. set: function (b) {
  23838. this._singleClick = b;
  23839. },
  23840. enumerable: true,
  23841. configurable: true
  23842. });
  23843. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23844. get: function () {
  23845. return this._doubleClick;
  23846. },
  23847. set: function (b) {
  23848. this._doubleClick = b;
  23849. },
  23850. enumerable: true,
  23851. configurable: true
  23852. });
  23853. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23854. get: function () {
  23855. return this._hasSwiped;
  23856. },
  23857. set: function (b) {
  23858. this._hasSwiped = b;
  23859. },
  23860. enumerable: true,
  23861. configurable: true
  23862. });
  23863. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23864. get: function () {
  23865. return this._ignore;
  23866. },
  23867. set: function (b) {
  23868. this._ignore = b;
  23869. },
  23870. enumerable: true,
  23871. configurable: true
  23872. });
  23873. return ClickInfo;
  23874. }());
  23875. /**
  23876. * This class is used by the onRenderingGroupObservable
  23877. */
  23878. var RenderingGroupInfo = /** @class */ (function () {
  23879. function RenderingGroupInfo() {
  23880. }
  23881. return RenderingGroupInfo;
  23882. }());
  23883. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23884. /**
  23885. * Represents a scene to be rendered by the engine.
  23886. * @see http://doc.babylonjs.com/features/scene
  23887. */
  23888. var Scene = /** @class */ (function (_super) {
  23889. __extends(Scene, _super);
  23890. /**
  23891. * Creates a new Scene
  23892. * @param engine defines the engine to use to render this scene
  23893. */
  23894. function Scene(engine) {
  23895. var _this = _super.call(this) || this;
  23896. // Members
  23897. /**
  23898. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23899. */
  23900. _this.autoClear = true;
  23901. /**
  23902. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23903. */
  23904. _this.autoClearDepthAndStencil = true;
  23905. /**
  23906. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23907. */
  23908. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23909. /**
  23910. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23911. */
  23912. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23913. _this._forceWireframe = false;
  23914. _this._forcePointsCloud = false;
  23915. /**
  23916. * Gets or sets a boolean indicating if animations are enabled
  23917. */
  23918. _this.animationsEnabled = true;
  23919. _this._animationPropertiesOverride = null;
  23920. /**
  23921. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23922. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23923. */
  23924. _this.useConstantAnimationDeltaTime = false;
  23925. /**
  23926. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23927. * Please note that it requires to run a ray cast through the scene on every frame
  23928. */
  23929. _this.constantlyUpdateMeshUnderPointer = false;
  23930. /**
  23931. * Defines the HTML cursor to use when hovering over interactive elements
  23932. */
  23933. _this.hoverCursor = "pointer";
  23934. /**
  23935. * Defines the HTML default cursor to use (empty by default)
  23936. */
  23937. _this.defaultCursor = "";
  23938. /**
  23939. * This is used to call preventDefault() on pointer down
  23940. * in order to block unwanted artifacts like system double clicks
  23941. */
  23942. _this.preventDefaultOnPointerDown = true;
  23943. // Metadata
  23944. /**
  23945. * Gets or sets user defined metadata
  23946. */
  23947. _this.metadata = null;
  23948. /**
  23949. * Use this array to add regular expressions used to disable offline support for specific urls
  23950. */
  23951. _this.disableOfflineSupportExceptionRules = new Array();
  23952. /**
  23953. * An event triggered when the scene is disposed.
  23954. */
  23955. _this.onDisposeObservable = new BABYLON.Observable();
  23956. _this._onDisposeObserver = null;
  23957. /**
  23958. * An event triggered before rendering the scene (right after animations and physics)
  23959. */
  23960. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23961. _this._onBeforeRenderObserver = null;
  23962. /**
  23963. * An event triggered after rendering the scene
  23964. */
  23965. _this.onAfterRenderObservable = new BABYLON.Observable();
  23966. _this._onAfterRenderObserver = null;
  23967. /**
  23968. * An event triggered before animating the scene
  23969. */
  23970. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23971. /**
  23972. * An event triggered after animations processing
  23973. */
  23974. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23975. /**
  23976. * An event triggered before draw calls are ready to be sent
  23977. */
  23978. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23979. /**
  23980. * An event triggered after draw calls have been sent
  23981. */
  23982. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23983. /**
  23984. * An event triggered when physic simulation is about to be run
  23985. */
  23986. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23987. /**
  23988. * An event triggered when physic simulation has been done
  23989. */
  23990. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  23991. /**
  23992. * An event triggered when the scene is ready
  23993. */
  23994. _this.onReadyObservable = new BABYLON.Observable();
  23995. /**
  23996. * An event triggered before rendering a camera
  23997. */
  23998. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23999. _this._onBeforeCameraRenderObserver = null;
  24000. /**
  24001. * An event triggered after rendering a camera
  24002. */
  24003. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24004. _this._onAfterCameraRenderObserver = null;
  24005. /**
  24006. * An event triggered when active meshes evaluation is about to start
  24007. */
  24008. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24009. /**
  24010. * An event triggered when active meshes evaluation is done
  24011. */
  24012. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24013. /**
  24014. * An event triggered when particles rendering is about to start
  24015. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24016. */
  24017. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24018. /**
  24019. * An event triggered when particles rendering is done
  24020. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24021. */
  24022. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24023. /**
  24024. * An event triggered when sprites rendering is about to start
  24025. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24026. */
  24027. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24028. /**
  24029. * An event triggered when sprites rendering is done
  24030. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24031. */
  24032. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24033. /**
  24034. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24035. */
  24036. _this.onDataLoadedObservable = new BABYLON.Observable();
  24037. /**
  24038. * An event triggered when a camera is created
  24039. */
  24040. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24041. /**
  24042. * An event triggered when a camera is removed
  24043. */
  24044. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24045. /**
  24046. * An event triggered when a light is created
  24047. */
  24048. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24049. /**
  24050. * An event triggered when a light is removed
  24051. */
  24052. _this.onLightRemovedObservable = new BABYLON.Observable();
  24053. /**
  24054. * An event triggered when a geometry is created
  24055. */
  24056. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24057. /**
  24058. * An event triggered when a geometry is removed
  24059. */
  24060. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24061. /**
  24062. * An event triggered when a transform node is created
  24063. */
  24064. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24065. /**
  24066. * An event triggered when a transform node is removed
  24067. */
  24068. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24069. /**
  24070. * An event triggered when a mesh is created
  24071. */
  24072. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24073. /**
  24074. * An event triggered when a mesh is removed
  24075. */
  24076. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24077. /**
  24078. * An event triggered when render targets are about to be rendered
  24079. * Can happen multiple times per frame.
  24080. */
  24081. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24082. /**
  24083. * An event triggered when render targets were rendered.
  24084. * Can happen multiple times per frame.
  24085. */
  24086. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24087. /**
  24088. * An event triggered before calculating deterministic simulation step
  24089. */
  24090. _this.onBeforeStepObservable = new BABYLON.Observable();
  24091. /**
  24092. * An event triggered after calculating deterministic simulation step
  24093. */
  24094. _this.onAfterStepObservable = new BABYLON.Observable();
  24095. /**
  24096. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24097. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24098. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  24099. */
  24100. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24101. /**
  24102. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24103. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24104. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  24105. */
  24106. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24107. // Animations
  24108. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24109. /**
  24110. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  24111. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24112. */
  24113. _this.onPrePointerObservable = new BABYLON.Observable();
  24114. /**
  24115. * Observable event triggered each time an input event is received from the rendering canvas
  24116. */
  24117. _this.onPointerObservable = new BABYLON.Observable();
  24118. _this._meshPickProceed = false;
  24119. _this._currentPickResult = null;
  24120. _this._previousPickResult = null;
  24121. _this._totalPointersPressed = 0;
  24122. _this._doubleClickOccured = false;
  24123. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24124. _this.cameraToUseForPointers = null;
  24125. _this._pointerX = 0;
  24126. _this._pointerY = 0;
  24127. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24128. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24129. _this._startingPointerTime = 0;
  24130. _this._previousStartingPointerTime = 0;
  24131. _this._pointerCaptures = {};
  24132. // Deterministic lockstep
  24133. _this._timeAccumulator = 0;
  24134. _this._currentStepId = 0;
  24135. _this._currentInternalStep = 0;
  24136. // Keyboard
  24137. /**
  24138. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24139. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24140. */
  24141. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24142. /**
  24143. * Observable event triggered each time an keyboard event is received from the hosting window
  24144. */
  24145. _this.onKeyboardObservable = new BABYLON.Observable();
  24146. // Coordinates system
  24147. _this._useRightHandedSystem = false;
  24148. // Fog
  24149. _this._fogEnabled = true;
  24150. _this._fogMode = Scene.FOGMODE_NONE;
  24151. /**
  24152. * Gets or sets the fog color to use
  24153. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24154. */
  24155. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24156. /**
  24157. * Gets or sets the fog density to use
  24158. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24159. */
  24160. _this.fogDensity = 0.1;
  24161. /**
  24162. * Gets or sets the fog start distance to use
  24163. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24164. */
  24165. _this.fogStart = 0;
  24166. /**
  24167. * Gets or sets the fog end distance to use
  24168. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24169. */
  24170. _this.fogEnd = 1000.0;
  24171. // Lights
  24172. _this._shadowsEnabled = true;
  24173. _this._lightsEnabled = true;
  24174. /** All of the active cameras added to this scene. */
  24175. _this.activeCameras = new Array();
  24176. // Textures
  24177. _this._texturesEnabled = true;
  24178. // Particles
  24179. /**
  24180. * Gets or sets a boolean indicating if particles are enabled on this scene
  24181. */
  24182. _this.particlesEnabled = true;
  24183. // Sprites
  24184. /**
  24185. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24186. */
  24187. _this.spritesEnabled = true;
  24188. /**
  24189. * All of the sprite managers added to this scene
  24190. * @see http://doc.babylonjs.com/babylon101/sprites
  24191. */
  24192. _this.spriteManagers = new Array();
  24193. // Skeletons
  24194. _this._skeletonsEnabled = true;
  24195. // Lens flares
  24196. /**
  24197. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24198. */
  24199. _this.lensFlaresEnabled = true;
  24200. // Collisions
  24201. /**
  24202. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24203. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24204. */
  24205. _this.collisionsEnabled = true;
  24206. /**
  24207. * Defines the gravity applied to this scene (used only for collisions)
  24208. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24209. */
  24210. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24211. // Postprocesses
  24212. /**
  24213. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24214. */
  24215. _this.postProcessesEnabled = true;
  24216. /**
  24217. * The list of postprocesses added to the scene
  24218. */
  24219. _this.postProcesses = new Array();
  24220. // Customs render targets
  24221. /**
  24222. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24223. */
  24224. _this.renderTargetsEnabled = true;
  24225. /**
  24226. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24227. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24228. */
  24229. _this.dumpNextRenderTargets = false;
  24230. /**
  24231. * The list of user defined render targets added to the scene
  24232. */
  24233. _this.customRenderTargets = new Array();
  24234. /**
  24235. * Gets the list of meshes imported to the scene through SceneLoader
  24236. */
  24237. _this.importedMeshesFiles = new Array();
  24238. // Probes
  24239. /**
  24240. * Gets or sets a boolean indicating if probes are enabled on this scene
  24241. */
  24242. _this.probesEnabled = true;
  24243. /**
  24244. * The list of reflection probes added to the scene
  24245. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24246. */
  24247. _this.reflectionProbes = new Array();
  24248. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24249. // Procedural textures
  24250. /**
  24251. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24252. */
  24253. _this.proceduralTexturesEnabled = true;
  24254. /**
  24255. * The list of procedural textures added to the scene
  24256. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24257. */
  24258. _this.proceduralTextures = new Array();
  24259. /**
  24260. * The list of sound tracks added to the scene
  24261. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24262. */
  24263. _this.soundTracks = new Array();
  24264. _this._audioEnabled = true;
  24265. _this._headphone = false;
  24266. // Performance counters
  24267. _this._totalVertices = new BABYLON.PerfCounter();
  24268. /** @hidden */
  24269. _this._activeIndices = new BABYLON.PerfCounter();
  24270. /** @hidden */
  24271. _this._activeParticles = new BABYLON.PerfCounter();
  24272. /** @hidden */
  24273. _this._activeBones = new BABYLON.PerfCounter();
  24274. _this._animationTime = 0;
  24275. /**
  24276. * Gets or sets a general scale for animation speed
  24277. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24278. */
  24279. _this.animationTimeScale = 1;
  24280. _this._renderId = 0;
  24281. _this._executeWhenReadyTimeoutId = -1;
  24282. _this._intermediateRendering = false;
  24283. _this._viewUpdateFlag = -1;
  24284. _this._projectionUpdateFlag = -1;
  24285. _this._alternateViewUpdateFlag = -1;
  24286. _this._alternateProjectionUpdateFlag = -1;
  24287. /** @hidden */
  24288. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24289. _this._activeRequests = new Array();
  24290. _this._pendingData = new Array();
  24291. _this._isDisposed = false;
  24292. /**
  24293. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24294. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24295. */
  24296. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24297. _this._activeMeshes = new BABYLON.SmartArray(256);
  24298. _this._processedMaterials = new BABYLON.SmartArray(256);
  24299. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24300. /** @hidden */
  24301. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24302. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24303. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24304. /** @hidden */
  24305. _this._activeAnimatables = new Array();
  24306. _this._transformMatrix = BABYLON.Matrix.Zero();
  24307. _this._useAlternateCameraConfiguration = false;
  24308. _this._alternateRendering = false;
  24309. /**
  24310. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24311. * This is useful if there are more lights that the maximum simulteanous authorized
  24312. */
  24313. _this.requireLightSorting = false;
  24314. /**
  24315. * @hidden
  24316. * Backing store of defined scene components.
  24317. */
  24318. _this._components = [];
  24319. /**
  24320. * @hidden
  24321. * Backing store of defined scene components.
  24322. */
  24323. _this._serializableComponents = [];
  24324. /**
  24325. * List of components to register on the next registration step.
  24326. */
  24327. _this._transientComponents = [];
  24328. /**
  24329. * @hidden
  24330. * Defines the actions happening before camera updates.
  24331. */
  24332. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24333. /**
  24334. * @hidden
  24335. * Defines the actions happening before camera updates.
  24336. */
  24337. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24338. /**
  24339. * @hidden
  24340. * Defines the actions happening during the per mesh ready checks.
  24341. */
  24342. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24343. /**
  24344. * @hidden
  24345. * Defines the actions happening before evaluate active mesh checks.
  24346. */
  24347. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24348. /**
  24349. * @hidden
  24350. * Defines the actions happening during the evaluate sub mesh checks.
  24351. */
  24352. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24353. /**
  24354. * @hidden
  24355. * Defines the actions happening during the active mesh stage.
  24356. */
  24357. _this._activeMeshStage = BABYLON.Stage.Create();
  24358. /**
  24359. * @hidden
  24360. * Defines the actions happening during the per camera render target step.
  24361. */
  24362. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24363. /**
  24364. * @hidden
  24365. * Defines the actions happening just before the active camera is drawing.
  24366. */
  24367. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24368. /**
  24369. * Defines the actions happening just before a rendering group is drawing.
  24370. */
  24371. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24372. /**
  24373. * @hidden
  24374. * Defines the actions happening just after a rendering group has been drawn.
  24375. */
  24376. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24377. /**
  24378. * @hidden
  24379. * Defines the actions happening just after the active camera has been drawn.
  24380. */
  24381. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24382. /**
  24383. * @hidden
  24384. * Defines the actions happening when Geometries are rebuilding.
  24385. */
  24386. _this._rebuildGeometryStage = BABYLON.Stage.Create();
  24387. _this._activeMeshesFrozen = false;
  24388. /** @hidden */
  24389. _this._allowPostProcessClear = true;
  24390. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24391. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24392. _this.blockMaterialDirtyMechanism = false;
  24393. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24394. _this._engine.scenes.push(_this);
  24395. _this._uid = null;
  24396. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24397. if (BABYLON.PostProcessManager) {
  24398. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24399. }
  24400. if (BABYLON.OutlineRenderer) {
  24401. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24402. }
  24403. if (BABYLON.Tools.IsWindowObjectExist()) {
  24404. _this.attachControl();
  24405. }
  24406. //collision coordinator initialization. For now legacy per default.
  24407. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24408. // Uniform Buffer
  24409. _this._createUbo();
  24410. // Default Image processing definition
  24411. if (BABYLON.ImageProcessingConfiguration) {
  24412. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24413. }
  24414. return _this;
  24415. }
  24416. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24417. /**
  24418. * Texture used in all pbr material as the reflection texture.
  24419. * As in the majority of the scene they are the same (exception for multi room and so on),
  24420. * this is easier to reference from here than from all the materials.
  24421. */
  24422. get: function () {
  24423. return this._environmentTexture;
  24424. },
  24425. /**
  24426. * Texture used in all pbr material as the reflection texture.
  24427. * As in the majority of the scene they are the same (exception for multi room and so on),
  24428. * this is easier to set here than in all the materials.
  24429. */
  24430. set: function (value) {
  24431. if (this._environmentTexture === value) {
  24432. return;
  24433. }
  24434. this._environmentTexture = value;
  24435. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24436. },
  24437. enumerable: true,
  24438. configurable: true
  24439. });
  24440. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24441. /**
  24442. * Default image processing configuration used either in the rendering
  24443. * Forward main pass or through the imageProcessingPostProcess if present.
  24444. * As in the majority of the scene they are the same (exception for multi camera),
  24445. * this is easier to reference from here than from all the materials and post process.
  24446. *
  24447. * No setter as we it is a shared configuration, you can set the values instead.
  24448. */
  24449. get: function () {
  24450. return this._imageProcessingConfiguration;
  24451. },
  24452. enumerable: true,
  24453. configurable: true
  24454. });
  24455. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24456. get: function () {
  24457. return this._forceWireframe;
  24458. },
  24459. /**
  24460. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24461. */
  24462. set: function (value) {
  24463. if (this._forceWireframe === value) {
  24464. return;
  24465. }
  24466. this._forceWireframe = value;
  24467. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24468. },
  24469. enumerable: true,
  24470. configurable: true
  24471. });
  24472. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24473. get: function () {
  24474. return this._forcePointsCloud;
  24475. },
  24476. /**
  24477. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24478. */
  24479. set: function (value) {
  24480. if (this._forcePointsCloud === value) {
  24481. return;
  24482. }
  24483. this._forcePointsCloud = value;
  24484. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24485. },
  24486. enumerable: true,
  24487. configurable: true
  24488. });
  24489. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24490. /**
  24491. * Gets or sets the animation properties override
  24492. */
  24493. get: function () {
  24494. return this._animationPropertiesOverride;
  24495. },
  24496. set: function (value) {
  24497. this._animationPropertiesOverride = value;
  24498. },
  24499. enumerable: true,
  24500. configurable: true
  24501. });
  24502. Object.defineProperty(Scene.prototype, "onDispose", {
  24503. /** Sets a function to be executed when this scene is disposed. */
  24504. set: function (callback) {
  24505. if (this._onDisposeObserver) {
  24506. this.onDisposeObservable.remove(this._onDisposeObserver);
  24507. }
  24508. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24509. },
  24510. enumerable: true,
  24511. configurable: true
  24512. });
  24513. Object.defineProperty(Scene.prototype, "beforeRender", {
  24514. /** Sets a function to be executed before rendering this scene */
  24515. set: function (callback) {
  24516. if (this._onBeforeRenderObserver) {
  24517. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24518. }
  24519. if (callback) {
  24520. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24521. }
  24522. },
  24523. enumerable: true,
  24524. configurable: true
  24525. });
  24526. Object.defineProperty(Scene.prototype, "afterRender", {
  24527. /** Sets a function to be executed after rendering this scene */
  24528. set: function (callback) {
  24529. if (this._onAfterRenderObserver) {
  24530. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24531. }
  24532. if (callback) {
  24533. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24534. }
  24535. },
  24536. enumerable: true,
  24537. configurable: true
  24538. });
  24539. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24540. /** Sets a function to be executed before rendering a camera*/
  24541. set: function (callback) {
  24542. if (this._onBeforeCameraRenderObserver) {
  24543. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24544. }
  24545. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24546. },
  24547. enumerable: true,
  24548. configurable: true
  24549. });
  24550. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24551. /** Sets a function to be executed after rendering a camera*/
  24552. set: function (callback) {
  24553. if (this._onAfterCameraRenderObserver) {
  24554. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24555. }
  24556. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24557. },
  24558. enumerable: true,
  24559. configurable: true
  24560. });
  24561. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24562. /**
  24563. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24564. */
  24565. get: function () {
  24566. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24567. },
  24568. enumerable: true,
  24569. configurable: true
  24570. });
  24571. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24572. get: function () {
  24573. return this._useRightHandedSystem;
  24574. },
  24575. /**
  24576. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24577. */
  24578. set: function (value) {
  24579. if (this._useRightHandedSystem === value) {
  24580. return;
  24581. }
  24582. this._useRightHandedSystem = value;
  24583. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24584. },
  24585. enumerable: true,
  24586. configurable: true
  24587. });
  24588. /**
  24589. * Sets the step Id used by deterministic lock step
  24590. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24591. * @param newStepId defines the step Id
  24592. */
  24593. Scene.prototype.setStepId = function (newStepId) {
  24594. this._currentStepId = newStepId;
  24595. };
  24596. ;
  24597. /**
  24598. * Gets the step Id used by deterministic lock step
  24599. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24600. * @returns the step Id
  24601. */
  24602. Scene.prototype.getStepId = function () {
  24603. return this._currentStepId;
  24604. };
  24605. ;
  24606. /**
  24607. * Gets the internal step used by deterministic lock step
  24608. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24609. * @returns the internal step
  24610. */
  24611. Scene.prototype.getInternalStep = function () {
  24612. return this._currentInternalStep;
  24613. };
  24614. ;
  24615. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24616. get: function () {
  24617. return this._fogEnabled;
  24618. },
  24619. /**
  24620. * Gets or sets a boolean indicating if fog is enabled on this scene
  24621. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24622. */
  24623. set: function (value) {
  24624. if (this._fogEnabled === value) {
  24625. return;
  24626. }
  24627. this._fogEnabled = value;
  24628. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24629. },
  24630. enumerable: true,
  24631. configurable: true
  24632. });
  24633. Object.defineProperty(Scene.prototype, "fogMode", {
  24634. get: function () {
  24635. return this._fogMode;
  24636. },
  24637. /**
  24638. * Gets or sets the fog mode to use
  24639. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24640. */
  24641. set: function (value) {
  24642. if (this._fogMode === value) {
  24643. return;
  24644. }
  24645. this._fogMode = value;
  24646. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24647. },
  24648. enumerable: true,
  24649. configurable: true
  24650. });
  24651. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24652. get: function () {
  24653. return this._shadowsEnabled;
  24654. },
  24655. /**
  24656. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24657. */
  24658. set: function (value) {
  24659. if (this._shadowsEnabled === value) {
  24660. return;
  24661. }
  24662. this._shadowsEnabled = value;
  24663. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24664. },
  24665. enumerable: true,
  24666. configurable: true
  24667. });
  24668. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24669. get: function () {
  24670. return this._lightsEnabled;
  24671. },
  24672. /**
  24673. * Gets or sets a boolean indicating if lights are enabled on this scene
  24674. */
  24675. set: function (value) {
  24676. if (this._lightsEnabled === value) {
  24677. return;
  24678. }
  24679. this._lightsEnabled = value;
  24680. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24681. },
  24682. enumerable: true,
  24683. configurable: true
  24684. });
  24685. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24686. /** The default material used on meshes when no material is affected */
  24687. get: function () {
  24688. if (!this._defaultMaterial) {
  24689. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24690. }
  24691. return this._defaultMaterial;
  24692. },
  24693. /** The default material used on meshes when no material is affected */
  24694. set: function (value) {
  24695. this._defaultMaterial = value;
  24696. },
  24697. enumerable: true,
  24698. configurable: true
  24699. });
  24700. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24701. get: function () {
  24702. return this._texturesEnabled;
  24703. },
  24704. /**
  24705. * Gets or sets a boolean indicating if textures are enabled on this scene
  24706. */
  24707. set: function (value) {
  24708. if (this._texturesEnabled === value) {
  24709. return;
  24710. }
  24711. this._texturesEnabled = value;
  24712. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24713. },
  24714. enumerable: true,
  24715. configurable: true
  24716. });
  24717. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24718. get: function () {
  24719. return this._skeletonsEnabled;
  24720. },
  24721. /**
  24722. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24723. */
  24724. set: function (value) {
  24725. if (this._skeletonsEnabled === value) {
  24726. return;
  24727. }
  24728. this._skeletonsEnabled = value;
  24729. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24730. },
  24731. enumerable: true,
  24732. configurable: true
  24733. });
  24734. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24735. /**
  24736. * Gets the main soundtrack associated with the scene
  24737. */
  24738. get: function () {
  24739. if (!this._mainSoundTrack) {
  24740. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24741. }
  24742. return this._mainSoundTrack;
  24743. },
  24744. enumerable: true,
  24745. configurable: true
  24746. });
  24747. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24748. /** @hidden */
  24749. get: function () {
  24750. return this._alternateRendering;
  24751. },
  24752. enumerable: true,
  24753. configurable: true
  24754. });
  24755. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24756. /**
  24757. * Gets the list of frustum planes (built from the active camera)
  24758. */
  24759. get: function () {
  24760. return this._frustumPlanes;
  24761. },
  24762. enumerable: true,
  24763. configurable: true
  24764. });
  24765. /**
  24766. * Registers the transient components if needed.
  24767. */
  24768. Scene.prototype._registerTransientComponents = function () {
  24769. // Register components that have been associated lately to the scene.
  24770. if (this._transientComponents.length > 0) {
  24771. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24772. var component = _a[_i];
  24773. component.register();
  24774. }
  24775. this._transientComponents = [];
  24776. }
  24777. };
  24778. /**
  24779. * @hidden
  24780. * Add a component to the scene.
  24781. * Note that the ccomponent could be registered on th next frame if this is called after
  24782. * the register component stage.
  24783. * @param component Defines the component to add to the scene
  24784. */
  24785. Scene.prototype._addComponent = function (component) {
  24786. this._components.push(component);
  24787. this._transientComponents.push(component);
  24788. var serializableComponent = component;
  24789. if (serializableComponent.addFromContainer) {
  24790. this._serializableComponents.push(serializableComponent);
  24791. }
  24792. };
  24793. /**
  24794. * @hidden
  24795. * Gets a component from the scene.
  24796. * @param name defines the name of the component to retrieve
  24797. * @returns the component or null if not present
  24798. */
  24799. Scene.prototype._getComponent = function (name) {
  24800. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24801. var component = _a[_i];
  24802. if (component.name === name) {
  24803. return component;
  24804. }
  24805. }
  24806. return null;
  24807. };
  24808. Object.defineProperty(Scene.prototype, "debugLayer", {
  24809. /**
  24810. * Gets the debug layer (aka Inspector) associated with the scene
  24811. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24812. */
  24813. get: function () {
  24814. if (!this._debugLayer) {
  24815. this._debugLayer = new BABYLON.DebugLayer(this);
  24816. }
  24817. return this._debugLayer;
  24818. },
  24819. enumerable: true,
  24820. configurable: true
  24821. });
  24822. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24823. /**
  24824. * Gets a boolean indicating if collisions are processed on a web worker
  24825. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24826. */
  24827. get: function () {
  24828. return this._workerCollisions;
  24829. },
  24830. set: function (enabled) {
  24831. if (!BABYLON.CollisionCoordinatorLegacy) {
  24832. return;
  24833. }
  24834. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24835. this._workerCollisions = enabled;
  24836. if (this.collisionCoordinator) {
  24837. this.collisionCoordinator.destroy();
  24838. }
  24839. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24840. this.collisionCoordinator.init(this);
  24841. },
  24842. enumerable: true,
  24843. configurable: true
  24844. });
  24845. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24846. /**
  24847. * Gets the octree used to boost mesh selection (picking)
  24848. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24849. */
  24850. get: function () {
  24851. return this._selectionOctree;
  24852. },
  24853. enumerable: true,
  24854. configurable: true
  24855. });
  24856. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24857. /**
  24858. * Gets the mesh that is currently under the pointer
  24859. */
  24860. get: function () {
  24861. return this._pointerOverMesh;
  24862. },
  24863. enumerable: true,
  24864. configurable: true
  24865. });
  24866. Object.defineProperty(Scene.prototype, "pointerX", {
  24867. /**
  24868. * Gets the current on-screen X position of the pointer
  24869. */
  24870. get: function () {
  24871. return this._pointerX;
  24872. },
  24873. enumerable: true,
  24874. configurable: true
  24875. });
  24876. Object.defineProperty(Scene.prototype, "pointerY", {
  24877. /**
  24878. * Gets the current on-screen Y position of the pointer
  24879. */
  24880. get: function () {
  24881. return this._pointerY;
  24882. },
  24883. enumerable: true,
  24884. configurable: true
  24885. });
  24886. /**
  24887. * Gets the cached material (ie. the latest rendered one)
  24888. * @returns the cached material
  24889. */
  24890. Scene.prototype.getCachedMaterial = function () {
  24891. return this._cachedMaterial;
  24892. };
  24893. /**
  24894. * Gets the cached effect (ie. the latest rendered one)
  24895. * @returns the cached effect
  24896. */
  24897. Scene.prototype.getCachedEffect = function () {
  24898. return this._cachedEffect;
  24899. };
  24900. /**
  24901. * Gets the cached visibility state (ie. the latest rendered one)
  24902. * @returns the cached visibility state
  24903. */
  24904. Scene.prototype.getCachedVisibility = function () {
  24905. return this._cachedVisibility;
  24906. };
  24907. /**
  24908. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24909. * @param material defines the current material
  24910. * @param effect defines the current effect
  24911. * @param visibility defines the current visibility state
  24912. * @returns true if one parameter is not cached
  24913. */
  24914. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24915. if (visibility === void 0) { visibility = 1; }
  24916. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24917. };
  24918. /**
  24919. * Gets the outline renderer associated with the scene
  24920. * @returns a OutlineRenderer
  24921. */
  24922. Scene.prototype.getOutlineRenderer = function () {
  24923. return this._outlineRenderer;
  24924. };
  24925. /**
  24926. * Gets the engine associated with the scene
  24927. * @returns an Engine
  24928. */
  24929. Scene.prototype.getEngine = function () {
  24930. return this._engine;
  24931. };
  24932. /**
  24933. * Gets the total number of vertices rendered per frame
  24934. * @returns the total number of vertices rendered per frame
  24935. */
  24936. Scene.prototype.getTotalVertices = function () {
  24937. return this._totalVertices.current;
  24938. };
  24939. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24940. /**
  24941. * Gets the performance counter for total vertices
  24942. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24943. */
  24944. get: function () {
  24945. return this._totalVertices;
  24946. },
  24947. enumerable: true,
  24948. configurable: true
  24949. });
  24950. /**
  24951. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24952. * @returns the total number of active indices rendered per frame
  24953. */
  24954. Scene.prototype.getActiveIndices = function () {
  24955. return this._activeIndices.current;
  24956. };
  24957. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24958. /**
  24959. * Gets the performance counter for active indices
  24960. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24961. */
  24962. get: function () {
  24963. return this._activeIndices;
  24964. },
  24965. enumerable: true,
  24966. configurable: true
  24967. });
  24968. /**
  24969. * Gets the total number of active particles rendered per frame
  24970. * @returns the total number of active particles rendered per frame
  24971. */
  24972. Scene.prototype.getActiveParticles = function () {
  24973. return this._activeParticles.current;
  24974. };
  24975. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24976. /**
  24977. * Gets the performance counter for active particles
  24978. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24979. */
  24980. get: function () {
  24981. return this._activeParticles;
  24982. },
  24983. enumerable: true,
  24984. configurable: true
  24985. });
  24986. /**
  24987. * Gets the total number of active bones rendered per frame
  24988. * @returns the total number of active bones rendered per frame
  24989. */
  24990. Scene.prototype.getActiveBones = function () {
  24991. return this._activeBones.current;
  24992. };
  24993. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24994. /**
  24995. * Gets the performance counter for active bones
  24996. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24997. */
  24998. get: function () {
  24999. return this._activeBones;
  25000. },
  25001. enumerable: true,
  25002. configurable: true
  25003. });
  25004. /** @hidden */
  25005. Scene.prototype.getInterFramePerfCounter = function () {
  25006. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25007. return 0;
  25008. };
  25009. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25010. /** @hidden */
  25011. get: function () {
  25012. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25013. return null;
  25014. },
  25015. enumerable: true,
  25016. configurable: true
  25017. });
  25018. /** @hidden */
  25019. Scene.prototype.getLastFrameDuration = function () {
  25020. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25021. return 0;
  25022. };
  25023. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25024. /** @hidden */
  25025. get: function () {
  25026. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25027. return null;
  25028. },
  25029. enumerable: true,
  25030. configurable: true
  25031. });
  25032. /** @hidden */
  25033. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25034. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25035. return 0;
  25036. };
  25037. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25038. /** @hidden */
  25039. get: function () {
  25040. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25041. return null;
  25042. },
  25043. enumerable: true,
  25044. configurable: true
  25045. });
  25046. /**
  25047. * Gets the array of active meshes
  25048. * @returns an array of AbstractMesh
  25049. */
  25050. Scene.prototype.getActiveMeshes = function () {
  25051. return this._activeMeshes;
  25052. };
  25053. /** @hidden */
  25054. Scene.prototype.getRenderTargetsDuration = function () {
  25055. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25056. return 0;
  25057. };
  25058. /** @hidden */
  25059. Scene.prototype.getRenderDuration = function () {
  25060. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25061. return 0;
  25062. };
  25063. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25064. /** @hidden */
  25065. get: function () {
  25066. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25067. return null;
  25068. },
  25069. enumerable: true,
  25070. configurable: true
  25071. });
  25072. /** @hidden */
  25073. Scene.prototype.getParticlesDuration = function () {
  25074. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25075. return 0;
  25076. };
  25077. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25078. /** @hidden */
  25079. get: function () {
  25080. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25081. return null;
  25082. },
  25083. enumerable: true,
  25084. configurable: true
  25085. });
  25086. /** @hidden */
  25087. Scene.prototype.getSpritesDuration = function () {
  25088. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25089. return 0;
  25090. };
  25091. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25092. /** @hidden */
  25093. get: function () {
  25094. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25095. return null;
  25096. },
  25097. enumerable: true,
  25098. configurable: true
  25099. });
  25100. /**
  25101. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25102. * @returns a number
  25103. */
  25104. Scene.prototype.getAnimationRatio = function () {
  25105. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25106. };
  25107. /**
  25108. * Gets an unique Id for the current frame
  25109. * @returns a number
  25110. */
  25111. Scene.prototype.getRenderId = function () {
  25112. return this._renderId;
  25113. };
  25114. /** Call this function if you want to manually increment the render Id*/
  25115. Scene.prototype.incrementRenderId = function () {
  25116. this._renderId++;
  25117. };
  25118. Scene.prototype._updatePointerPosition = function (evt) {
  25119. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25120. if (!canvasRect) {
  25121. return;
  25122. }
  25123. this._pointerX = evt.clientX - canvasRect.left;
  25124. this._pointerY = evt.clientY - canvasRect.top;
  25125. this._unTranslatedPointerX = this._pointerX;
  25126. this._unTranslatedPointerY = this._pointerY;
  25127. };
  25128. Scene.prototype._createUbo = function () {
  25129. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25130. this._sceneUbo.addUniform("viewProjection", 16);
  25131. this._sceneUbo.addUniform("view", 16);
  25132. };
  25133. Scene.prototype._createAlternateUbo = function () {
  25134. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25135. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25136. this._alternateSceneUbo.addUniform("view", 16);
  25137. };
  25138. // Pointers handling
  25139. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25140. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25141. if (result) {
  25142. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25143. }
  25144. return result;
  25145. };
  25146. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25147. if (pointerInfo.pickInfo) {
  25148. if (!pointerInfo.pickInfo.ray) {
  25149. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25150. }
  25151. }
  25152. };
  25153. /**
  25154. * Use this method to simulate a pointer move on a mesh
  25155. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25156. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25157. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25158. * @returns the current scene
  25159. */
  25160. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25161. var evt = new PointerEvent("pointermove", pointerEventInit);
  25162. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25163. return this;
  25164. }
  25165. return this._processPointerMove(pickResult, evt);
  25166. };
  25167. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25168. var canvas = this._engine.getRenderingCanvas();
  25169. if (!canvas) {
  25170. return this;
  25171. }
  25172. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25173. this.setPointerOverSprite(null);
  25174. this.setPointerOverMesh(pickResult.pickedMesh);
  25175. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25176. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25177. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25178. }
  25179. else {
  25180. canvas.style.cursor = this.hoverCursor;
  25181. }
  25182. }
  25183. else {
  25184. canvas.style.cursor = this.defaultCursor;
  25185. }
  25186. }
  25187. else {
  25188. this.setPointerOverMesh(null);
  25189. // Sprites
  25190. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25191. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25192. this.setPointerOverSprite(pickResult.pickedSprite);
  25193. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25194. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25195. }
  25196. else {
  25197. canvas.style.cursor = this.hoverCursor;
  25198. }
  25199. }
  25200. else {
  25201. this.setPointerOverSprite(null);
  25202. // Restore pointer
  25203. canvas.style.cursor = this.defaultCursor;
  25204. }
  25205. }
  25206. if (pickResult) {
  25207. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25208. if (this.onPointerMove) {
  25209. this.onPointerMove(evt, pickResult, type);
  25210. }
  25211. if (this.onPointerObservable.hasObservers()) {
  25212. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25213. this._setRayOnPointerInfo(pi);
  25214. this.onPointerObservable.notifyObservers(pi, type);
  25215. }
  25216. }
  25217. return this;
  25218. };
  25219. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25220. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25221. if (pickResult) {
  25222. pi.ray = pickResult.ray;
  25223. }
  25224. this.onPrePointerObservable.notifyObservers(pi, type);
  25225. if (pi.skipOnPointerObservable) {
  25226. return true;
  25227. }
  25228. else {
  25229. return false;
  25230. }
  25231. };
  25232. /**
  25233. * Use this method to simulate a pointer down on a mesh
  25234. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25235. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25236. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25237. * @returns the current scene
  25238. */
  25239. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25240. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25241. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25242. return this;
  25243. }
  25244. return this._processPointerDown(pickResult, evt);
  25245. };
  25246. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25247. var _this = this;
  25248. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25249. this._pickedDownMesh = pickResult.pickedMesh;
  25250. var actionManager = pickResult.pickedMesh.actionManager;
  25251. if (actionManager) {
  25252. if (actionManager.hasPickTriggers) {
  25253. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25254. switch (evt.button) {
  25255. case 0:
  25256. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25257. break;
  25258. case 1:
  25259. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25260. break;
  25261. case 2:
  25262. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25263. break;
  25264. }
  25265. }
  25266. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25267. window.setTimeout(function () {
  25268. 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);
  25269. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25270. if (_this._totalPointersPressed !== 0 &&
  25271. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25272. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25273. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25274. _this._startingPointerTime = 0;
  25275. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25276. }
  25277. }
  25278. }, Scene.LongPressDelay);
  25279. }
  25280. }
  25281. }
  25282. if (pickResult) {
  25283. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25284. if (this.onPointerDown) {
  25285. this.onPointerDown(evt, pickResult, type);
  25286. }
  25287. if (this.onPointerObservable.hasObservers()) {
  25288. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25289. this._setRayOnPointerInfo(pi);
  25290. this.onPointerObservable.notifyObservers(pi, type);
  25291. }
  25292. }
  25293. return this;
  25294. };
  25295. /**
  25296. * Use this method to simulate a pointer up on a mesh
  25297. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25298. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25299. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25300. * @returns the current scene
  25301. */
  25302. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25303. var evt = new PointerEvent("pointerup", pointerEventInit);
  25304. var clickInfo = new ClickInfo();
  25305. clickInfo.singleClick = true;
  25306. clickInfo.ignore = true;
  25307. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25308. return this;
  25309. }
  25310. return this._processPointerUp(pickResult, evt, clickInfo);
  25311. };
  25312. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25313. if (pickResult && pickResult && pickResult.pickedMesh) {
  25314. this._pickedUpMesh = pickResult.pickedMesh;
  25315. if (this._pickedDownMesh === this._pickedUpMesh) {
  25316. if (this.onPointerPick) {
  25317. this.onPointerPick(evt, pickResult);
  25318. }
  25319. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25320. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25321. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25322. this._setRayOnPointerInfo(pi);
  25323. this.onPointerObservable.notifyObservers(pi, type_1);
  25324. }
  25325. }
  25326. if (pickResult.pickedMesh.actionManager) {
  25327. if (clickInfo.ignore) {
  25328. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25329. }
  25330. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25331. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25332. }
  25333. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25334. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25335. }
  25336. }
  25337. }
  25338. if (this._pickedDownMesh &&
  25339. this._pickedDownMesh.actionManager &&
  25340. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25341. this._pickedDownMesh !== this._pickedUpMesh) {
  25342. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25343. }
  25344. var type = BABYLON.PointerEventTypes.POINTERUP;
  25345. if (this.onPointerObservable.hasObservers()) {
  25346. if (!clickInfo.ignore) {
  25347. if (!clickInfo.hasSwiped) {
  25348. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25349. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25350. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25351. this._setRayOnPointerInfo(pi);
  25352. this.onPointerObservable.notifyObservers(pi, type_2);
  25353. }
  25354. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25355. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25356. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25357. this._setRayOnPointerInfo(pi);
  25358. this.onPointerObservable.notifyObservers(pi, type_3);
  25359. }
  25360. }
  25361. }
  25362. else {
  25363. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25364. this._setRayOnPointerInfo(pi);
  25365. this.onPointerObservable.notifyObservers(pi, type);
  25366. }
  25367. }
  25368. if (this.onPointerUp) {
  25369. this.onPointerUp(evt, pickResult, type);
  25370. }
  25371. return this;
  25372. };
  25373. /**
  25374. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25375. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25376. * @returns true if the pointer was captured
  25377. */
  25378. Scene.prototype.isPointerCaptured = function (pointerId) {
  25379. if (pointerId === void 0) { pointerId = 0; }
  25380. return this._pointerCaptures[pointerId];
  25381. };
  25382. /**
  25383. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25384. * @param attachUp defines if you want to attach events to pointerup
  25385. * @param attachDown defines if you want to attach events to pointerdown
  25386. * @param attachMove defines if you want to attach events to pointermove
  25387. */
  25388. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25389. var _this = this;
  25390. if (attachUp === void 0) { attachUp = true; }
  25391. if (attachDown === void 0) { attachDown = true; }
  25392. if (attachMove === void 0) { attachMove = true; }
  25393. this._initActionManager = function (act, clickInfo) {
  25394. if (!_this._meshPickProceed) {
  25395. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25396. _this._currentPickResult = pickResult;
  25397. if (pickResult) {
  25398. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25399. }
  25400. _this._meshPickProceed = true;
  25401. }
  25402. return act;
  25403. };
  25404. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25405. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25406. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25407. btn !== _this._previousButtonPressed) {
  25408. _this._doubleClickOccured = false;
  25409. clickInfo.singleClick = true;
  25410. clickInfo.ignore = false;
  25411. cb(clickInfo, _this._currentPickResult);
  25412. }
  25413. };
  25414. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25415. var clickInfo = new ClickInfo();
  25416. _this._currentPickResult = null;
  25417. var act = null;
  25418. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25419. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25420. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25421. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25422. act = _this._initActionManager(act, clickInfo);
  25423. if (act)
  25424. checkPicking = act.hasPickTriggers;
  25425. }
  25426. if (checkPicking) {
  25427. var btn = evt.button;
  25428. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25429. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25430. if (!clickInfo.hasSwiped) {
  25431. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25432. if (!checkSingleClickImmediately) {
  25433. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25434. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25435. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25436. act = _this._initActionManager(act, clickInfo);
  25437. if (act)
  25438. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25439. }
  25440. }
  25441. if (checkSingleClickImmediately) {
  25442. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25443. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25444. btn !== _this._previousButtonPressed) {
  25445. clickInfo.singleClick = true;
  25446. cb(clickInfo, _this._currentPickResult);
  25447. }
  25448. }
  25449. // at least one double click is required to be check and exclusive double click is enabled
  25450. else {
  25451. // wait that no double click has been raised during the double click delay
  25452. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25453. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25454. }
  25455. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25456. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25457. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25458. act = _this._initActionManager(act, clickInfo);
  25459. if (act)
  25460. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25461. }
  25462. if (checkDoubleClick) {
  25463. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25464. if (btn === _this._previousButtonPressed &&
  25465. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25466. !_this._doubleClickOccured) {
  25467. // pointer has not moved for 2 clicks, it's a double click
  25468. if (!clickInfo.hasSwiped &&
  25469. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25470. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25471. _this._previousStartingPointerTime = 0;
  25472. _this._doubleClickOccured = true;
  25473. clickInfo.doubleClick = true;
  25474. clickInfo.ignore = false;
  25475. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25476. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25477. }
  25478. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25479. cb(clickInfo, _this._currentPickResult);
  25480. }
  25481. // if the two successive clicks are too far, it's just two simple clicks
  25482. else {
  25483. _this._doubleClickOccured = false;
  25484. _this._previousStartingPointerTime = _this._startingPointerTime;
  25485. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25486. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25487. _this._previousButtonPressed = btn;
  25488. if (Scene.ExclusiveDoubleClickMode) {
  25489. if (_this._previousDelayedSimpleClickTimeout) {
  25490. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25491. }
  25492. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25493. cb(clickInfo, _this._previousPickResult);
  25494. }
  25495. else {
  25496. cb(clickInfo, _this._currentPickResult);
  25497. }
  25498. }
  25499. }
  25500. // just the first click of the double has been raised
  25501. else {
  25502. _this._doubleClickOccured = false;
  25503. _this._previousStartingPointerTime = _this._startingPointerTime;
  25504. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25505. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25506. _this._previousButtonPressed = btn;
  25507. }
  25508. }
  25509. }
  25510. }
  25511. clickInfo.ignore = true;
  25512. cb(clickInfo, _this._currentPickResult);
  25513. };
  25514. this._spritePredicate = function (sprite) {
  25515. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25516. };
  25517. this._onPointerMove = function (evt) {
  25518. _this._updatePointerPosition(evt);
  25519. // PreObservable support
  25520. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25521. return;
  25522. }
  25523. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25524. return;
  25525. }
  25526. if (!_this.pointerMovePredicate) {
  25527. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25528. }
  25529. // Meshes
  25530. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25531. _this._processPointerMove(pickResult, evt);
  25532. };
  25533. this._onPointerDown = function (evt) {
  25534. _this._totalPointersPressed++;
  25535. _this._pickedDownMesh = null;
  25536. _this._meshPickProceed = false;
  25537. _this._updatePointerPosition(evt);
  25538. if (_this.preventDefaultOnPointerDown && canvas) {
  25539. evt.preventDefault();
  25540. canvas.focus();
  25541. }
  25542. // PreObservable support
  25543. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25544. return;
  25545. }
  25546. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25547. return;
  25548. }
  25549. _this._pointerCaptures[evt.pointerId] = true;
  25550. _this._startingPointerPosition.x = _this._pointerX;
  25551. _this._startingPointerPosition.y = _this._pointerY;
  25552. _this._startingPointerTime = Date.now();
  25553. if (!_this.pointerDownPredicate) {
  25554. _this.pointerDownPredicate = function (mesh) {
  25555. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25556. };
  25557. }
  25558. // Meshes
  25559. _this._pickedDownMesh = null;
  25560. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25561. _this._processPointerDown(pickResult, evt);
  25562. // Sprites
  25563. _this._pickedDownSprite = null;
  25564. if (_this.spriteManagers.length > 0) {
  25565. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25566. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25567. if (pickResult.pickedSprite.actionManager) {
  25568. _this._pickedDownSprite = pickResult.pickedSprite;
  25569. switch (evt.button) {
  25570. case 0:
  25571. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25572. break;
  25573. case 1:
  25574. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25575. break;
  25576. case 2:
  25577. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25578. break;
  25579. }
  25580. if (pickResult.pickedSprite.actionManager) {
  25581. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25582. }
  25583. }
  25584. }
  25585. }
  25586. };
  25587. this._onPointerUp = function (evt) {
  25588. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25589. return; // So we need to test it the pointer down was pressed before.
  25590. }
  25591. _this._totalPointersPressed--;
  25592. _this._pickedUpMesh = null;
  25593. _this._meshPickProceed = false;
  25594. _this._updatePointerPosition(evt);
  25595. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25596. // PreObservable support
  25597. if (_this.onPrePointerObservable.hasObservers()) {
  25598. if (!clickInfo.ignore) {
  25599. if (!clickInfo.hasSwiped) {
  25600. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25601. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25602. return;
  25603. }
  25604. }
  25605. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25606. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25607. return;
  25608. }
  25609. }
  25610. }
  25611. }
  25612. else {
  25613. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25614. return;
  25615. }
  25616. }
  25617. }
  25618. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25619. return;
  25620. }
  25621. _this._pointerCaptures[evt.pointerId] = false;
  25622. if (!_this.pointerUpPredicate) {
  25623. _this.pointerUpPredicate = function (mesh) {
  25624. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25625. };
  25626. }
  25627. // Meshes
  25628. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25629. _this._initActionManager(null, clickInfo);
  25630. }
  25631. if (!pickResult) {
  25632. pickResult = _this._currentPickResult;
  25633. }
  25634. _this._processPointerUp(pickResult, evt, clickInfo);
  25635. // Sprites
  25636. if (!clickInfo.ignore) {
  25637. if (_this.spriteManagers.length > 0) {
  25638. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25639. if (spritePickResult) {
  25640. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25641. if (spritePickResult.pickedSprite.actionManager) {
  25642. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25643. if (spritePickResult.pickedSprite.actionManager) {
  25644. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25645. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25646. }
  25647. }
  25648. }
  25649. }
  25650. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25651. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25652. }
  25653. }
  25654. }
  25655. }
  25656. _this._previousPickResult = _this._currentPickResult;
  25657. });
  25658. };
  25659. this._onKeyDown = function (evt) {
  25660. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25661. if (_this.onPreKeyboardObservable.hasObservers()) {
  25662. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25663. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25664. if (pi.skipOnPointerObservable) {
  25665. return;
  25666. }
  25667. }
  25668. if (_this.onKeyboardObservable.hasObservers()) {
  25669. var pi = new BABYLON.KeyboardInfo(type, evt);
  25670. _this.onKeyboardObservable.notifyObservers(pi, type);
  25671. }
  25672. if (_this.actionManager) {
  25673. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25674. }
  25675. };
  25676. this._onKeyUp = function (evt) {
  25677. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25678. if (_this.onPreKeyboardObservable.hasObservers()) {
  25679. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25680. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25681. if (pi.skipOnPointerObservable) {
  25682. return;
  25683. }
  25684. }
  25685. if (_this.onKeyboardObservable.hasObservers()) {
  25686. var pi = new BABYLON.KeyboardInfo(type, evt);
  25687. _this.onKeyboardObservable.notifyObservers(pi, type);
  25688. }
  25689. if (_this.actionManager) {
  25690. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25691. }
  25692. };
  25693. var engine = this.getEngine();
  25694. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25695. if (!canvas) {
  25696. return;
  25697. }
  25698. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25699. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25700. });
  25701. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25702. if (!canvas) {
  25703. return;
  25704. }
  25705. canvas.removeEventListener("keydown", _this._onKeyDown);
  25706. canvas.removeEventListener("keyup", _this._onKeyUp);
  25707. });
  25708. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25709. var canvas = this._engine.getRenderingCanvas();
  25710. if (!canvas) {
  25711. return;
  25712. }
  25713. if (attachMove) {
  25714. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25715. // Wheel
  25716. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25717. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25718. }
  25719. if (attachDown) {
  25720. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25721. }
  25722. if (attachUp) {
  25723. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25724. }
  25725. canvas.tabIndex = 1;
  25726. };
  25727. /** Detaches all event handlers*/
  25728. Scene.prototype.detachControl = function () {
  25729. var engine = this.getEngine();
  25730. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25731. var canvas = engine.getRenderingCanvas();
  25732. if (!canvas) {
  25733. return;
  25734. }
  25735. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25736. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25737. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25738. if (this._onCanvasBlurObserver) {
  25739. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25740. }
  25741. if (this._onCanvasFocusObserver) {
  25742. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25743. }
  25744. // Wheel
  25745. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25746. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25747. // Keyboard
  25748. canvas.removeEventListener("keydown", this._onKeyDown);
  25749. canvas.removeEventListener("keyup", this._onKeyUp);
  25750. // Observables
  25751. this.onKeyboardObservable.clear();
  25752. this.onPreKeyboardObservable.clear();
  25753. this.onPointerObservable.clear();
  25754. this.onPrePointerObservable.clear();
  25755. };
  25756. /**
  25757. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25758. * Delay loaded resources are not taking in account
  25759. * @return true if all required resources are ready
  25760. */
  25761. Scene.prototype.isReady = function () {
  25762. if (this._isDisposed) {
  25763. return false;
  25764. }
  25765. if (this._pendingData.length > 0) {
  25766. return false;
  25767. }
  25768. var index;
  25769. var engine = this.getEngine();
  25770. // Geometries
  25771. for (index = 0; index < this.geometries.length; index++) {
  25772. var geometry = this.geometries[index];
  25773. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25774. return false;
  25775. }
  25776. }
  25777. // Meshes
  25778. for (index = 0; index < this.meshes.length; index++) {
  25779. var mesh = this.meshes[index];
  25780. if (!mesh.isEnabled()) {
  25781. continue;
  25782. }
  25783. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25784. continue;
  25785. }
  25786. if (!mesh.isReady(true)) {
  25787. return false;
  25788. }
  25789. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25790. // Is Ready For Mesh
  25791. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25792. var step = _a[_i];
  25793. if (!step.action(mesh, hardwareInstancedRendering)) {
  25794. return false;
  25795. }
  25796. }
  25797. }
  25798. // Post-processes
  25799. if (this.activeCameras && this.activeCameras.length > 0) {
  25800. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25801. var camera = _c[_b];
  25802. if (!camera.isReady(true)) {
  25803. return false;
  25804. }
  25805. }
  25806. }
  25807. else if (this.activeCamera) {
  25808. if (!this.activeCamera.isReady(true)) {
  25809. return false;
  25810. }
  25811. }
  25812. // Particles
  25813. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25814. var particleSystem = _e[_d];
  25815. if (!particleSystem.isReady()) {
  25816. return false;
  25817. }
  25818. }
  25819. return true;
  25820. };
  25821. /** Resets all cached information relative to material (including effect and visibility) */
  25822. Scene.prototype.resetCachedMaterial = function () {
  25823. this._cachedMaterial = null;
  25824. this._cachedEffect = null;
  25825. this._cachedVisibility = null;
  25826. };
  25827. /**
  25828. * Registers a function to be called before every frame render
  25829. * @param func defines the function to register
  25830. */
  25831. Scene.prototype.registerBeforeRender = function (func) {
  25832. this.onBeforeRenderObservable.add(func);
  25833. };
  25834. /**
  25835. * Unregisters a function called before every frame render
  25836. * @param func defines the function to unregister
  25837. */
  25838. Scene.prototype.unregisterBeforeRender = function (func) {
  25839. this.onBeforeRenderObservable.removeCallback(func);
  25840. };
  25841. /**
  25842. * Registers a function to be called after every frame render
  25843. * @param func defines the function to register
  25844. */
  25845. Scene.prototype.registerAfterRender = function (func) {
  25846. this.onAfterRenderObservable.add(func);
  25847. };
  25848. /**
  25849. * Unregisters a function called after every frame render
  25850. * @param func defines the function to unregister
  25851. */
  25852. Scene.prototype.unregisterAfterRender = function (func) {
  25853. this.onAfterRenderObservable.removeCallback(func);
  25854. };
  25855. Scene.prototype._executeOnceBeforeRender = function (func) {
  25856. var _this = this;
  25857. var execFunc = function () {
  25858. func();
  25859. setTimeout(function () {
  25860. _this.unregisterBeforeRender(execFunc);
  25861. });
  25862. };
  25863. this.registerBeforeRender(execFunc);
  25864. };
  25865. /**
  25866. * The provided function will run before render once and will be disposed afterwards.
  25867. * A timeout delay can be provided so that the function will be executed in N ms.
  25868. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25869. * @param func The function to be executed.
  25870. * @param timeout optional delay in ms
  25871. */
  25872. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25873. var _this = this;
  25874. if (timeout !== undefined) {
  25875. setTimeout(function () {
  25876. _this._executeOnceBeforeRender(func);
  25877. }, timeout);
  25878. }
  25879. else {
  25880. this._executeOnceBeforeRender(func);
  25881. }
  25882. };
  25883. /** @hidden */
  25884. Scene.prototype._addPendingData = function (data) {
  25885. this._pendingData.push(data);
  25886. };
  25887. /** @hidden */
  25888. Scene.prototype._removePendingData = function (data) {
  25889. var wasLoading = this.isLoading;
  25890. var index = this._pendingData.indexOf(data);
  25891. if (index !== -1) {
  25892. this._pendingData.splice(index, 1);
  25893. }
  25894. if (wasLoading && !this.isLoading) {
  25895. this.onDataLoadedObservable.notifyObservers(this);
  25896. }
  25897. };
  25898. /**
  25899. * Returns the number of items waiting to be loaded
  25900. * @returns the number of items waiting to be loaded
  25901. */
  25902. Scene.prototype.getWaitingItemsCount = function () {
  25903. return this._pendingData.length;
  25904. };
  25905. Object.defineProperty(Scene.prototype, "isLoading", {
  25906. /**
  25907. * Returns a boolean indicating if the scene is still loading data
  25908. */
  25909. get: function () {
  25910. return this._pendingData.length > 0;
  25911. },
  25912. enumerable: true,
  25913. configurable: true
  25914. });
  25915. /**
  25916. * Registers a function to be executed when the scene is ready
  25917. * @param {Function} func - the function to be executed
  25918. */
  25919. Scene.prototype.executeWhenReady = function (func) {
  25920. var _this = this;
  25921. this.onReadyObservable.add(func);
  25922. if (this._executeWhenReadyTimeoutId !== -1) {
  25923. return;
  25924. }
  25925. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25926. _this._checkIsReady();
  25927. }, 150);
  25928. };
  25929. /**
  25930. * Returns a promise that resolves when the scene is ready
  25931. * @returns A promise that resolves when the scene is ready
  25932. */
  25933. Scene.prototype.whenReadyAsync = function () {
  25934. var _this = this;
  25935. return new Promise(function (resolve) {
  25936. _this.executeWhenReady(function () {
  25937. resolve();
  25938. });
  25939. });
  25940. };
  25941. /** @hidden */
  25942. Scene.prototype._checkIsReady = function () {
  25943. var _this = this;
  25944. this._registerTransientComponents();
  25945. if (this.isReady()) {
  25946. this.onReadyObservable.notifyObservers(this);
  25947. this.onReadyObservable.clear();
  25948. this._executeWhenReadyTimeoutId = -1;
  25949. return;
  25950. }
  25951. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25952. _this._checkIsReady();
  25953. }, 150);
  25954. };
  25955. // Animations
  25956. /**
  25957. * Will start the animation sequence of a given target
  25958. * @param target defines the target
  25959. * @param from defines from which frame should animation start
  25960. * @param to defines until which frame should animation run.
  25961. * @param weight defines the weight to apply to the animation (1.0 by default)
  25962. * @param loop defines if the animation loops
  25963. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25964. * @param onAnimationEnd defines the function to be executed when the animation ends
  25965. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25966. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25967. * @returns the animatable object created for this animation
  25968. */
  25969. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25970. if (weight === void 0) { weight = 1.0; }
  25971. if (speedRatio === void 0) { speedRatio = 1.0; }
  25972. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25973. returnedAnimatable.weight = weight;
  25974. return returnedAnimatable;
  25975. };
  25976. /**
  25977. * Will start the animation sequence of a given target
  25978. * @param target defines the target
  25979. * @param from defines from which frame should animation start
  25980. * @param to defines until which frame should animation run.
  25981. * @param loop defines if the animation loops
  25982. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25983. * @param onAnimationEnd defines the function to be executed when the animation ends
  25984. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25985. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25986. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25987. * @returns the animatable object created for this animation
  25988. */
  25989. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25990. if (speedRatio === void 0) { speedRatio = 1.0; }
  25991. if (stopCurrent === void 0) { stopCurrent = true; }
  25992. if (from > to && speedRatio > 0) {
  25993. speedRatio *= -1;
  25994. }
  25995. if (stopCurrent) {
  25996. this.stopAnimation(target, undefined, targetMask);
  25997. }
  25998. if (!animatable) {
  25999. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26000. }
  26001. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26002. // Local animations
  26003. if (target.animations && shouldRunTargetAnimations) {
  26004. animatable.appendAnimations(target, target.animations);
  26005. }
  26006. // Children animations
  26007. if (target.getAnimatables) {
  26008. var animatables = target.getAnimatables();
  26009. for (var index = 0; index < animatables.length; index++) {
  26010. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26011. }
  26012. }
  26013. animatable.reset();
  26014. return animatable;
  26015. };
  26016. /**
  26017. * Begin a new animation on a given node
  26018. * @param target defines the target where the animation will take place
  26019. * @param animations defines the list of animations to start
  26020. * @param from defines the initial value
  26021. * @param to defines the final value
  26022. * @param loop defines if you want animation to loop (off by default)
  26023. * @param speedRatio defines the speed ratio to apply to all animations
  26024. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26025. * @returns the list of created animatables
  26026. */
  26027. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26028. if (speedRatio === undefined) {
  26029. speedRatio = 1.0;
  26030. }
  26031. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26032. return animatable;
  26033. };
  26034. /**
  26035. * Begin a new animation on a given node and its hierarchy
  26036. * @param target defines the root node where the animation will take place
  26037. * @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.
  26038. * @param animations defines the list of animations to start
  26039. * @param from defines the initial value
  26040. * @param to defines the final value
  26041. * @param loop defines if you want animation to loop (off by default)
  26042. * @param speedRatio defines the speed ratio to apply to all animations
  26043. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26044. * @returns the list of animatables created for all nodes
  26045. */
  26046. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26047. var children = target.getDescendants(directDescendantsOnly);
  26048. var result = [];
  26049. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26050. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26051. var child = children_1[_i];
  26052. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26053. }
  26054. return result;
  26055. };
  26056. /**
  26057. * Gets the animatable associated with a specific target
  26058. * @param target defines the target of the animatable
  26059. * @returns the required animatable if found
  26060. */
  26061. Scene.prototype.getAnimatableByTarget = function (target) {
  26062. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26063. if (this._activeAnimatables[index].target === target) {
  26064. return this._activeAnimatables[index];
  26065. }
  26066. }
  26067. return null;
  26068. };
  26069. /**
  26070. * Gets all animatables associated with a given target
  26071. * @param target defines the target to look animatables for
  26072. * @returns an array of Animatables
  26073. */
  26074. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26075. var result = [];
  26076. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26077. if (this._activeAnimatables[index].target === target) {
  26078. result.push(this._activeAnimatables[index]);
  26079. }
  26080. }
  26081. return result;
  26082. };
  26083. Object.defineProperty(Scene.prototype, "animatables", {
  26084. /**
  26085. * Gets all animatable attached to the scene
  26086. */
  26087. get: function () {
  26088. return this._activeAnimatables;
  26089. },
  26090. enumerable: true,
  26091. configurable: true
  26092. });
  26093. /**
  26094. * Will stop the animation of the given target
  26095. * @param target - the target
  26096. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26097. * @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)
  26098. */
  26099. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26100. var animatables = this.getAllAnimatablesByTarget(target);
  26101. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26102. var animatable = animatables_1[_i];
  26103. animatable.stop(animationName, targetMask);
  26104. }
  26105. };
  26106. /**
  26107. * Stops and removes all animations that have been applied to the scene
  26108. */
  26109. Scene.prototype.stopAllAnimations = function () {
  26110. if (this._activeAnimatables) {
  26111. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26112. this._activeAnimatables[i].stop();
  26113. }
  26114. this._activeAnimatables = [];
  26115. }
  26116. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26117. var group = _a[_i];
  26118. group.stop();
  26119. }
  26120. };
  26121. Scene.prototype._animate = function () {
  26122. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26123. return;
  26124. }
  26125. // Getting time
  26126. var now = BABYLON.Tools.Now;
  26127. if (!this._animationTimeLast) {
  26128. if (this._pendingData.length > 0) {
  26129. return;
  26130. }
  26131. this._animationTimeLast = now;
  26132. }
  26133. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26134. this._animationTime += deltaTime;
  26135. this._animationTimeLast = now;
  26136. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26137. this._activeAnimatables[index]._animate(this._animationTime);
  26138. }
  26139. // Late animation bindings
  26140. this._processLateAnimationBindings();
  26141. };
  26142. /** @hidden */
  26143. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26144. var target = runtimeAnimation.target;
  26145. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26146. if (!target._lateAnimationHolders) {
  26147. target._lateAnimationHolders = {};
  26148. }
  26149. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26150. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26151. totalWeight: 0,
  26152. animations: [],
  26153. originalValue: originalValue
  26154. };
  26155. }
  26156. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26157. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26158. };
  26159. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26160. var normalizer = 1.0;
  26161. var finalPosition = BABYLON.Tmp.Vector3[0];
  26162. var finalScaling = BABYLON.Tmp.Vector3[1];
  26163. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26164. var startIndex = 0;
  26165. var originalAnimation = holder.animations[0];
  26166. var originalValue = holder.originalValue;
  26167. var scale = 1;
  26168. if (holder.totalWeight < 1.0) {
  26169. // We need to mix the original value in
  26170. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26171. scale = 1.0 - holder.totalWeight;
  26172. }
  26173. else {
  26174. startIndex = 1;
  26175. // We need to normalize the weights
  26176. normalizer = holder.totalWeight;
  26177. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26178. scale = originalAnimation.weight / normalizer;
  26179. if (scale == 1) {
  26180. return originalAnimation.currentValue;
  26181. }
  26182. }
  26183. finalScaling.scaleInPlace(scale);
  26184. finalPosition.scaleInPlace(scale);
  26185. finalQuaternion.scaleInPlace(scale);
  26186. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26187. var runtimeAnimation = holder.animations[animIndex];
  26188. var scale = runtimeAnimation.weight / normalizer;
  26189. var currentPosition = BABYLON.Tmp.Vector3[2];
  26190. var currentScaling = BABYLON.Tmp.Vector3[3];
  26191. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26192. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26193. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26194. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26195. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26196. }
  26197. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26198. return originalAnimation._workValue;
  26199. };
  26200. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26201. var originalAnimation = holder.animations[0];
  26202. var originalValue = holder.originalValue;
  26203. if (holder.animations.length === 1) {
  26204. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26205. }
  26206. var normalizer = 1.0;
  26207. var quaternions;
  26208. var weights;
  26209. if (holder.totalWeight < 1.0) {
  26210. var scale = 1.0 - holder.totalWeight;
  26211. quaternions = [];
  26212. weights = [];
  26213. quaternions.push(originalValue);
  26214. weights.push(scale);
  26215. }
  26216. else {
  26217. if (holder.animations.length === 2) { // Slerp as soon as we can
  26218. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26219. }
  26220. quaternions = [];
  26221. weights = [];
  26222. normalizer = holder.totalWeight;
  26223. }
  26224. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26225. var runtimeAnimation = holder.animations[animIndex];
  26226. quaternions.push(runtimeAnimation.currentValue);
  26227. weights.push(runtimeAnimation.weight / normalizer);
  26228. }
  26229. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26230. var cumulativeAmount = 0;
  26231. var cumulativeQuaternion = null;
  26232. for (var index = 0; index < quaternions.length;) {
  26233. if (!cumulativeQuaternion) {
  26234. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26235. cumulativeAmount = weights[index] + weights[index + 1];
  26236. index += 2;
  26237. continue;
  26238. }
  26239. cumulativeAmount += weights[index];
  26240. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26241. index++;
  26242. }
  26243. return cumulativeQuaternion;
  26244. };
  26245. Scene.prototype._processLateAnimationBindings = function () {
  26246. if (!this._registeredForLateAnimationBindings.length) {
  26247. return;
  26248. }
  26249. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26250. var target = this._registeredForLateAnimationBindings.data[index];
  26251. for (var path in target._lateAnimationHolders) {
  26252. var holder = target._lateAnimationHolders[path];
  26253. var originalAnimation = holder.animations[0];
  26254. var originalValue = holder.originalValue;
  26255. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26256. var finalValue = void 0;
  26257. if (matrixDecomposeMode) {
  26258. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26259. }
  26260. else {
  26261. var quaternionMode = originalValue.w !== undefined;
  26262. if (quaternionMode) {
  26263. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26264. }
  26265. else {
  26266. var startIndex = 0;
  26267. var normalizer = 1.0;
  26268. if (holder.totalWeight < 1.0) {
  26269. // We need to mix the original value in
  26270. if (originalValue.scale) {
  26271. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26272. }
  26273. else {
  26274. finalValue = originalValue * (1.0 - holder.totalWeight);
  26275. }
  26276. }
  26277. else {
  26278. // We need to normalize the weights
  26279. normalizer = holder.totalWeight;
  26280. var scale_1 = originalAnimation.weight / normalizer;
  26281. if (scale_1 !== 1) {
  26282. if (originalAnimation.currentValue.scale) {
  26283. finalValue = originalAnimation.currentValue.scale(scale_1);
  26284. }
  26285. else {
  26286. finalValue = originalAnimation.currentValue * scale_1;
  26287. }
  26288. }
  26289. else {
  26290. finalValue = originalAnimation.currentValue;
  26291. }
  26292. startIndex = 1;
  26293. }
  26294. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26295. var runtimeAnimation = holder.animations[animIndex];
  26296. var scale = runtimeAnimation.weight / normalizer;
  26297. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26298. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26299. }
  26300. else {
  26301. finalValue += runtimeAnimation.currentValue * scale;
  26302. }
  26303. }
  26304. }
  26305. }
  26306. target[path] = finalValue;
  26307. }
  26308. target._lateAnimationHolders = {};
  26309. }
  26310. this._registeredForLateAnimationBindings.reset();
  26311. };
  26312. // Matrix
  26313. /** @hidden */
  26314. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26315. this._useAlternateCameraConfiguration = active;
  26316. };
  26317. /**
  26318. * Gets the current view matrix
  26319. * @returns a Matrix
  26320. */
  26321. Scene.prototype.getViewMatrix = function () {
  26322. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26323. };
  26324. /**
  26325. * Gets the current projection matrix
  26326. * @returns a Matrix
  26327. */
  26328. Scene.prototype.getProjectionMatrix = function () {
  26329. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26330. };
  26331. /**
  26332. * Gets the current transform matrix
  26333. * @returns a Matrix made of View * Projection
  26334. */
  26335. Scene.prototype.getTransformMatrix = function () {
  26336. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26337. };
  26338. /**
  26339. * Sets the current transform matrix
  26340. * @param view defines the View matrix to use
  26341. * @param projection defines the Projection matrix to use
  26342. */
  26343. Scene.prototype.setTransformMatrix = function (view, projection) {
  26344. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26345. return;
  26346. }
  26347. this._viewUpdateFlag = view.updateFlag;
  26348. this._projectionUpdateFlag = projection.updateFlag;
  26349. this._viewMatrix = view;
  26350. this._projectionMatrix = projection;
  26351. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26352. // Update frustum
  26353. if (!this._frustumPlanes) {
  26354. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26355. }
  26356. else {
  26357. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26358. }
  26359. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26360. var otherCamera = this.activeCamera._alternateCamera;
  26361. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26362. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26363. }
  26364. if (this._sceneUbo.useUbo) {
  26365. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26366. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26367. this._sceneUbo.update();
  26368. }
  26369. };
  26370. /** @hidden */
  26371. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26372. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26373. return;
  26374. }
  26375. this._alternateViewUpdateFlag = view.updateFlag;
  26376. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26377. this._alternateViewMatrix = view;
  26378. this._alternateProjectionMatrix = projection;
  26379. if (!this._alternateTransformMatrix) {
  26380. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26381. }
  26382. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26383. if (!this._alternateSceneUbo) {
  26384. this._createAlternateUbo();
  26385. }
  26386. if (this._alternateSceneUbo.useUbo) {
  26387. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26388. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26389. this._alternateSceneUbo.update();
  26390. }
  26391. };
  26392. /**
  26393. * Gets the uniform buffer used to store scene data
  26394. * @returns a UniformBuffer
  26395. */
  26396. Scene.prototype.getSceneUniformBuffer = function () {
  26397. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26398. };
  26399. /**
  26400. * Gets an unique (relatively to the current scene) Id
  26401. * @returns an unique number for the scene
  26402. */
  26403. Scene.prototype.getUniqueId = function () {
  26404. var result = Scene._uniqueIdCounter;
  26405. Scene._uniqueIdCounter++;
  26406. return result;
  26407. };
  26408. /**
  26409. * Add a mesh to the list of scene's meshes
  26410. * @param newMesh defines the mesh to add
  26411. * @param recursive if all child meshes should also be added to the scene
  26412. */
  26413. Scene.prototype.addMesh = function (newMesh, recursive) {
  26414. var _this = this;
  26415. if (recursive === void 0) { recursive = false; }
  26416. this.meshes.push(newMesh);
  26417. //notify the collision coordinator
  26418. if (this.collisionCoordinator) {
  26419. this.collisionCoordinator.onMeshAdded(newMesh);
  26420. }
  26421. newMesh._resyncLightSources();
  26422. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26423. if (recursive) {
  26424. newMesh.getChildMeshes().forEach(function (m) {
  26425. _this.addMesh(m);
  26426. });
  26427. }
  26428. };
  26429. /**
  26430. * Remove a mesh for the list of scene's meshes
  26431. * @param toRemove defines the mesh to remove
  26432. * @param recursive if all child meshes should also be removed from the scene
  26433. * @returns the index where the mesh was in the mesh list
  26434. */
  26435. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26436. var _this = this;
  26437. if (recursive === void 0) { recursive = false; }
  26438. var index = this.meshes.indexOf(toRemove);
  26439. if (index !== -1) {
  26440. // Remove from the scene if mesh found
  26441. this.meshes.splice(index, 1);
  26442. }
  26443. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26444. if (recursive) {
  26445. toRemove.getChildMeshes().forEach(function (m) {
  26446. _this.removeMesh(m);
  26447. });
  26448. }
  26449. return index;
  26450. };
  26451. /**
  26452. * Add a transform node to the list of scene's transform nodes
  26453. * @param newTransformNode defines the transform node to add
  26454. */
  26455. Scene.prototype.addTransformNode = function (newTransformNode) {
  26456. this.transformNodes.push(newTransformNode);
  26457. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26458. };
  26459. /**
  26460. * Remove a transform node for the list of scene's transform nodes
  26461. * @param toRemove defines the transform node to remove
  26462. * @returns the index where the transform node was in the transform node list
  26463. */
  26464. Scene.prototype.removeTransformNode = function (toRemove) {
  26465. var index = this.transformNodes.indexOf(toRemove);
  26466. if (index !== -1) {
  26467. // Remove from the scene if found
  26468. this.transformNodes.splice(index, 1);
  26469. }
  26470. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26471. return index;
  26472. };
  26473. /**
  26474. * Remove a skeleton for the list of scene's skeletons
  26475. * @param toRemove defines the skeleton to remove
  26476. * @returns the index where the skeleton was in the skeleton list
  26477. */
  26478. Scene.prototype.removeSkeleton = function (toRemove) {
  26479. var index = this.skeletons.indexOf(toRemove);
  26480. if (index !== -1) {
  26481. // Remove from the scene if found
  26482. this.skeletons.splice(index, 1);
  26483. }
  26484. return index;
  26485. };
  26486. /**
  26487. * Remove a morph target for the list of scene's morph targets
  26488. * @param toRemove defines the morph target to remove
  26489. * @returns the index where the morph target was in the morph target list
  26490. */
  26491. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26492. var index = this.morphTargetManagers.indexOf(toRemove);
  26493. if (index !== -1) {
  26494. // Remove from the scene if found
  26495. this.morphTargetManagers.splice(index, 1);
  26496. }
  26497. return index;
  26498. };
  26499. /**
  26500. * Remove a light for the list of scene's lights
  26501. * @param toRemove defines the light to remove
  26502. * @returns the index where the light was in the light list
  26503. */
  26504. Scene.prototype.removeLight = function (toRemove) {
  26505. var index = this.lights.indexOf(toRemove);
  26506. if (index !== -1) {
  26507. // Remove from meshes
  26508. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26509. var mesh = _a[_i];
  26510. mesh._removeLightSource(toRemove);
  26511. }
  26512. // Remove from the scene if mesh found
  26513. this.lights.splice(index, 1);
  26514. this.sortLightsByPriority();
  26515. }
  26516. this.onLightRemovedObservable.notifyObservers(toRemove);
  26517. return index;
  26518. };
  26519. /**
  26520. * Remove a camera for the list of scene's cameras
  26521. * @param toRemove defines the camera to remove
  26522. * @returns the index where the camera was in the camera list
  26523. */
  26524. Scene.prototype.removeCamera = function (toRemove) {
  26525. var index = this.cameras.indexOf(toRemove);
  26526. if (index !== -1) {
  26527. // Remove from the scene if mesh found
  26528. this.cameras.splice(index, 1);
  26529. }
  26530. // Remove from activeCameras
  26531. var index2 = this.activeCameras.indexOf(toRemove);
  26532. if (index2 !== -1) {
  26533. // Remove from the scene if mesh found
  26534. this.activeCameras.splice(index2, 1);
  26535. }
  26536. // Reset the activeCamera
  26537. if (this.activeCamera === toRemove) {
  26538. if (this.cameras.length > 0) {
  26539. this.activeCamera = this.cameras[0];
  26540. }
  26541. else {
  26542. this.activeCamera = null;
  26543. }
  26544. }
  26545. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26546. return index;
  26547. };
  26548. /**
  26549. * Remove a particle system for the list of scene's particle systems
  26550. * @param toRemove defines the particle system to remove
  26551. * @returns the index where the particle system was in the particle system list
  26552. */
  26553. Scene.prototype.removeParticleSystem = function (toRemove) {
  26554. var index = this.particleSystems.indexOf(toRemove);
  26555. if (index !== -1) {
  26556. this.particleSystems.splice(index, 1);
  26557. }
  26558. return index;
  26559. };
  26560. /**
  26561. * Remove a animation for the list of scene's animations
  26562. * @param toRemove defines the animation to remove
  26563. * @returns the index where the animation was in the animation list
  26564. */
  26565. Scene.prototype.removeAnimation = function (toRemove) {
  26566. var index = this.animations.indexOf(toRemove);
  26567. if (index !== -1) {
  26568. this.animations.splice(index, 1);
  26569. }
  26570. return index;
  26571. };
  26572. /**
  26573. * Removes the given animation group from this scene.
  26574. * @param toRemove The animation group to remove
  26575. * @returns The index of the removed animation group
  26576. */
  26577. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26578. var index = this.animationGroups.indexOf(toRemove);
  26579. if (index !== -1) {
  26580. this.animationGroups.splice(index, 1);
  26581. }
  26582. return index;
  26583. };
  26584. /**
  26585. * Removes the given multi-material from this scene.
  26586. * @param toRemove The multi-material to remove
  26587. * @returns The index of the removed multi-material
  26588. */
  26589. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26590. var index = this.multiMaterials.indexOf(toRemove);
  26591. if (index !== -1) {
  26592. this.multiMaterials.splice(index, 1);
  26593. }
  26594. return index;
  26595. };
  26596. /**
  26597. * Removes the given material from this scene.
  26598. * @param toRemove The material to remove
  26599. * @returns The index of the removed material
  26600. */
  26601. Scene.prototype.removeMaterial = function (toRemove) {
  26602. var index = this.materials.indexOf(toRemove);
  26603. if (index !== -1) {
  26604. this.materials.splice(index, 1);
  26605. }
  26606. return index;
  26607. };
  26608. /**
  26609. * Removes the given action manager from this scene.
  26610. * @param toRemove The action manager to remove
  26611. * @returns The index of the removed action manager
  26612. */
  26613. Scene.prototype.removeActionManager = function (toRemove) {
  26614. var index = this.actionManagers.indexOf(toRemove);
  26615. if (index !== -1) {
  26616. this.actionManagers.splice(index, 1);
  26617. }
  26618. return index;
  26619. };
  26620. /**
  26621. * Removes the given texture from this scene.
  26622. * @param toRemove The texture to remove
  26623. * @returns The index of the removed texture
  26624. */
  26625. Scene.prototype.removeTexture = function (toRemove) {
  26626. var index = this.textures.indexOf(toRemove);
  26627. if (index !== -1) {
  26628. this.textures.splice(index, 1);
  26629. }
  26630. return index;
  26631. };
  26632. /**
  26633. * Adds the given light to this scene
  26634. * @param newLight The light to add
  26635. */
  26636. Scene.prototype.addLight = function (newLight) {
  26637. this.lights.push(newLight);
  26638. this.sortLightsByPriority();
  26639. // Add light to all meshes (To support if the light is removed and then readded)
  26640. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26641. var mesh = _a[_i];
  26642. if (mesh._lightSources.indexOf(newLight) === -1) {
  26643. mesh._lightSources.push(newLight);
  26644. mesh._resyncLightSources();
  26645. }
  26646. }
  26647. this.onNewLightAddedObservable.notifyObservers(newLight);
  26648. };
  26649. /**
  26650. * Sorts the list list based on light priorities
  26651. */
  26652. Scene.prototype.sortLightsByPriority = function () {
  26653. if (this.requireLightSorting) {
  26654. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26655. }
  26656. };
  26657. /**
  26658. * Adds the given camera to this scene
  26659. * @param newCamera The camera to add
  26660. */
  26661. Scene.prototype.addCamera = function (newCamera) {
  26662. this.cameras.push(newCamera);
  26663. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26664. };
  26665. /**
  26666. * Adds the given skeleton to this scene
  26667. * @param newSkeleton The skeleton to add
  26668. */
  26669. Scene.prototype.addSkeleton = function (newSkeleton) {
  26670. this.skeletons.push(newSkeleton);
  26671. };
  26672. /**
  26673. * Adds the given particle system to this scene
  26674. * @param newParticleSystem The particle system to add
  26675. */
  26676. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26677. this.particleSystems.push(newParticleSystem);
  26678. };
  26679. /**
  26680. * Adds the given animation to this scene
  26681. * @param newAnimation The animation to add
  26682. */
  26683. Scene.prototype.addAnimation = function (newAnimation) {
  26684. this.animations.push(newAnimation);
  26685. };
  26686. /**
  26687. * Adds the given animation group to this scene.
  26688. * @param newAnimationGroup The animation group to add
  26689. */
  26690. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26691. this.animationGroups.push(newAnimationGroup);
  26692. };
  26693. /**
  26694. * Adds the given multi-material to this scene
  26695. * @param newMultiMaterial The multi-material to add
  26696. */
  26697. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26698. this.multiMaterials.push(newMultiMaterial);
  26699. };
  26700. /**
  26701. * Adds the given material to this scene
  26702. * @param newMaterial The material to add
  26703. */
  26704. Scene.prototype.addMaterial = function (newMaterial) {
  26705. this.materials.push(newMaterial);
  26706. };
  26707. /**
  26708. * Adds the given morph target to this scene
  26709. * @param newMorphTargetManager The morph target to add
  26710. */
  26711. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26712. this.morphTargetManagers.push(newMorphTargetManager);
  26713. };
  26714. /**
  26715. * Adds the given geometry to this scene
  26716. * @param newGeometry The geometry to add
  26717. */
  26718. Scene.prototype.addGeometry = function (newGeometry) {
  26719. this.geometries.push(newGeometry);
  26720. };
  26721. /**
  26722. * Adds the given action manager to this scene
  26723. * @param newActionManager The action manager to add
  26724. */
  26725. Scene.prototype.addActionManager = function (newActionManager) {
  26726. this.actionManagers.push(newActionManager);
  26727. };
  26728. /**
  26729. * Adds the given texture to this scene.
  26730. * @param newTexture The texture to add
  26731. */
  26732. Scene.prototype.addTexture = function (newTexture) {
  26733. this.textures.push(newTexture);
  26734. };
  26735. /**
  26736. * Switch active camera
  26737. * @param newCamera defines the new active camera
  26738. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26739. */
  26740. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26741. if (attachControl === void 0) { attachControl = true; }
  26742. var canvas = this._engine.getRenderingCanvas();
  26743. if (!canvas) {
  26744. return;
  26745. }
  26746. if (this.activeCamera) {
  26747. this.activeCamera.detachControl(canvas);
  26748. }
  26749. this.activeCamera = newCamera;
  26750. if (attachControl) {
  26751. newCamera.attachControl(canvas);
  26752. }
  26753. };
  26754. /**
  26755. * sets the active camera of the scene using its ID
  26756. * @param id defines the camera's ID
  26757. * @return the new active camera or null if none found.
  26758. */
  26759. Scene.prototype.setActiveCameraByID = function (id) {
  26760. var camera = this.getCameraByID(id);
  26761. if (camera) {
  26762. this.activeCamera = camera;
  26763. return camera;
  26764. }
  26765. return null;
  26766. };
  26767. /**
  26768. * sets the active camera of the scene using its name
  26769. * @param name defines the camera's name
  26770. * @returns the new active camera or null if none found.
  26771. */
  26772. Scene.prototype.setActiveCameraByName = function (name) {
  26773. var camera = this.getCameraByName(name);
  26774. if (camera) {
  26775. this.activeCamera = camera;
  26776. return camera;
  26777. }
  26778. return null;
  26779. };
  26780. /**
  26781. * get an animation group using its name
  26782. * @param name defines the material's name
  26783. * @return the animation group or null if none found.
  26784. */
  26785. Scene.prototype.getAnimationGroupByName = function (name) {
  26786. for (var index = 0; index < this.animationGroups.length; index++) {
  26787. if (this.animationGroups[index].name === name) {
  26788. return this.animationGroups[index];
  26789. }
  26790. }
  26791. return null;
  26792. };
  26793. /**
  26794. * get a material using its id
  26795. * @param id defines the material's ID
  26796. * @return the material or null if none found.
  26797. */
  26798. Scene.prototype.getMaterialByID = function (id) {
  26799. for (var index = 0; index < this.materials.length; index++) {
  26800. if (this.materials[index].id === id) {
  26801. return this.materials[index];
  26802. }
  26803. }
  26804. return null;
  26805. };
  26806. /**
  26807. * Gets a material using its name
  26808. * @param name defines the material's name
  26809. * @return the material or null if none found.
  26810. */
  26811. Scene.prototype.getMaterialByName = function (name) {
  26812. for (var index = 0; index < this.materials.length; index++) {
  26813. if (this.materials[index].name === name) {
  26814. return this.materials[index];
  26815. }
  26816. }
  26817. return null;
  26818. };
  26819. /**
  26820. * Gets a camera using its id
  26821. * @param id defines the id to look for
  26822. * @returns the camera or null if not found
  26823. */
  26824. Scene.prototype.getCameraByID = function (id) {
  26825. for (var index = 0; index < this.cameras.length; index++) {
  26826. if (this.cameras[index].id === id) {
  26827. return this.cameras[index];
  26828. }
  26829. }
  26830. return null;
  26831. };
  26832. /**
  26833. * Gets a camera using its unique id
  26834. * @param uniqueId defines the unique id to look for
  26835. * @returns the camera or null if not found
  26836. */
  26837. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26838. for (var index = 0; index < this.cameras.length; index++) {
  26839. if (this.cameras[index].uniqueId === uniqueId) {
  26840. return this.cameras[index];
  26841. }
  26842. }
  26843. return null;
  26844. };
  26845. /**
  26846. * Gets a camera using its name
  26847. * @param name defines the camera's name
  26848. * @return the camera or null if none found.
  26849. */
  26850. Scene.prototype.getCameraByName = function (name) {
  26851. for (var index = 0; index < this.cameras.length; index++) {
  26852. if (this.cameras[index].name === name) {
  26853. return this.cameras[index];
  26854. }
  26855. }
  26856. return null;
  26857. };
  26858. /**
  26859. * Gets a bone using its id
  26860. * @param id defines the bone's id
  26861. * @return the bone or null if not found
  26862. */
  26863. Scene.prototype.getBoneByID = function (id) {
  26864. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26865. var skeleton = this.skeletons[skeletonIndex];
  26866. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26867. if (skeleton.bones[boneIndex].id === id) {
  26868. return skeleton.bones[boneIndex];
  26869. }
  26870. }
  26871. }
  26872. return null;
  26873. };
  26874. /**
  26875. * Gets a bone using its id
  26876. * @param name defines the bone's name
  26877. * @return the bone or null if not found
  26878. */
  26879. Scene.prototype.getBoneByName = function (name) {
  26880. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26881. var skeleton = this.skeletons[skeletonIndex];
  26882. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26883. if (skeleton.bones[boneIndex].name === name) {
  26884. return skeleton.bones[boneIndex];
  26885. }
  26886. }
  26887. }
  26888. return null;
  26889. };
  26890. /**
  26891. * Gets a light node using its name
  26892. * @param name defines the the light's name
  26893. * @return the light or null if none found.
  26894. */
  26895. Scene.prototype.getLightByName = function (name) {
  26896. for (var index = 0; index < this.lights.length; index++) {
  26897. if (this.lights[index].name === name) {
  26898. return this.lights[index];
  26899. }
  26900. }
  26901. return null;
  26902. };
  26903. /**
  26904. * Gets a light node using its id
  26905. * @param id defines the light's id
  26906. * @return the light or null if none found.
  26907. */
  26908. Scene.prototype.getLightByID = function (id) {
  26909. for (var index = 0; index < this.lights.length; index++) {
  26910. if (this.lights[index].id === id) {
  26911. return this.lights[index];
  26912. }
  26913. }
  26914. return null;
  26915. };
  26916. /**
  26917. * Gets a light node using its scene-generated unique ID
  26918. * @param uniqueId defines the light's unique id
  26919. * @return the light or null if none found.
  26920. */
  26921. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26922. for (var index = 0; index < this.lights.length; index++) {
  26923. if (this.lights[index].uniqueId === uniqueId) {
  26924. return this.lights[index];
  26925. }
  26926. }
  26927. return null;
  26928. };
  26929. /**
  26930. * Gets a particle system by id
  26931. * @param id defines the particle system id
  26932. * @return the corresponding system or null if none found
  26933. */
  26934. Scene.prototype.getParticleSystemByID = function (id) {
  26935. for (var index = 0; index < this.particleSystems.length; index++) {
  26936. if (this.particleSystems[index].id === id) {
  26937. return this.particleSystems[index];
  26938. }
  26939. }
  26940. return null;
  26941. };
  26942. /**
  26943. * Gets a geometry using its ID
  26944. * @param id defines the geometry's id
  26945. * @return the geometry or null if none found.
  26946. */
  26947. Scene.prototype.getGeometryByID = function (id) {
  26948. for (var index = 0; index < this.geometries.length; index++) {
  26949. if (this.geometries[index].id === id) {
  26950. return this.geometries[index];
  26951. }
  26952. }
  26953. return null;
  26954. };
  26955. /**
  26956. * Add a new geometry to this scene
  26957. * @param geometry defines the geometry to be added to the scene.
  26958. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26959. * @return a boolean defining if the geometry was added or not
  26960. */
  26961. Scene.prototype.pushGeometry = function (geometry, force) {
  26962. if (!force && this.getGeometryByID(geometry.id)) {
  26963. return false;
  26964. }
  26965. this.geometries.push(geometry);
  26966. //notify the collision coordinator
  26967. if (this.collisionCoordinator) {
  26968. this.collisionCoordinator.onGeometryAdded(geometry);
  26969. }
  26970. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26971. return true;
  26972. };
  26973. /**
  26974. * Removes an existing geometry
  26975. * @param geometry defines the geometry to be removed from the scene
  26976. * @return a boolean defining if the geometry was removed or not
  26977. */
  26978. Scene.prototype.removeGeometry = function (geometry) {
  26979. var index = this.geometries.indexOf(geometry);
  26980. if (index > -1) {
  26981. this.geometries.splice(index, 1);
  26982. //notify the collision coordinator
  26983. if (this.collisionCoordinator) {
  26984. this.collisionCoordinator.onGeometryDeleted(geometry);
  26985. }
  26986. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26987. return true;
  26988. }
  26989. return false;
  26990. };
  26991. /**
  26992. * Gets the list of geometries attached to the scene
  26993. * @returns an array of Geometry
  26994. */
  26995. Scene.prototype.getGeometries = function () {
  26996. return this.geometries;
  26997. };
  26998. /**
  26999. * Gets the first added mesh found of a given ID
  27000. * @param id defines the id to search for
  27001. * @return the mesh found or null if not found at all
  27002. */
  27003. Scene.prototype.getMeshByID = function (id) {
  27004. for (var index = 0; index < this.meshes.length; index++) {
  27005. if (this.meshes[index].id === id) {
  27006. return this.meshes[index];
  27007. }
  27008. }
  27009. return null;
  27010. };
  27011. /**
  27012. * Gets a list of meshes using their id
  27013. * @param id defines the id to search for
  27014. * @returns a list of meshes
  27015. */
  27016. Scene.prototype.getMeshesByID = function (id) {
  27017. return this.meshes.filter(function (m) {
  27018. return m.id === id;
  27019. });
  27020. };
  27021. /**
  27022. * Gets the first added transform node found of a given ID
  27023. * @param id defines the id to search for
  27024. * @return the found transform node or null if not found at all.
  27025. */
  27026. Scene.prototype.getTransformNodeByID = function (id) {
  27027. for (var index = 0; index < this.transformNodes.length; index++) {
  27028. if (this.transformNodes[index].id === id) {
  27029. return this.transformNodes[index];
  27030. }
  27031. }
  27032. return null;
  27033. };
  27034. /**
  27035. * Gets a list of transform nodes using their id
  27036. * @param id defines the id to search for
  27037. * @returns a list of transform nodes
  27038. */
  27039. Scene.prototype.getTransformNodesByID = function (id) {
  27040. return this.transformNodes.filter(function (m) {
  27041. return m.id === id;
  27042. });
  27043. };
  27044. /**
  27045. * Gets a mesh with its auto-generated unique id
  27046. * @param uniqueId defines the unique id to search for
  27047. * @return the found mesh or null if not found at all.
  27048. */
  27049. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27050. for (var index = 0; index < this.meshes.length; index++) {
  27051. if (this.meshes[index].uniqueId === uniqueId) {
  27052. return this.meshes[index];
  27053. }
  27054. }
  27055. return null;
  27056. };
  27057. /**
  27058. * Gets a the last added mesh using a given id
  27059. * @param id defines the id to search for
  27060. * @return the found mesh or null if not found at all.
  27061. */
  27062. Scene.prototype.getLastMeshByID = function (id) {
  27063. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27064. if (this.meshes[index].id === id) {
  27065. return this.meshes[index];
  27066. }
  27067. }
  27068. return null;
  27069. };
  27070. /**
  27071. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27072. * @param id defines the id to search for
  27073. * @return the found node or null if not found at all
  27074. */
  27075. Scene.prototype.getLastEntryByID = function (id) {
  27076. var index;
  27077. for (index = this.meshes.length - 1; index >= 0; index--) {
  27078. if (this.meshes[index].id === id) {
  27079. return this.meshes[index];
  27080. }
  27081. }
  27082. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27083. if (this.transformNodes[index].id === id) {
  27084. return this.transformNodes[index];
  27085. }
  27086. }
  27087. for (index = this.cameras.length - 1; index >= 0; index--) {
  27088. if (this.cameras[index].id === id) {
  27089. return this.cameras[index];
  27090. }
  27091. }
  27092. for (index = this.lights.length - 1; index >= 0; index--) {
  27093. if (this.lights[index].id === id) {
  27094. return this.lights[index];
  27095. }
  27096. }
  27097. return null;
  27098. };
  27099. /**
  27100. * Gets a node (Mesh, Camera, Light) using a given id
  27101. * @param id defines the id to search for
  27102. * @return the found node or null if not found at all
  27103. */
  27104. Scene.prototype.getNodeByID = function (id) {
  27105. var mesh = this.getMeshByID(id);
  27106. if (mesh) {
  27107. return mesh;
  27108. }
  27109. var light = this.getLightByID(id);
  27110. if (light) {
  27111. return light;
  27112. }
  27113. var camera = this.getCameraByID(id);
  27114. if (camera) {
  27115. return camera;
  27116. }
  27117. var bone = this.getBoneByID(id);
  27118. return bone;
  27119. };
  27120. /**
  27121. * Gets a node (Mesh, Camera, Light) using a given name
  27122. * @param name defines the name to search for
  27123. * @return the found node or null if not found at all.
  27124. */
  27125. Scene.prototype.getNodeByName = function (name) {
  27126. var mesh = this.getMeshByName(name);
  27127. if (mesh) {
  27128. return mesh;
  27129. }
  27130. var light = this.getLightByName(name);
  27131. if (light) {
  27132. return light;
  27133. }
  27134. var camera = this.getCameraByName(name);
  27135. if (camera) {
  27136. return camera;
  27137. }
  27138. var bone = this.getBoneByName(name);
  27139. return bone;
  27140. };
  27141. /**
  27142. * Gets a mesh using a given name
  27143. * @param name defines the name to search for
  27144. * @return the found mesh or null if not found at all.
  27145. */
  27146. Scene.prototype.getMeshByName = function (name) {
  27147. for (var index = 0; index < this.meshes.length; index++) {
  27148. if (this.meshes[index].name === name) {
  27149. return this.meshes[index];
  27150. }
  27151. }
  27152. return null;
  27153. };
  27154. /**
  27155. * Gets a transform node using a given name
  27156. * @param name defines the name to search for
  27157. * @return the found transform node or null if not found at all.
  27158. */
  27159. Scene.prototype.getTransformNodeByName = function (name) {
  27160. for (var index = 0; index < this.transformNodes.length; index++) {
  27161. if (this.transformNodes[index].name === name) {
  27162. return this.transformNodes[index];
  27163. }
  27164. }
  27165. return null;
  27166. };
  27167. /**
  27168. * Gets a sound using a given name
  27169. * @param name defines the name to search for
  27170. * @return the found sound or null if not found at all.
  27171. */
  27172. Scene.prototype.getSoundByName = function (name) {
  27173. var index;
  27174. if (BABYLON.AudioEngine) {
  27175. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27176. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27177. return this.mainSoundTrack.soundCollection[index];
  27178. }
  27179. }
  27180. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27181. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27182. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27183. return this.soundTracks[sdIndex].soundCollection[index];
  27184. }
  27185. }
  27186. }
  27187. }
  27188. return null;
  27189. };
  27190. /**
  27191. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27192. * @param id defines the id to search for
  27193. * @return the found skeleton or null if not found at all.
  27194. */
  27195. Scene.prototype.getLastSkeletonByID = function (id) {
  27196. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27197. if (this.skeletons[index].id === id) {
  27198. return this.skeletons[index];
  27199. }
  27200. }
  27201. return null;
  27202. };
  27203. /**
  27204. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27205. * @param id defines the id to search for
  27206. * @return the found skeleton or null if not found at all.
  27207. */
  27208. Scene.prototype.getSkeletonById = function (id) {
  27209. for (var index = 0; index < this.skeletons.length; index++) {
  27210. if (this.skeletons[index].id === id) {
  27211. return this.skeletons[index];
  27212. }
  27213. }
  27214. return null;
  27215. };
  27216. /**
  27217. * Gets a skeleton using a given name
  27218. * @param name defines the name to search for
  27219. * @return the found skeleton or null if not found at all.
  27220. */
  27221. Scene.prototype.getSkeletonByName = function (name) {
  27222. for (var index = 0; index < this.skeletons.length; index++) {
  27223. if (this.skeletons[index].name === name) {
  27224. return this.skeletons[index];
  27225. }
  27226. }
  27227. return null;
  27228. };
  27229. /**
  27230. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27231. * @param id defines the id to search for
  27232. * @return the found morph target manager or null if not found at all.
  27233. */
  27234. Scene.prototype.getMorphTargetManagerById = function (id) {
  27235. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27236. if (this.morphTargetManagers[index].uniqueId === id) {
  27237. return this.morphTargetManagers[index];
  27238. }
  27239. }
  27240. return null;
  27241. };
  27242. /**
  27243. * Gets a boolean indicating if the given mesh is active
  27244. * @param mesh defines the mesh to look for
  27245. * @returns true if the mesh is in the active list
  27246. */
  27247. Scene.prototype.isActiveMesh = function (mesh) {
  27248. return (this._activeMeshes.indexOf(mesh) !== -1);
  27249. };
  27250. Object.defineProperty(Scene.prototype, "uid", {
  27251. /**
  27252. * Return a unique id as a string which can serve as an identifier for the scene
  27253. */
  27254. get: function () {
  27255. if (!this._uid) {
  27256. this._uid = BABYLON.Tools.RandomId();
  27257. }
  27258. return this._uid;
  27259. },
  27260. enumerable: true,
  27261. configurable: true
  27262. });
  27263. /**
  27264. * Add an externaly attached data from its key.
  27265. * This method call will fail and return false, if such key already exists.
  27266. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27267. * @param key the unique key that identifies the data
  27268. * @param data the data object to associate to the key for this Engine instance
  27269. * @return true if no such key were already present and the data was added successfully, false otherwise
  27270. */
  27271. Scene.prototype.addExternalData = function (key, data) {
  27272. if (!this._externalData) {
  27273. this._externalData = new BABYLON.StringDictionary();
  27274. }
  27275. return this._externalData.add(key, data);
  27276. };
  27277. /**
  27278. * Get an externaly attached data from its key
  27279. * @param key the unique key that identifies the data
  27280. * @return the associated data, if present (can be null), or undefined if not present
  27281. */
  27282. Scene.prototype.getExternalData = function (key) {
  27283. if (!this._externalData) {
  27284. return null;
  27285. }
  27286. return this._externalData.get(key);
  27287. };
  27288. /**
  27289. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27290. * @param key the unique key that identifies the data
  27291. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27292. * @return the associated data, can be null if the factory returned null.
  27293. */
  27294. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27295. if (!this._externalData) {
  27296. this._externalData = new BABYLON.StringDictionary();
  27297. }
  27298. return this._externalData.getOrAddWithFactory(key, factory);
  27299. };
  27300. /**
  27301. * Remove an externaly attached data from the Engine instance
  27302. * @param key the unique key that identifies the data
  27303. * @return true if the data was successfully removed, false if it doesn't exist
  27304. */
  27305. Scene.prototype.removeExternalData = function (key) {
  27306. return this._externalData.remove(key);
  27307. };
  27308. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27309. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27310. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27311. var step = _a[_i];
  27312. step.action(mesh, subMesh);
  27313. }
  27314. var material = subMesh.getMaterial();
  27315. if (material !== null && material !== undefined) {
  27316. // Render targets
  27317. if (material.getRenderTargetTextures !== undefined) {
  27318. if (this._processedMaterials.indexOf(material) === -1) {
  27319. this._processedMaterials.push(material);
  27320. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27321. }
  27322. }
  27323. // Dispatch
  27324. this._activeIndices.addCount(subMesh.indexCount, false);
  27325. this._renderingManager.dispatch(subMesh, mesh, material);
  27326. }
  27327. }
  27328. };
  27329. /**
  27330. * Clear the processed materials smart array preventing retention point in material dispose.
  27331. */
  27332. Scene.prototype.freeProcessedMaterials = function () {
  27333. this._processedMaterials.dispose();
  27334. };
  27335. /**
  27336. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27337. */
  27338. Scene.prototype.freeActiveMeshes = function () {
  27339. this._activeMeshes.dispose();
  27340. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27341. this.activeCamera._activeMeshes.dispose();
  27342. }
  27343. if (this.activeCameras) {
  27344. for (var i = 0; i < this.activeCameras.length; i++) {
  27345. var activeCamera = this.activeCameras[i];
  27346. if (activeCamera && activeCamera._activeMeshes) {
  27347. activeCamera._activeMeshes.dispose();
  27348. }
  27349. }
  27350. }
  27351. };
  27352. /**
  27353. * Clear the info related to rendering groups preventing retention points during dispose.
  27354. */
  27355. Scene.prototype.freeRenderingGroups = function () {
  27356. if (this._renderingManager) {
  27357. this._renderingManager.freeRenderingGroups();
  27358. }
  27359. if (this.textures) {
  27360. for (var i = 0; i < this.textures.length; i++) {
  27361. var texture = this.textures[i];
  27362. if (texture && texture.renderList) {
  27363. texture.freeRenderingGroups();
  27364. }
  27365. }
  27366. }
  27367. };
  27368. /** @hidden */
  27369. Scene.prototype._isInIntermediateRendering = function () {
  27370. return this._intermediateRendering;
  27371. };
  27372. /**
  27373. * Defines the current active mesh candidate provider
  27374. * @param provider defines the provider to use
  27375. */
  27376. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27377. this._activeMeshCandidateProvider = provider;
  27378. };
  27379. /**
  27380. * Gets the current active mesh candidate provider
  27381. * @returns the current active mesh candidate provider
  27382. */
  27383. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27384. return this._activeMeshCandidateProvider;
  27385. };
  27386. /**
  27387. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27388. * @returns the current scene
  27389. */
  27390. Scene.prototype.freezeActiveMeshes = function () {
  27391. if (!this.activeCamera) {
  27392. return this;
  27393. }
  27394. if (!this._frustumPlanes) {
  27395. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27396. }
  27397. this._evaluateActiveMeshes();
  27398. this._activeMeshesFrozen = true;
  27399. return this;
  27400. };
  27401. /**
  27402. * Use this function to restart evaluating active meshes on every frame
  27403. * @returns the current scene
  27404. */
  27405. Scene.prototype.unfreezeActiveMeshes = function () {
  27406. this._activeMeshesFrozen = false;
  27407. return this;
  27408. };
  27409. Scene.prototype._evaluateActiveMeshes = function () {
  27410. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27411. return;
  27412. }
  27413. if (!this.activeCamera) {
  27414. return;
  27415. }
  27416. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27417. this.activeCamera._activeMeshes.reset();
  27418. this._activeMeshes.reset();
  27419. this._renderingManager.reset();
  27420. this._processedMaterials.reset();
  27421. this._activeParticleSystems.reset();
  27422. this._activeSkeletons.reset();
  27423. this._softwareSkinnedMeshes.reset();
  27424. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27425. var step = _a[_i];
  27426. step.action();
  27427. }
  27428. // Meshes
  27429. var meshes;
  27430. var len;
  27431. var checkIsEnabled = true;
  27432. // Determine mesh candidates
  27433. if (this._activeMeshCandidateProvider !== undefined) {
  27434. // Use _activeMeshCandidateProvider
  27435. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27436. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27437. if (meshes !== undefined) {
  27438. len = meshes.length;
  27439. }
  27440. else {
  27441. len = 0;
  27442. }
  27443. }
  27444. else if (this._selectionOctree !== undefined) {
  27445. // Octree
  27446. var selection = this._selectionOctree.select(this._frustumPlanes);
  27447. meshes = selection.data;
  27448. len = selection.length;
  27449. }
  27450. else {
  27451. // Full scene traversal
  27452. len = this.meshes.length;
  27453. meshes = this.meshes;
  27454. }
  27455. // Check each mesh
  27456. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27457. mesh = meshes[meshIndex];
  27458. if (mesh.isBlocked) {
  27459. continue;
  27460. }
  27461. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27462. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27463. continue;
  27464. }
  27465. mesh.computeWorldMatrix();
  27466. // Intersections
  27467. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27468. this._meshesForIntersections.pushNoDuplicate(mesh);
  27469. }
  27470. // Switch to current LOD
  27471. meshLOD = mesh.getLOD(this.activeCamera);
  27472. if (meshLOD === undefined || meshLOD === null) {
  27473. continue;
  27474. }
  27475. mesh._preActivate();
  27476. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27477. this._activeMeshes.push(mesh);
  27478. this.activeCamera._activeMeshes.push(mesh);
  27479. mesh._activate(this._renderId);
  27480. if (meshLOD !== mesh) {
  27481. meshLOD._activate(this._renderId);
  27482. }
  27483. this._activeMesh(mesh, meshLOD);
  27484. }
  27485. }
  27486. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27487. // Particle systems
  27488. if (this.particlesEnabled) {
  27489. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27490. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27491. var particleSystem = this.particleSystems[particleIndex];
  27492. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27493. continue;
  27494. }
  27495. var emitter = particleSystem.emitter;
  27496. if (!emitter.position || emitter.isEnabled()) {
  27497. this._activeParticleSystems.push(particleSystem);
  27498. particleSystem.animate();
  27499. this._renderingManager.dispatchParticles(particleSystem);
  27500. }
  27501. }
  27502. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27503. }
  27504. };
  27505. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27506. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27507. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27508. mesh.skeleton.prepare();
  27509. }
  27510. if (!mesh.computeBonesUsingShaders) {
  27511. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27512. }
  27513. }
  27514. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27515. var step = _a[_i];
  27516. step.action(sourceMesh, mesh);
  27517. }
  27518. if (mesh !== undefined && mesh !== null
  27519. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27520. // Submeshes Octrees
  27521. var len;
  27522. var subMeshes;
  27523. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27524. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27525. len = intersections.length;
  27526. subMeshes = intersections.data;
  27527. }
  27528. else {
  27529. subMeshes = mesh.subMeshes;
  27530. len = subMeshes.length;
  27531. }
  27532. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27533. subMesh = subMeshes[subIndex];
  27534. this._evaluateSubMesh(subMesh, mesh);
  27535. }
  27536. }
  27537. };
  27538. /**
  27539. * Update the transform matrix to update from the current active camera
  27540. * @param force defines a boolean used to force the update even if cache is up to date
  27541. */
  27542. Scene.prototype.updateTransformMatrix = function (force) {
  27543. if (!this.activeCamera) {
  27544. return;
  27545. }
  27546. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27547. };
  27548. /**
  27549. * 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)
  27550. * @param alternateCamera defines the camera to use
  27551. */
  27552. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27553. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27554. };
  27555. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27556. if (camera && camera._skipRendering) {
  27557. return;
  27558. }
  27559. var engine = this._engine;
  27560. this.activeCamera = camera;
  27561. if (!this.activeCamera)
  27562. throw new Error("Active camera not set");
  27563. // Viewport
  27564. engine.setViewport(this.activeCamera.viewport);
  27565. // Camera
  27566. this.resetCachedMaterial();
  27567. this._renderId++;
  27568. this.updateTransformMatrix();
  27569. if (camera._alternateCamera) {
  27570. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27571. this._alternateRendering = true;
  27572. }
  27573. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27574. // Meshes
  27575. this._evaluateActiveMeshes();
  27576. // Software skinning
  27577. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27578. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27579. mesh.applySkeleton(mesh.skeleton);
  27580. }
  27581. // Render targets
  27582. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27583. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27584. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27585. }
  27586. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27587. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27588. }
  27589. if (this.renderTargetsEnabled) {
  27590. this._intermediateRendering = true;
  27591. if (this._renderTargets.length > 0) {
  27592. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27593. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27594. var renderTarget = this._renderTargets.data[renderIndex];
  27595. if (renderTarget._shouldRender()) {
  27596. this._renderId++;
  27597. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27598. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27599. }
  27600. }
  27601. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27602. this._renderId++;
  27603. }
  27604. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27605. var step = _a[_i];
  27606. step.action(this.activeCamera);
  27607. }
  27608. this._intermediateRendering = false;
  27609. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27610. }
  27611. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27612. // Prepare Frame
  27613. if (this.postProcessManager) {
  27614. this.postProcessManager._prepareFrame();
  27615. }
  27616. // Before Camera Draw
  27617. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27618. var step = _c[_b];
  27619. step.action(this.activeCamera);
  27620. }
  27621. // Render
  27622. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27623. this._renderingManager.render(null, null, true, true);
  27624. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27625. // After Camera Draw
  27626. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27627. var step = _e[_d];
  27628. step.action(this.activeCamera);
  27629. }
  27630. // Finalize frame
  27631. if (this.postProcessManager) {
  27632. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27633. }
  27634. // Reset some special arrays
  27635. this._renderTargets.reset();
  27636. this._alternateRendering = false;
  27637. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27638. };
  27639. Scene.prototype._processSubCameras = function (camera) {
  27640. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27641. this._renderForCamera(camera);
  27642. return;
  27643. }
  27644. // rig cameras
  27645. for (var index = 0; index < camera._rigCameras.length; index++) {
  27646. this._renderForCamera(camera._rigCameras[index], camera);
  27647. }
  27648. this.activeCamera = camera;
  27649. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27650. };
  27651. Scene.prototype._checkIntersections = function () {
  27652. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27653. var sourceMesh = this._meshesForIntersections.data[index];
  27654. if (!sourceMesh.actionManager) {
  27655. continue;
  27656. }
  27657. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27658. var action = sourceMesh.actionManager.actions[actionIndex];
  27659. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27660. var parameters = action.getTriggerParameter();
  27661. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27662. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27663. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27664. if (areIntersecting && currentIntersectionInProgress === -1) {
  27665. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27666. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27667. sourceMesh._intersectionsInProgress.push(otherMesh);
  27668. }
  27669. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27670. sourceMesh._intersectionsInProgress.push(otherMesh);
  27671. }
  27672. }
  27673. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27674. //They intersected, and now they don't.
  27675. //is this trigger an exit trigger? execute an event.
  27676. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27677. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27678. }
  27679. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27680. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27681. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27682. return otherMesh === parameterMesh;
  27683. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27684. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27685. }
  27686. }
  27687. }
  27688. }
  27689. }
  27690. };
  27691. /**
  27692. * Render the scene
  27693. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27694. */
  27695. Scene.prototype.render = function (updateCameras) {
  27696. if (updateCameras === void 0) { updateCameras = true; }
  27697. if (this.isDisposed) {
  27698. return;
  27699. }
  27700. // Register components that have been associated lately to the scene.
  27701. this._registerTransientComponents();
  27702. this._activeParticles.fetchNewFrame();
  27703. this._totalVertices.fetchNewFrame();
  27704. this._activeIndices.fetchNewFrame();
  27705. this._activeBones.fetchNewFrame();
  27706. this._meshesForIntersections.reset();
  27707. this.resetCachedMaterial();
  27708. this.onBeforeAnimationsObservable.notifyObservers(this);
  27709. // Actions
  27710. if (this.actionManager) {
  27711. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27712. }
  27713. if (this._engine.isDeterministicLockStep()) {
  27714. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27715. var defaultFPS = (60.0 / 1000.0);
  27716. var defaultFrameTime = 1000 / 60; // frame time in MS
  27717. if (this._physicsEngine) {
  27718. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27719. }
  27720. var stepsTaken = 0;
  27721. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27722. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27723. internalSteps = Math.min(internalSteps, maxSubSteps);
  27724. do {
  27725. this.onBeforeStepObservable.notifyObservers(this);
  27726. // Animations
  27727. this._animationRatio = defaultFrameTime * defaultFPS;
  27728. this._animate();
  27729. this.onAfterAnimationsObservable.notifyObservers(this);
  27730. // Physics
  27731. if (this._physicsEngine) {
  27732. this.onBeforePhysicsObservable.notifyObservers(this);
  27733. this._physicsEngine._step(defaultFrameTime / 1000);
  27734. this.onAfterPhysicsObservable.notifyObservers(this);
  27735. }
  27736. this.onAfterStepObservable.notifyObservers(this);
  27737. this._currentStepId++;
  27738. stepsTaken++;
  27739. deltaTime -= defaultFrameTime;
  27740. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27741. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27742. }
  27743. else {
  27744. // Animations
  27745. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27746. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27747. this._animate();
  27748. this.onAfterAnimationsObservable.notifyObservers(this);
  27749. // Physics
  27750. if (this._physicsEngine) {
  27751. this.onBeforePhysicsObservable.notifyObservers(this);
  27752. this._physicsEngine._step(deltaTime / 1000.0);
  27753. this.onAfterPhysicsObservable.notifyObservers(this);
  27754. }
  27755. }
  27756. // Before camera update steps
  27757. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27758. var step = _a[_i];
  27759. step.action();
  27760. }
  27761. // Update Cameras
  27762. if (updateCameras) {
  27763. if (this.activeCameras.length > 0) {
  27764. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27765. var camera = this.activeCameras[cameraIndex];
  27766. camera.update();
  27767. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27768. // rig cameras
  27769. for (var index = 0; index < camera._rigCameras.length; index++) {
  27770. camera._rigCameras[index].update();
  27771. }
  27772. }
  27773. }
  27774. }
  27775. else if (this.activeCamera) {
  27776. this.activeCamera.update();
  27777. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27778. // rig cameras
  27779. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27780. this.activeCamera._rigCameras[index].update();
  27781. }
  27782. }
  27783. }
  27784. }
  27785. // Before render
  27786. this.onBeforeRenderObservable.notifyObservers(this);
  27787. // Customs render targets
  27788. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27789. var engine = this.getEngine();
  27790. var currentActiveCamera = this.activeCamera;
  27791. if (this.renderTargetsEnabled) {
  27792. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27793. this._intermediateRendering = true;
  27794. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27795. var renderTarget = this.customRenderTargets[customIndex];
  27796. if (renderTarget._shouldRender()) {
  27797. this._renderId++;
  27798. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27799. if (!this.activeCamera)
  27800. throw new Error("Active camera not set");
  27801. // Viewport
  27802. engine.setViewport(this.activeCamera.viewport);
  27803. // Camera
  27804. this.updateTransformMatrix();
  27805. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27806. }
  27807. }
  27808. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27809. this._intermediateRendering = false;
  27810. this._renderId++;
  27811. }
  27812. // Restore back buffer
  27813. if (this.customRenderTargets.length > 0) {
  27814. engine.restoreDefaultFramebuffer();
  27815. }
  27816. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27817. this.activeCamera = currentActiveCamera;
  27818. // Procedural textures
  27819. if (this.proceduralTexturesEnabled) {
  27820. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27821. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27822. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27823. if (proceduralTexture._shouldRender()) {
  27824. proceduralTexture.render();
  27825. }
  27826. }
  27827. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27828. }
  27829. // Clear
  27830. if (this.autoClearDepthAndStencil || this.autoClear) {
  27831. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27832. }
  27833. // Shadows
  27834. if (this.shadowsEnabled) {
  27835. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27836. var light = this.lights[lightIndex];
  27837. var shadowGenerator = light.getShadowGenerator();
  27838. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27839. var shadowMap = (shadowGenerator.getShadowMap());
  27840. if (this.textures.indexOf(shadowMap) !== -1) {
  27841. this._renderTargets.push(shadowMap);
  27842. }
  27843. }
  27844. }
  27845. }
  27846. // Collects render targets from external components.
  27847. for (var _b = 0, _c = this._gatherRenderTargetsStage; _b < _c.length; _b++) {
  27848. var step = _c[_b];
  27849. step.action(this._renderTargets);
  27850. }
  27851. // Multi-cameras?
  27852. if (this.activeCameras.length > 0) {
  27853. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27854. if (cameraIndex > 0) {
  27855. this._engine.clear(null, false, true, true);
  27856. }
  27857. this._processSubCameras(this.activeCameras[cameraIndex]);
  27858. }
  27859. }
  27860. else {
  27861. if (!this.activeCamera) {
  27862. throw new Error("No camera defined");
  27863. }
  27864. this._processSubCameras(this.activeCamera);
  27865. }
  27866. // Intersection checks
  27867. this._checkIntersections();
  27868. // Update the audio listener attached to the camera
  27869. if (BABYLON.AudioEngine) {
  27870. this._updateAudioParameters();
  27871. }
  27872. // After render
  27873. if (this.afterRender) {
  27874. this.afterRender();
  27875. }
  27876. this.onAfterRenderObservable.notifyObservers(this);
  27877. // Cleaning
  27878. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27879. var data = this._toBeDisposed.data[index];
  27880. if (data) {
  27881. data.dispose();
  27882. }
  27883. this._toBeDisposed[index] = null;
  27884. }
  27885. this._toBeDisposed.reset();
  27886. if (this.dumpNextRenderTargets) {
  27887. this.dumpNextRenderTargets = false;
  27888. }
  27889. this._activeBones.addCount(0, true);
  27890. this._activeIndices.addCount(0, true);
  27891. this._activeParticles.addCount(0, true);
  27892. };
  27893. Scene.prototype._updateAudioParameters = function () {
  27894. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27895. return;
  27896. }
  27897. var listeningCamera;
  27898. var audioEngine = BABYLON.Engine.audioEngine;
  27899. if (this.activeCameras.length > 0) {
  27900. listeningCamera = this.activeCameras[0];
  27901. }
  27902. else {
  27903. listeningCamera = this.activeCamera;
  27904. }
  27905. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27906. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27907. // for VR cameras
  27908. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27909. listeningCamera = listeningCamera.rigCameras[0];
  27910. }
  27911. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27912. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27913. cameraDirection.normalize();
  27914. // To avoid some errors on GearVR
  27915. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27916. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27917. }
  27918. var i;
  27919. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27920. var sound = this.mainSoundTrack.soundCollection[i];
  27921. if (sound.useCustomAttenuation) {
  27922. sound.updateDistanceFromListener();
  27923. }
  27924. }
  27925. for (i = 0; i < this.soundTracks.length; i++) {
  27926. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27927. sound = this.soundTracks[i].soundCollection[j];
  27928. if (sound.useCustomAttenuation) {
  27929. sound.updateDistanceFromListener();
  27930. }
  27931. }
  27932. }
  27933. }
  27934. };
  27935. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27936. // Audio
  27937. /**
  27938. * Gets or sets if audio support is enabled
  27939. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27940. */
  27941. get: function () {
  27942. return this._audioEnabled;
  27943. },
  27944. set: function (value) {
  27945. this._audioEnabled = value;
  27946. if (BABYLON.AudioEngine) {
  27947. if (this._audioEnabled) {
  27948. this._enableAudio();
  27949. }
  27950. else {
  27951. this._disableAudio();
  27952. }
  27953. }
  27954. },
  27955. enumerable: true,
  27956. configurable: true
  27957. });
  27958. Scene.prototype._disableAudio = function () {
  27959. var i;
  27960. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27961. this.mainSoundTrack.soundCollection[i].pause();
  27962. }
  27963. for (i = 0; i < this.soundTracks.length; i++) {
  27964. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27965. this.soundTracks[i].soundCollection[j].pause();
  27966. }
  27967. }
  27968. };
  27969. Scene.prototype._enableAudio = function () {
  27970. var i;
  27971. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27972. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27973. this.mainSoundTrack.soundCollection[i].play();
  27974. }
  27975. }
  27976. for (i = 0; i < this.soundTracks.length; i++) {
  27977. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27978. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27979. this.soundTracks[i].soundCollection[j].play();
  27980. }
  27981. }
  27982. }
  27983. };
  27984. Object.defineProperty(Scene.prototype, "headphone", {
  27985. /**
  27986. * Gets or sets if audio will be output to headphones
  27987. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27988. */
  27989. get: function () {
  27990. return this._headphone;
  27991. },
  27992. set: function (value) {
  27993. this._headphone = value;
  27994. if (BABYLON.AudioEngine) {
  27995. if (this._headphone) {
  27996. this._switchAudioModeForHeadphones();
  27997. }
  27998. else {
  27999. this._switchAudioModeForNormalSpeakers();
  28000. }
  28001. }
  28002. },
  28003. enumerable: true,
  28004. configurable: true
  28005. });
  28006. Scene.prototype._switchAudioModeForHeadphones = function () {
  28007. this.mainSoundTrack.switchPanningModelToHRTF();
  28008. for (var i = 0; i < this.soundTracks.length; i++) {
  28009. this.soundTracks[i].switchPanningModelToHRTF();
  28010. }
  28011. };
  28012. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28013. this.mainSoundTrack.switchPanningModelToEqualPower();
  28014. for (var i = 0; i < this.soundTracks.length; i++) {
  28015. this.soundTracks[i].switchPanningModelToEqualPower();
  28016. }
  28017. };
  28018. /**
  28019. * Freeze all materials
  28020. * A frozen material will not be updatable but should be faster to render
  28021. */
  28022. Scene.prototype.freezeMaterials = function () {
  28023. for (var i = 0; i < this.materials.length; i++) {
  28024. this.materials[i].freeze();
  28025. }
  28026. };
  28027. /**
  28028. * Unfreeze all materials
  28029. * A frozen material will not be updatable but should be faster to render
  28030. */
  28031. Scene.prototype.unfreezeMaterials = function () {
  28032. for (var i = 0; i < this.materials.length; i++) {
  28033. this.materials[i].unfreeze();
  28034. }
  28035. };
  28036. /**
  28037. * Releases all held ressources
  28038. */
  28039. Scene.prototype.dispose = function () {
  28040. this.beforeRender = null;
  28041. this.afterRender = null;
  28042. this.skeletons = [];
  28043. this.morphTargetManagers = [];
  28044. this._transientComponents = [];
  28045. this._isReadyForMeshStage.clear();
  28046. this._beforeEvaluateActiveMeshStage.clear();
  28047. this._evaluateSubMeshStage.clear();
  28048. this._activeMeshStage.clear();
  28049. this._cameraDrawRenderTargetStage.clear();
  28050. this._beforeCameraDrawStage.clear();
  28051. this._beforeRenderingGroupDrawStage.clear();
  28052. this._afterRenderingGroupDrawStage.clear();
  28053. this._afterCameraDrawStage.clear();
  28054. this._beforeCameraUpdateStage.clear();
  28055. this._gatherRenderTargetsStage.clear();
  28056. this._rebuildGeometryStage.clear();
  28057. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28058. var component = _a[_i];
  28059. component.dispose();
  28060. }
  28061. this.importedMeshesFiles = new Array();
  28062. this.stopAllAnimations();
  28063. this.resetCachedMaterial();
  28064. // Smart arrays
  28065. if (this.activeCamera) {
  28066. this.activeCamera._activeMeshes.dispose();
  28067. this.activeCamera = null;
  28068. }
  28069. this._activeMeshes.dispose();
  28070. this._renderingManager.dispose();
  28071. this._processedMaterials.dispose();
  28072. this._activeParticleSystems.dispose();
  28073. this._activeSkeletons.dispose();
  28074. this._softwareSkinnedMeshes.dispose();
  28075. this._renderTargets.dispose();
  28076. this._registeredForLateAnimationBindings.dispose();
  28077. this._meshesForIntersections.dispose();
  28078. this._toBeDisposed.dispose();
  28079. // Abort active requests
  28080. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28081. var request = _c[_b];
  28082. request.abort();
  28083. }
  28084. // Debug layer
  28085. if (this._debugLayer) {
  28086. this._debugLayer.hide();
  28087. }
  28088. // Events
  28089. this.onDisposeObservable.notifyObservers(this);
  28090. this.onDisposeObservable.clear();
  28091. this.onBeforeRenderObservable.clear();
  28092. this.onAfterRenderObservable.clear();
  28093. this.onBeforeRenderTargetsRenderObservable.clear();
  28094. this.onAfterRenderTargetsRenderObservable.clear();
  28095. this.onAfterStepObservable.clear();
  28096. this.onBeforeStepObservable.clear();
  28097. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28098. this.onAfterActiveMeshesEvaluationObservable.clear();
  28099. this.onBeforeParticlesRenderingObservable.clear();
  28100. this.onAfterParticlesRenderingObservable.clear();
  28101. this.onBeforeSpritesRenderingObservable.clear();
  28102. this.onAfterSpritesRenderingObservable.clear();
  28103. this.onBeforeDrawPhaseObservable.clear();
  28104. this.onAfterDrawPhaseObservable.clear();
  28105. this.onBeforePhysicsObservable.clear();
  28106. this.onAfterPhysicsObservable.clear();
  28107. this.onBeforeAnimationsObservable.clear();
  28108. this.onAfterAnimationsObservable.clear();
  28109. this.onDataLoadedObservable.clear();
  28110. this.onBeforeRenderingGroupObservable.clear();
  28111. this.onAfterRenderingGroupObservable.clear();
  28112. this.detachControl();
  28113. // Release sounds & sounds tracks
  28114. if (BABYLON.AudioEngine) {
  28115. this.disposeSounds();
  28116. }
  28117. // VR Helper
  28118. if (this.VRHelper) {
  28119. this.VRHelper.dispose();
  28120. }
  28121. // Detach cameras
  28122. var canvas = this._engine.getRenderingCanvas();
  28123. if (canvas) {
  28124. var index;
  28125. for (index = 0; index < this.cameras.length; index++) {
  28126. this.cameras[index].detachControl(canvas);
  28127. }
  28128. }
  28129. // Release animation groups
  28130. while (this.animationGroups.length) {
  28131. this.animationGroups[0].dispose();
  28132. }
  28133. // Release lights
  28134. while (this.lights.length) {
  28135. this.lights[0].dispose();
  28136. }
  28137. // Release meshes
  28138. while (this.meshes.length) {
  28139. this.meshes[0].dispose(true);
  28140. }
  28141. while (this.transformNodes.length) {
  28142. this.removeTransformNode(this.transformNodes[0]);
  28143. }
  28144. // Release cameras
  28145. while (this.cameras.length) {
  28146. this.cameras[0].dispose();
  28147. }
  28148. // Release materials
  28149. if (this.defaultMaterial) {
  28150. this.defaultMaterial.dispose();
  28151. }
  28152. while (this.multiMaterials.length) {
  28153. this.multiMaterials[0].dispose();
  28154. }
  28155. while (this.materials.length) {
  28156. this.materials[0].dispose();
  28157. }
  28158. // Release particles
  28159. while (this.particleSystems.length) {
  28160. this.particleSystems[0].dispose();
  28161. }
  28162. // Release sprites
  28163. while (this.spriteManagers.length) {
  28164. this.spriteManagers[0].dispose();
  28165. }
  28166. // Release postProcesses
  28167. while (this.postProcesses.length) {
  28168. this.postProcesses[0].dispose();
  28169. }
  28170. // Release textures
  28171. while (this.textures.length) {
  28172. this.textures[0].dispose();
  28173. }
  28174. // Release UBO
  28175. this._sceneUbo.dispose();
  28176. if (this._alternateSceneUbo) {
  28177. this._alternateSceneUbo.dispose();
  28178. }
  28179. // Post-processes
  28180. this.postProcessManager.dispose();
  28181. // Physics
  28182. if (this._physicsEngine) {
  28183. this.disablePhysicsEngine();
  28184. }
  28185. // Remove from engine
  28186. index = this._engine.scenes.indexOf(this);
  28187. if (index > -1) {
  28188. this._engine.scenes.splice(index, 1);
  28189. }
  28190. this._engine.wipeCaches(true);
  28191. this._isDisposed = true;
  28192. };
  28193. Object.defineProperty(Scene.prototype, "isDisposed", {
  28194. /**
  28195. * Gets if the scene is already disposed
  28196. */
  28197. get: function () {
  28198. return this._isDisposed;
  28199. },
  28200. enumerable: true,
  28201. configurable: true
  28202. });
  28203. /**
  28204. * Releases sounds & soundtracks
  28205. */
  28206. Scene.prototype.disposeSounds = function () {
  28207. if (!this._mainSoundTrack) {
  28208. return;
  28209. }
  28210. this.mainSoundTrack.dispose();
  28211. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28212. this.soundTracks[scIndex].dispose();
  28213. }
  28214. };
  28215. /**
  28216. * Call this function to reduce memory footprint of the scene.
  28217. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28218. */
  28219. Scene.prototype.clearCachedVertexData = function () {
  28220. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28221. var mesh = this.meshes[meshIndex];
  28222. var geometry = mesh.geometry;
  28223. if (geometry) {
  28224. geometry._indices = [];
  28225. for (var vbName in geometry._vertexBuffers) {
  28226. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28227. continue;
  28228. }
  28229. geometry._vertexBuffers[vbName]._buffer._data = null;
  28230. }
  28231. }
  28232. }
  28233. };
  28234. /**
  28235. * This function will remove the local cached buffer data from texture.
  28236. * It will save memory but will prevent the texture from being rebuilt
  28237. */
  28238. Scene.prototype.cleanCachedTextureBuffer = function () {
  28239. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28240. var baseTexture = _a[_i];
  28241. var buffer = baseTexture._buffer;
  28242. if (buffer) {
  28243. baseTexture._buffer = null;
  28244. }
  28245. }
  28246. };
  28247. // Octrees
  28248. /**
  28249. * Get the world extend vectors with an optional filter
  28250. *
  28251. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28252. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28253. */
  28254. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28255. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28256. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28257. filterPredicate = filterPredicate || (function () { return true; });
  28258. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28259. mesh.computeWorldMatrix(true);
  28260. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28261. return;
  28262. }
  28263. var boundingInfo = mesh.getBoundingInfo();
  28264. var minBox = boundingInfo.boundingBox.minimumWorld;
  28265. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28266. BABYLON.Tools.CheckExtends(minBox, min, max);
  28267. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28268. });
  28269. return {
  28270. min: min,
  28271. max: max
  28272. };
  28273. };
  28274. /**
  28275. * Creates or updates the octree used to boost selection (picking)
  28276. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28277. * @param maxCapacity defines the maximum capacity per leaf
  28278. * @param maxDepth defines the maximum depth of the octree
  28279. * @returns an octree of AbstractMesh
  28280. */
  28281. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28282. if (maxCapacity === void 0) { maxCapacity = 64; }
  28283. if (maxDepth === void 0) { maxDepth = 2; }
  28284. if (!this._selectionOctree) {
  28285. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28286. }
  28287. var worldExtends = this.getWorldExtends();
  28288. // Update octree
  28289. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28290. return this._selectionOctree;
  28291. };
  28292. // Picking
  28293. /**
  28294. * Creates a ray that can be used to pick in the scene
  28295. * @param x defines the x coordinate of the origin (on-screen)
  28296. * @param y defines the y coordinate of the origin (on-screen)
  28297. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28298. * @param camera defines the camera to use for the picking
  28299. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28300. * @returns a Ray
  28301. */
  28302. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28303. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28304. var result = BABYLON.Ray.Zero();
  28305. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28306. return result;
  28307. };
  28308. /**
  28309. * Creates a ray that can be used to pick in the scene
  28310. * @param x defines the x coordinate of the origin (on-screen)
  28311. * @param y defines the y coordinate of the origin (on-screen)
  28312. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28313. * @param result defines the ray where to store the picking ray
  28314. * @param camera defines the camera to use for the picking
  28315. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28316. * @returns the current scene
  28317. */
  28318. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28319. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28320. var engine = this._engine;
  28321. if (!camera) {
  28322. if (!this.activeCamera)
  28323. throw new Error("Active camera not set");
  28324. camera = this.activeCamera;
  28325. }
  28326. var cameraViewport = camera.viewport;
  28327. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28328. // Moving coordinates to local viewport world
  28329. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28330. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28331. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28332. return this;
  28333. };
  28334. /**
  28335. * Creates a ray that can be used to pick in the scene
  28336. * @param x defines the x coordinate of the origin (on-screen)
  28337. * @param y defines the y coordinate of the origin (on-screen)
  28338. * @param camera defines the camera to use for the picking
  28339. * @returns a Ray
  28340. */
  28341. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28342. var result = BABYLON.Ray.Zero();
  28343. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28344. return result;
  28345. };
  28346. /**
  28347. * Creates a ray that can be used to pick in the scene
  28348. * @param x defines the x coordinate of the origin (on-screen)
  28349. * @param y defines the y coordinate of the origin (on-screen)
  28350. * @param result defines the ray where to store the picking ray
  28351. * @param camera defines the camera to use for the picking
  28352. * @returns the current scene
  28353. */
  28354. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28355. if (!BABYLON.PickingInfo) {
  28356. return this;
  28357. }
  28358. var engine = this._engine;
  28359. if (!camera) {
  28360. if (!this.activeCamera)
  28361. throw new Error("Active camera not set");
  28362. camera = this.activeCamera;
  28363. }
  28364. var cameraViewport = camera.viewport;
  28365. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28366. var identity = BABYLON.Matrix.Identity();
  28367. // Moving coordinates to local viewport world
  28368. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28369. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28370. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28371. return this;
  28372. };
  28373. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28374. if (!BABYLON.PickingInfo) {
  28375. return null;
  28376. }
  28377. var pickingInfo = null;
  28378. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28379. var mesh = this.meshes[meshIndex];
  28380. if (predicate) {
  28381. if (!predicate(mesh)) {
  28382. continue;
  28383. }
  28384. }
  28385. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28386. continue;
  28387. }
  28388. var world = mesh.getWorldMatrix();
  28389. var ray = rayFunction(world);
  28390. var result = mesh.intersects(ray, fastCheck);
  28391. if (!result || !result.hit)
  28392. continue;
  28393. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28394. continue;
  28395. pickingInfo = result;
  28396. if (fastCheck) {
  28397. break;
  28398. }
  28399. }
  28400. return pickingInfo || new BABYLON.PickingInfo();
  28401. };
  28402. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28403. if (!BABYLON.PickingInfo) {
  28404. return null;
  28405. }
  28406. var pickingInfos = new Array();
  28407. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28408. var mesh = this.meshes[meshIndex];
  28409. if (predicate) {
  28410. if (!predicate(mesh)) {
  28411. continue;
  28412. }
  28413. }
  28414. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28415. continue;
  28416. }
  28417. var world = mesh.getWorldMatrix();
  28418. var ray = rayFunction(world);
  28419. var result = mesh.intersects(ray, false);
  28420. if (!result || !result.hit)
  28421. continue;
  28422. pickingInfos.push(result);
  28423. }
  28424. return pickingInfos;
  28425. };
  28426. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28427. if (!BABYLON.PickingInfo) {
  28428. return null;
  28429. }
  28430. var pickingInfo = null;
  28431. if (!camera) {
  28432. if (!this.activeCamera) {
  28433. return null;
  28434. }
  28435. camera = this.activeCamera;
  28436. }
  28437. if (this.spriteManagers.length > 0) {
  28438. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28439. var spriteManager = this.spriteManagers[spriteIndex];
  28440. if (!spriteManager.isPickable) {
  28441. continue;
  28442. }
  28443. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28444. if (!result || !result.hit)
  28445. continue;
  28446. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28447. continue;
  28448. pickingInfo = result;
  28449. if (fastCheck) {
  28450. break;
  28451. }
  28452. }
  28453. }
  28454. return pickingInfo || new BABYLON.PickingInfo();
  28455. };
  28456. /** Launch a ray to try to pick a mesh in the scene
  28457. * @param x position on screen
  28458. * @param y position on screen
  28459. * @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
  28460. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28461. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28462. * @returns a PickingInfo
  28463. */
  28464. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28465. var _this = this;
  28466. if (!BABYLON.PickingInfo) {
  28467. return null;
  28468. }
  28469. var result = this._internalPick(function (world) {
  28470. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28471. return _this._tempPickingRay;
  28472. }, predicate, fastCheck);
  28473. if (result) {
  28474. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28475. }
  28476. return result;
  28477. };
  28478. /** Launch a ray to try to pick a sprite in the scene
  28479. * @param x position on screen
  28480. * @param y position on screen
  28481. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28482. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28483. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28484. * @returns a PickingInfo
  28485. */
  28486. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28487. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28488. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28489. };
  28490. /** Use the given ray to pick a mesh in the scene
  28491. * @param ray The ray to use to pick meshes
  28492. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28493. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28494. * @returns a PickingInfo
  28495. */
  28496. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28497. var _this = this;
  28498. var result = this._internalPick(function (world) {
  28499. if (!_this._pickWithRayInverseMatrix) {
  28500. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28501. }
  28502. world.invertToRef(_this._pickWithRayInverseMatrix);
  28503. if (!_this._cachedRayForTransform) {
  28504. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28505. }
  28506. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28507. return _this._cachedRayForTransform;
  28508. }, predicate, fastCheck);
  28509. if (result) {
  28510. result.ray = ray;
  28511. }
  28512. return result;
  28513. };
  28514. /**
  28515. * Launch a ray to try to pick a mesh in the scene
  28516. * @param x X position on screen
  28517. * @param y Y position on screen
  28518. * @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
  28519. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28520. * @returns an array of PickingInfo
  28521. */
  28522. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28523. var _this = this;
  28524. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28525. };
  28526. /**
  28527. * Launch a ray to try to pick a mesh in the scene
  28528. * @param ray Ray to use
  28529. * @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
  28530. * @returns an array of PickingInfo
  28531. */
  28532. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28533. var _this = this;
  28534. return this._internalMultiPick(function (world) {
  28535. if (!_this._pickWithRayInverseMatrix) {
  28536. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28537. }
  28538. world.invertToRef(_this._pickWithRayInverseMatrix);
  28539. if (!_this._cachedRayForTransform) {
  28540. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28541. }
  28542. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28543. return _this._cachedRayForTransform;
  28544. }, predicate);
  28545. };
  28546. /**
  28547. * Force the value of meshUnderPointer
  28548. * @param mesh defines the mesh to use
  28549. */
  28550. Scene.prototype.setPointerOverMesh = function (mesh) {
  28551. if (this._pointerOverMesh === mesh) {
  28552. return;
  28553. }
  28554. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28555. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28556. }
  28557. this._pointerOverMesh = mesh;
  28558. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28559. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28560. }
  28561. };
  28562. /**
  28563. * Gets the mesh under the pointer
  28564. * @returns a Mesh or null if no mesh is under the pointer
  28565. */
  28566. Scene.prototype.getPointerOverMesh = function () {
  28567. return this._pointerOverMesh;
  28568. };
  28569. /**
  28570. * Force the sprite under the pointer
  28571. * @param sprite defines the sprite to use
  28572. */
  28573. Scene.prototype.setPointerOverSprite = function (sprite) {
  28574. if (this._pointerOverSprite === sprite) {
  28575. return;
  28576. }
  28577. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28578. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28579. }
  28580. this._pointerOverSprite = sprite;
  28581. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28582. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28583. }
  28584. };
  28585. /**
  28586. * Gets the sprite under the pointer
  28587. * @returns a Sprite or null if no sprite is under the pointer
  28588. */
  28589. Scene.prototype.getPointerOverSprite = function () {
  28590. return this._pointerOverSprite;
  28591. };
  28592. // Physics
  28593. /**
  28594. * Gets the current physics engine
  28595. * @returns a PhysicsEngine or null if none attached
  28596. */
  28597. Scene.prototype.getPhysicsEngine = function () {
  28598. return this._physicsEngine;
  28599. };
  28600. /**
  28601. * Enables physics to the current scene
  28602. * @param gravity defines the scene's gravity for the physics engine
  28603. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28604. * @return a boolean indicating if the physics engine was initialized
  28605. */
  28606. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28607. if (gravity === void 0) { gravity = null; }
  28608. if (this._physicsEngine) {
  28609. return true;
  28610. }
  28611. try {
  28612. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28613. return true;
  28614. }
  28615. catch (e) {
  28616. BABYLON.Tools.Error(e.message);
  28617. return false;
  28618. }
  28619. };
  28620. /**
  28621. * Disables and disposes the physics engine associated with the scene
  28622. */
  28623. Scene.prototype.disablePhysicsEngine = function () {
  28624. if (!this._physicsEngine) {
  28625. return;
  28626. }
  28627. this._physicsEngine.dispose();
  28628. this._physicsEngine = null;
  28629. };
  28630. /**
  28631. * Gets a boolean indicating if there is an active physics engine
  28632. * @returns a boolean indicating if there is an active physics engine
  28633. */
  28634. Scene.prototype.isPhysicsEnabled = function () {
  28635. return this._physicsEngine !== undefined;
  28636. };
  28637. /**
  28638. * Deletes a physics compound impostor
  28639. * @param compound defines the compound to delete
  28640. */
  28641. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28642. var mesh = compound.parts[0].mesh;
  28643. if (mesh.physicsImpostor) {
  28644. mesh.physicsImpostor.dispose( /*true*/);
  28645. mesh.physicsImpostor = null;
  28646. }
  28647. };
  28648. // Misc.
  28649. /** @hidden */
  28650. Scene.prototype._rebuildGeometries = function () {
  28651. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28652. var geometry = _a[_i];
  28653. geometry._rebuild();
  28654. }
  28655. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28656. var mesh = _c[_b];
  28657. mesh._rebuild();
  28658. }
  28659. if (this.postProcessManager) {
  28660. this.postProcessManager._rebuild();
  28661. }
  28662. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28663. var component = _e[_d];
  28664. component.rebuild();
  28665. }
  28666. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28667. var system = _g[_f];
  28668. system.rebuild();
  28669. }
  28670. for (var _h = 0, _j = this._rebuildGeometryStage; _h < _j.length; _h++) {
  28671. var step = _j[_h];
  28672. step.action();
  28673. }
  28674. };
  28675. /** @hidden */
  28676. Scene.prototype._rebuildTextures = function () {
  28677. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28678. var texture = _a[_i];
  28679. texture._rebuild();
  28680. }
  28681. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28682. };
  28683. /**
  28684. * Creates a default light for the scene.
  28685. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28686. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28687. */
  28688. Scene.prototype.createDefaultLight = function (replace) {
  28689. if (replace === void 0) { replace = false; }
  28690. // Dispose existing light in replace mode.
  28691. if (replace) {
  28692. if (this.lights) {
  28693. for (var i = 0; i < this.lights.length; i++) {
  28694. this.lights[i].dispose();
  28695. }
  28696. }
  28697. }
  28698. // Light
  28699. if (this.lights.length === 0) {
  28700. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28701. }
  28702. };
  28703. /**
  28704. * Creates a default camera for the scene.
  28705. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28706. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28707. * @param replace has default false, when true replaces the active camera in the scene
  28708. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28709. */
  28710. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28711. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28712. if (replace === void 0) { replace = false; }
  28713. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28714. // Dispose existing camera in replace mode.
  28715. if (replace) {
  28716. if (this.activeCamera) {
  28717. this.activeCamera.dispose();
  28718. this.activeCamera = null;
  28719. }
  28720. }
  28721. // Camera
  28722. if (!this.activeCamera) {
  28723. var worldExtends = this.getWorldExtends();
  28724. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28725. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28726. var camera;
  28727. var radius = worldSize.length() * 1.5;
  28728. // empty scene scenario!
  28729. if (!isFinite(radius)) {
  28730. radius = 1;
  28731. worldCenter.copyFromFloats(0, 0, 0);
  28732. }
  28733. if (createArcRotateCamera) {
  28734. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28735. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28736. arcRotateCamera.wheelPrecision = 100 / radius;
  28737. camera = arcRotateCamera;
  28738. }
  28739. else {
  28740. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28741. freeCamera.setTarget(worldCenter);
  28742. camera = freeCamera;
  28743. }
  28744. camera.minZ = radius * 0.01;
  28745. camera.maxZ = radius * 1000;
  28746. camera.speed = radius * 0.2;
  28747. this.activeCamera = camera;
  28748. var canvas = this.getEngine().getRenderingCanvas();
  28749. if (attachCameraControls && canvas) {
  28750. camera.attachControl(canvas);
  28751. }
  28752. }
  28753. };
  28754. /**
  28755. * Creates a default camera and a default light.
  28756. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28757. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28758. * @param replace has the default false, when true replaces the active camera/light in the scene
  28759. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28760. */
  28761. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28762. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28763. if (replace === void 0) { replace = false; }
  28764. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28765. this.createDefaultLight(replace);
  28766. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28767. };
  28768. /**
  28769. * Creates a new sky box
  28770. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28771. * @param environmentTexture defines the texture to use as environment texture
  28772. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28773. * @param scale defines the overall scale of the skybox
  28774. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28775. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28776. * @returns a new mesh holding the sky box
  28777. */
  28778. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28779. if (pbr === void 0) { pbr = false; }
  28780. if (scale === void 0) { scale = 1000; }
  28781. if (blur === void 0) { blur = 0; }
  28782. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28783. if (!environmentTexture) {
  28784. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28785. return null;
  28786. }
  28787. if (setGlobalEnvTexture) {
  28788. if (environmentTexture) {
  28789. this.environmentTexture = environmentTexture;
  28790. }
  28791. }
  28792. // Skybox
  28793. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28794. if (pbr) {
  28795. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28796. hdrSkyboxMaterial.backFaceCulling = false;
  28797. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28798. if (hdrSkyboxMaterial.reflectionTexture) {
  28799. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28800. }
  28801. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28802. hdrSkyboxMaterial.disableLighting = true;
  28803. hdrSkyboxMaterial.twoSidedLighting = true;
  28804. hdrSkybox.infiniteDistance = true;
  28805. hdrSkybox.material = hdrSkyboxMaterial;
  28806. }
  28807. else {
  28808. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28809. skyboxMaterial.backFaceCulling = false;
  28810. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28811. if (skyboxMaterial.reflectionTexture) {
  28812. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28813. }
  28814. skyboxMaterial.disableLighting = true;
  28815. hdrSkybox.infiniteDistance = true;
  28816. hdrSkybox.material = skyboxMaterial;
  28817. }
  28818. return hdrSkybox;
  28819. };
  28820. /**
  28821. * Creates a new environment
  28822. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28823. * @param options defines the options you can use to configure the environment
  28824. * @returns the new EnvironmentHelper
  28825. */
  28826. Scene.prototype.createDefaultEnvironment = function (options) {
  28827. if (BABYLON.EnvironmentHelper) {
  28828. return new BABYLON.EnvironmentHelper(options, this);
  28829. }
  28830. return null;
  28831. };
  28832. /**
  28833. * Creates a new VREXperienceHelper
  28834. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28835. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28836. * @returns a new VREXperienceHelper
  28837. */
  28838. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28839. if (webVROptions === void 0) { webVROptions = {}; }
  28840. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28841. };
  28842. // Tags
  28843. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28844. if (tagsQuery === undefined) {
  28845. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28846. return list;
  28847. }
  28848. var listByTags = [];
  28849. forEach = forEach || (function (item) { return; });
  28850. for (var i in list) {
  28851. var item = list[i];
  28852. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28853. listByTags.push(item);
  28854. forEach(item);
  28855. }
  28856. }
  28857. return listByTags;
  28858. };
  28859. /**
  28860. * Get a list of meshes by tags
  28861. * @param tagsQuery defines the tags query to use
  28862. * @param forEach defines a predicate used to filter results
  28863. * @returns an array of Mesh
  28864. */
  28865. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28866. return this._getByTags(this.meshes, tagsQuery, forEach);
  28867. };
  28868. /**
  28869. * Get a list of cameras by tags
  28870. * @param tagsQuery defines the tags query to use
  28871. * @param forEach defines a predicate used to filter results
  28872. * @returns an array of Camera
  28873. */
  28874. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28875. return this._getByTags(this.cameras, tagsQuery, forEach);
  28876. };
  28877. /**
  28878. * Get a list of lights by tags
  28879. * @param tagsQuery defines the tags query to use
  28880. * @param forEach defines a predicate used to filter results
  28881. * @returns an array of Light
  28882. */
  28883. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28884. return this._getByTags(this.lights, tagsQuery, forEach);
  28885. };
  28886. /**
  28887. * Get a list of materials by tags
  28888. * @param tagsQuery defines the tags query to use
  28889. * @param forEach defines a predicate used to filter results
  28890. * @returns an array of Material
  28891. */
  28892. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28893. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28894. };
  28895. /**
  28896. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28897. * This allowed control for front to back rendering or reversly depending of the special needs.
  28898. *
  28899. * @param renderingGroupId The rendering group id corresponding to its index
  28900. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28901. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28902. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28903. */
  28904. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28905. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28906. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28907. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28908. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28909. };
  28910. /**
  28911. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28912. *
  28913. * @param renderingGroupId The rendering group id corresponding to its index
  28914. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28915. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28916. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28917. */
  28918. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28919. if (depth === void 0) { depth = true; }
  28920. if (stencil === void 0) { stencil = true; }
  28921. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28922. };
  28923. /**
  28924. * Gets the current auto clear configuration for one rendering group of the rendering
  28925. * manager.
  28926. * @param index the rendering group index to get the information for
  28927. * @returns The auto clear setup for the requested rendering group
  28928. */
  28929. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28930. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28931. };
  28932. /**
  28933. * Will flag all materials as dirty to trigger new shader compilation
  28934. * @param flag defines the flag used to specify which material part must be marked as dirty
  28935. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28936. */
  28937. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28938. if (this.blockMaterialDirtyMechanism) {
  28939. return;
  28940. }
  28941. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28942. var material = _a[_i];
  28943. if (predicate && !predicate(material)) {
  28944. continue;
  28945. }
  28946. material.markAsDirty(flag);
  28947. }
  28948. };
  28949. /** @hidden */
  28950. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28951. var _this = this;
  28952. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28953. this._activeRequests.push(request);
  28954. request.onCompleteObservable.add(function (request) {
  28955. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28956. });
  28957. return request;
  28958. };
  28959. /** @hidden */
  28960. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28961. var _this = this;
  28962. return new Promise(function (resolve, reject) {
  28963. _this._loadFile(url, function (data) {
  28964. resolve(data);
  28965. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28966. reject(exception);
  28967. });
  28968. });
  28969. };
  28970. // Statics
  28971. Scene._uniqueIdCounter = 0;
  28972. /** The fog is deactivated */
  28973. Scene.FOGMODE_NONE = 0;
  28974. /** The fog density is following an exponential function */
  28975. Scene.FOGMODE_EXP = 1;
  28976. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28977. Scene.FOGMODE_EXP2 = 2;
  28978. /** The fog density is following a linear function. */
  28979. Scene.FOGMODE_LINEAR = 3;
  28980. /**
  28981. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28982. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28983. */
  28984. Scene.MinDeltaTime = 1.0;
  28985. /**
  28986. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28987. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28988. */
  28989. Scene.MaxDeltaTime = 1000.0;
  28990. /** The distance in pixel that you have to move to prevent some events */
  28991. Scene.DragMovementThreshold = 10; // in pixels
  28992. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28993. Scene.LongPressDelay = 500; // in milliseconds
  28994. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28995. Scene.DoubleClickDelay = 300; // in milliseconds
  28996. /** If you need to check double click without raising a single click at first click, enable this flag */
  28997. Scene.ExclusiveDoubleClickMode = false;
  28998. return Scene;
  28999. }(BABYLON.AbstractScene));
  29000. BABYLON.Scene = Scene;
  29001. })(BABYLON || (BABYLON = {}));
  29002. //# sourceMappingURL=babylon.scene.js.map
  29003. var BABYLON;
  29004. (function (BABYLON) {
  29005. /**
  29006. * Set of assets to keep when moving a scene into an asset container.
  29007. */
  29008. var KeepAssets = /** @class */ (function (_super) {
  29009. __extends(KeepAssets, _super);
  29010. function KeepAssets() {
  29011. return _super !== null && _super.apply(this, arguments) || this;
  29012. }
  29013. return KeepAssets;
  29014. }(BABYLON.AbstractScene));
  29015. BABYLON.KeepAssets = KeepAssets;
  29016. /**
  29017. * Container with a set of assets that can be added or removed from a scene.
  29018. */
  29019. var AssetContainer = /** @class */ (function (_super) {
  29020. __extends(AssetContainer, _super);
  29021. /**
  29022. * Instantiates an AssetContainer.
  29023. * @param scene The scene the AssetContainer belongs to.
  29024. */
  29025. function AssetContainer(scene) {
  29026. var _this = _super.call(this) || this;
  29027. _this.scene = scene;
  29028. return _this;
  29029. }
  29030. /**
  29031. * Adds all the assets from the container to the scene.
  29032. */
  29033. AssetContainer.prototype.addAllToScene = function () {
  29034. var _this = this;
  29035. this.cameras.forEach(function (o) {
  29036. _this.scene.addCamera(o);
  29037. });
  29038. this.lights.forEach(function (o) {
  29039. _this.scene.addLight(o);
  29040. });
  29041. this.meshes.forEach(function (o) {
  29042. _this.scene.addMesh(o);
  29043. });
  29044. this.skeletons.forEach(function (o) {
  29045. _this.scene.addSkeleton(o);
  29046. });
  29047. this.animations.forEach(function (o) {
  29048. _this.scene.addAnimation(o);
  29049. });
  29050. this.animationGroups.forEach(function (o) {
  29051. _this.scene.addAnimationGroup(o);
  29052. });
  29053. this.multiMaterials.forEach(function (o) {
  29054. _this.scene.addMultiMaterial(o);
  29055. });
  29056. this.materials.forEach(function (o) {
  29057. _this.scene.addMaterial(o);
  29058. });
  29059. this.morphTargetManagers.forEach(function (o) {
  29060. _this.scene.addMorphTargetManager(o);
  29061. });
  29062. this.geometries.forEach(function (o) {
  29063. _this.scene.addGeometry(o);
  29064. });
  29065. this.transformNodes.forEach(function (o) {
  29066. _this.scene.addTransformNode(o);
  29067. });
  29068. this.actionManagers.forEach(function (o) {
  29069. _this.scene.addActionManager(o);
  29070. });
  29071. this.sounds.forEach(function (o) {
  29072. o.play();
  29073. o.autoplay = true;
  29074. _this.scene.mainSoundTrack.AddSound(o);
  29075. });
  29076. this.textures.forEach(function (o) {
  29077. _this.scene.addTexture(o);
  29078. });
  29079. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29080. var component = _a[_i];
  29081. component.addFromContainer(this.scene);
  29082. }
  29083. };
  29084. /**
  29085. * Removes all the assets in the container from the scene
  29086. */
  29087. AssetContainer.prototype.removeAllFromScene = function () {
  29088. var _this = this;
  29089. this.cameras.forEach(function (o) {
  29090. _this.scene.removeCamera(o);
  29091. });
  29092. this.lights.forEach(function (o) {
  29093. _this.scene.removeLight(o);
  29094. });
  29095. this.meshes.forEach(function (o) {
  29096. _this.scene.removeMesh(o);
  29097. });
  29098. this.skeletons.forEach(function (o) {
  29099. _this.scene.removeSkeleton(o);
  29100. });
  29101. this.animations.forEach(function (o) {
  29102. _this.scene.removeAnimation(o);
  29103. });
  29104. this.animationGroups.forEach(function (o) {
  29105. _this.scene.removeAnimationGroup(o);
  29106. });
  29107. this.multiMaterials.forEach(function (o) {
  29108. _this.scene.removeMultiMaterial(o);
  29109. });
  29110. this.materials.forEach(function (o) {
  29111. _this.scene.removeMaterial(o);
  29112. });
  29113. this.morphTargetManagers.forEach(function (o) {
  29114. _this.scene.removeMorphTargetManager(o);
  29115. });
  29116. this.geometries.forEach(function (o) {
  29117. _this.scene.removeGeometry(o);
  29118. });
  29119. this.transformNodes.forEach(function (o) {
  29120. _this.scene.removeTransformNode(o);
  29121. });
  29122. this.actionManagers.forEach(function (o) {
  29123. _this.scene.removeActionManager(o);
  29124. });
  29125. this.sounds.forEach(function (o) {
  29126. o.stop();
  29127. o.autoplay = false;
  29128. _this.scene.mainSoundTrack.RemoveSound(o);
  29129. });
  29130. this.textures.forEach(function (o) {
  29131. _this.scene.removeTexture(o);
  29132. });
  29133. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29134. var component = _a[_i];
  29135. component.removeFromContainer(this.scene);
  29136. }
  29137. };
  29138. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29139. if (!sourceAssets) {
  29140. return;
  29141. }
  29142. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29143. var asset = sourceAssets_1[_i];
  29144. var move = true;
  29145. if (keepAssets) {
  29146. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29147. var keepAsset = keepAssets_1[_a];
  29148. if (asset === keepAsset) {
  29149. move = false;
  29150. break;
  29151. }
  29152. }
  29153. }
  29154. if (move) {
  29155. targetAssets.push(asset);
  29156. }
  29157. }
  29158. };
  29159. /**
  29160. * Removes all the assets contained in the scene and adds them to the container.
  29161. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29162. */
  29163. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29164. if (keepAssets === undefined) {
  29165. keepAssets = new KeepAssets();
  29166. }
  29167. for (var key in this) {
  29168. if (this.hasOwnProperty(key)) {
  29169. this[key] = this[key] || [];
  29170. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29171. }
  29172. }
  29173. this.removeAllFromScene();
  29174. };
  29175. /**
  29176. * 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.
  29177. * @returns the root mesh
  29178. */
  29179. AssetContainer.prototype.createRootMesh = function () {
  29180. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29181. this.meshes.forEach(function (m) {
  29182. if (!m.parent) {
  29183. rootMesh.addChild(m);
  29184. }
  29185. });
  29186. this.meshes.unshift(rootMesh);
  29187. return rootMesh;
  29188. };
  29189. return AssetContainer;
  29190. }(BABYLON.AbstractScene));
  29191. BABYLON.AssetContainer = AssetContainer;
  29192. })(BABYLON || (BABYLON = {}));
  29193. //# sourceMappingURL=babylon.assetContainer.js.map
  29194. var BABYLON;
  29195. (function (BABYLON) {
  29196. var Buffer = /** @class */ (function () {
  29197. /**
  29198. * Constructor
  29199. * @param engine the engine
  29200. * @param data the data to use for this buffer
  29201. * @param updatable whether the data is updatable
  29202. * @param stride the stride (optional)
  29203. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29204. * @param instanced whether the buffer is instanced (optional)
  29205. * @param useBytes set to true if the stride in in bytes (optional)
  29206. */
  29207. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29208. if (stride === void 0) { stride = 0; }
  29209. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29210. if (instanced === void 0) { instanced = false; }
  29211. if (useBytes === void 0) { useBytes = false; }
  29212. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29213. this._engine = engine.getScene().getEngine();
  29214. }
  29215. else {
  29216. this._engine = engine;
  29217. }
  29218. this._updatable = updatable;
  29219. this._instanced = instanced;
  29220. this._data = data;
  29221. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29222. if (!postponeInternalCreation) { // by default
  29223. this.create();
  29224. }
  29225. }
  29226. /**
  29227. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29228. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29229. * @param offset defines offset in the buffer (0 by default)
  29230. * @param size defines the size in floats of attributes (position is 3 for instance)
  29231. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29232. * @param instanced defines if the vertex buffer contains indexed data
  29233. * @param useBytes defines if the offset and stride are in bytes
  29234. * @returns the new vertex buffer
  29235. */
  29236. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29237. if (useBytes === void 0) { useBytes = false; }
  29238. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29239. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29240. // a lot of these parameters are ignored as they are overriden by the buffer
  29241. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29242. };
  29243. // Properties
  29244. Buffer.prototype.isUpdatable = function () {
  29245. return this._updatable;
  29246. };
  29247. Buffer.prototype.getData = function () {
  29248. return this._data;
  29249. };
  29250. Buffer.prototype.getBuffer = function () {
  29251. return this._buffer;
  29252. };
  29253. /**
  29254. * Gets the stride in float32 units (i.e. byte stride / 4).
  29255. * May not be an integer if the byte stride is not divisible by 4.
  29256. * DEPRECATED. Use byteStride instead.
  29257. * @returns the stride in float32 units
  29258. */
  29259. Buffer.prototype.getStrideSize = function () {
  29260. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29261. };
  29262. // Methods
  29263. Buffer.prototype.create = function (data) {
  29264. if (data === void 0) { data = null; }
  29265. if (!data && this._buffer) {
  29266. return; // nothing to do
  29267. }
  29268. data = data || this._data;
  29269. if (!data) {
  29270. return;
  29271. }
  29272. if (!this._buffer) { // create buffer
  29273. if (this._updatable) {
  29274. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29275. this._data = data;
  29276. }
  29277. else {
  29278. this._buffer = this._engine.createVertexBuffer(data);
  29279. }
  29280. }
  29281. else if (this._updatable) { // update buffer
  29282. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29283. this._data = data;
  29284. }
  29285. };
  29286. /** @hidden */
  29287. Buffer.prototype._rebuild = function () {
  29288. this._buffer = null;
  29289. this.create(this._data);
  29290. };
  29291. Buffer.prototype.update = function (data) {
  29292. this.create(data);
  29293. };
  29294. /**
  29295. * Updates the data directly.
  29296. * @param data the new data
  29297. * @param offset the new offset
  29298. * @param vertexCount the vertex count (optional)
  29299. * @param useBytes set to true if the offset is in bytes
  29300. */
  29301. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29302. if (useBytes === void 0) { useBytes = false; }
  29303. if (!this._buffer) {
  29304. return;
  29305. }
  29306. if (this._updatable) { // update buffer
  29307. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29308. this._data = null;
  29309. }
  29310. };
  29311. Buffer.prototype.dispose = function () {
  29312. if (!this._buffer) {
  29313. return;
  29314. }
  29315. if (this._engine._releaseBuffer(this._buffer)) {
  29316. this._buffer = null;
  29317. }
  29318. };
  29319. return Buffer;
  29320. }());
  29321. BABYLON.Buffer = Buffer;
  29322. })(BABYLON || (BABYLON = {}));
  29323. //# sourceMappingURL=babylon.buffer.js.map
  29324. var BABYLON;
  29325. (function (BABYLON) {
  29326. var VertexBuffer = /** @class */ (function () {
  29327. /**
  29328. * Constructor
  29329. * @param engine the engine
  29330. * @param data the data to use for this vertex buffer
  29331. * @param kind the vertex buffer kind
  29332. * @param updatable whether the data is updatable
  29333. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29334. * @param stride the stride (optional)
  29335. * @param instanced whether the buffer is instanced (optional)
  29336. * @param offset the offset of the data (optional)
  29337. * @param size the number of components (optional)
  29338. * @param type the type of the component (optional)
  29339. * @param normalized whether the data contains normalized data (optional)
  29340. * @param useBytes set to true if stride and offset are in bytes (optional)
  29341. */
  29342. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29343. if (normalized === void 0) { normalized = false; }
  29344. if (useBytes === void 0) { useBytes = false; }
  29345. if (data instanceof BABYLON.Buffer) {
  29346. this._buffer = data;
  29347. this._ownsBuffer = false;
  29348. }
  29349. else {
  29350. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29351. this._ownsBuffer = true;
  29352. }
  29353. this._kind = kind;
  29354. if (type == undefined) {
  29355. var data_1 = this.getData();
  29356. this.type = VertexBuffer.FLOAT;
  29357. if (data_1 instanceof Int8Array)
  29358. this.type = VertexBuffer.BYTE;
  29359. else if (data_1 instanceof Uint8Array)
  29360. this.type = VertexBuffer.UNSIGNED_BYTE;
  29361. else if (data_1 instanceof Int16Array)
  29362. this.type = VertexBuffer.SHORT;
  29363. else if (data_1 instanceof Uint16Array)
  29364. this.type = VertexBuffer.UNSIGNED_SHORT;
  29365. else if (data_1 instanceof Int32Array)
  29366. this.type = VertexBuffer.INT;
  29367. else if (data_1 instanceof Uint32Array)
  29368. this.type = VertexBuffer.UNSIGNED_INT;
  29369. }
  29370. else {
  29371. this.type = type;
  29372. }
  29373. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29374. if (useBytes) {
  29375. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29376. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29377. this.byteOffset = offset || 0;
  29378. }
  29379. else {
  29380. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29381. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29382. this.byteOffset = (offset || 0) * typeByteLength;
  29383. }
  29384. this.normalized = normalized;
  29385. this._instanced = instanced !== undefined ? instanced : false;
  29386. this._instanceDivisor = instanced ? 1 : 0;
  29387. }
  29388. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29389. /**
  29390. * Gets or sets the instance divisor when in instanced mode
  29391. */
  29392. get: function () {
  29393. return this._instanceDivisor;
  29394. },
  29395. set: function (value) {
  29396. this._instanceDivisor = value;
  29397. if (value == 0) {
  29398. this._instanced = false;
  29399. }
  29400. else {
  29401. this._instanced = true;
  29402. }
  29403. },
  29404. enumerable: true,
  29405. configurable: true
  29406. });
  29407. /** @hidden */
  29408. VertexBuffer.prototype._rebuild = function () {
  29409. if (!this._buffer) {
  29410. return;
  29411. }
  29412. this._buffer._rebuild();
  29413. };
  29414. /**
  29415. * Returns the kind of the VertexBuffer (string).
  29416. */
  29417. VertexBuffer.prototype.getKind = function () {
  29418. return this._kind;
  29419. };
  29420. // Properties
  29421. /**
  29422. * Boolean : is the VertexBuffer updatable ?
  29423. */
  29424. VertexBuffer.prototype.isUpdatable = function () {
  29425. return this._buffer.isUpdatable();
  29426. };
  29427. /**
  29428. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29429. */
  29430. VertexBuffer.prototype.getData = function () {
  29431. return this._buffer.getData();
  29432. };
  29433. /**
  29434. * Returns the WebGLBuffer associated to the VertexBuffer.
  29435. */
  29436. VertexBuffer.prototype.getBuffer = function () {
  29437. return this._buffer.getBuffer();
  29438. };
  29439. /**
  29440. * Returns the stride as a multiple of the type byte length.
  29441. * DEPRECATED. Use byteStride instead.
  29442. */
  29443. VertexBuffer.prototype.getStrideSize = function () {
  29444. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29445. };
  29446. /**
  29447. * Returns the offset as a multiple of the type byte length.
  29448. * DEPRECATED. Use byteOffset instead.
  29449. */
  29450. VertexBuffer.prototype.getOffset = function () {
  29451. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29452. };
  29453. /**
  29454. * Returns the number of components per vertex attribute (integer).
  29455. */
  29456. VertexBuffer.prototype.getSize = function () {
  29457. return this._size;
  29458. };
  29459. /**
  29460. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29461. */
  29462. VertexBuffer.prototype.getIsInstanced = function () {
  29463. return this._instanced;
  29464. };
  29465. /**
  29466. * Returns the instancing divisor, zero for non-instanced (integer).
  29467. */
  29468. VertexBuffer.prototype.getInstanceDivisor = function () {
  29469. return this._instanceDivisor;
  29470. };
  29471. // Methods
  29472. /**
  29473. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29474. * Returns the created WebGLBuffer.
  29475. */
  29476. VertexBuffer.prototype.create = function (data) {
  29477. return this._buffer.create(data);
  29478. };
  29479. /**
  29480. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29481. * This function will create a new buffer if the current one is not updatable
  29482. * Returns the updated WebGLBuffer.
  29483. */
  29484. VertexBuffer.prototype.update = function (data) {
  29485. return this._buffer.update(data);
  29486. };
  29487. /**
  29488. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29489. * Returns the directly updated WebGLBuffer.
  29490. * @param data the new data
  29491. * @param offset the new offset
  29492. * @param useBytes set to true if the offset is in bytes
  29493. */
  29494. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29495. if (useBytes === void 0) { useBytes = false; }
  29496. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29497. };
  29498. /**
  29499. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29500. */
  29501. VertexBuffer.prototype.dispose = function () {
  29502. if (this._ownsBuffer) {
  29503. this._buffer.dispose();
  29504. }
  29505. };
  29506. /**
  29507. * Enumerates each value of this vertex buffer as numbers.
  29508. * @param count the number of values to enumerate
  29509. * @param callback the callback function called for each value
  29510. */
  29511. VertexBuffer.prototype.forEach = function (count, callback) {
  29512. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29513. };
  29514. Object.defineProperty(VertexBuffer, "PositionKind", {
  29515. get: function () {
  29516. return VertexBuffer._PositionKind;
  29517. },
  29518. enumerable: true,
  29519. configurable: true
  29520. });
  29521. Object.defineProperty(VertexBuffer, "NormalKind", {
  29522. get: function () {
  29523. return VertexBuffer._NormalKind;
  29524. },
  29525. enumerable: true,
  29526. configurable: true
  29527. });
  29528. Object.defineProperty(VertexBuffer, "TangentKind", {
  29529. get: function () {
  29530. return VertexBuffer._TangentKind;
  29531. },
  29532. enumerable: true,
  29533. configurable: true
  29534. });
  29535. Object.defineProperty(VertexBuffer, "UVKind", {
  29536. get: function () {
  29537. return VertexBuffer._UVKind;
  29538. },
  29539. enumerable: true,
  29540. configurable: true
  29541. });
  29542. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29543. get: function () {
  29544. return VertexBuffer._UV2Kind;
  29545. },
  29546. enumerable: true,
  29547. configurable: true
  29548. });
  29549. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29550. get: function () {
  29551. return VertexBuffer._UV3Kind;
  29552. },
  29553. enumerable: true,
  29554. configurable: true
  29555. });
  29556. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29557. get: function () {
  29558. return VertexBuffer._UV4Kind;
  29559. },
  29560. enumerable: true,
  29561. configurable: true
  29562. });
  29563. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29564. get: function () {
  29565. return VertexBuffer._UV5Kind;
  29566. },
  29567. enumerable: true,
  29568. configurable: true
  29569. });
  29570. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29571. get: function () {
  29572. return VertexBuffer._UV6Kind;
  29573. },
  29574. enumerable: true,
  29575. configurable: true
  29576. });
  29577. Object.defineProperty(VertexBuffer, "ColorKind", {
  29578. get: function () {
  29579. return VertexBuffer._ColorKind;
  29580. },
  29581. enumerable: true,
  29582. configurable: true
  29583. });
  29584. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29585. get: function () {
  29586. return VertexBuffer._MatricesIndicesKind;
  29587. },
  29588. enumerable: true,
  29589. configurable: true
  29590. });
  29591. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29592. get: function () {
  29593. return VertexBuffer._MatricesWeightsKind;
  29594. },
  29595. enumerable: true,
  29596. configurable: true
  29597. });
  29598. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29599. get: function () {
  29600. return VertexBuffer._MatricesIndicesExtraKind;
  29601. },
  29602. enumerable: true,
  29603. configurable: true
  29604. });
  29605. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29606. get: function () {
  29607. return VertexBuffer._MatricesWeightsExtraKind;
  29608. },
  29609. enumerable: true,
  29610. configurable: true
  29611. });
  29612. /**
  29613. * Deduces the stride given a kind.
  29614. * @param kind The kind string to deduce
  29615. * @returns The deduced stride
  29616. */
  29617. VertexBuffer.DeduceStride = function (kind) {
  29618. switch (kind) {
  29619. case VertexBuffer.UVKind:
  29620. case VertexBuffer.UV2Kind:
  29621. case VertexBuffer.UV3Kind:
  29622. case VertexBuffer.UV4Kind:
  29623. case VertexBuffer.UV5Kind:
  29624. case VertexBuffer.UV6Kind:
  29625. return 2;
  29626. case VertexBuffer.NormalKind:
  29627. case VertexBuffer.PositionKind:
  29628. return 3;
  29629. case VertexBuffer.ColorKind:
  29630. case VertexBuffer.MatricesIndicesKind:
  29631. case VertexBuffer.MatricesIndicesExtraKind:
  29632. case VertexBuffer.MatricesWeightsKind:
  29633. case VertexBuffer.MatricesWeightsExtraKind:
  29634. case VertexBuffer.TangentKind:
  29635. return 4;
  29636. default:
  29637. throw new Error("Invalid kind '" + kind + "'");
  29638. }
  29639. };
  29640. /**
  29641. * Gets the byte length of the given type.
  29642. * @param type the type
  29643. * @returns the number of bytes
  29644. */
  29645. VertexBuffer.GetTypeByteLength = function (type) {
  29646. switch (type) {
  29647. case VertexBuffer.BYTE:
  29648. case VertexBuffer.UNSIGNED_BYTE:
  29649. return 1;
  29650. case VertexBuffer.SHORT:
  29651. case VertexBuffer.UNSIGNED_SHORT:
  29652. return 2;
  29653. case VertexBuffer.INT:
  29654. case VertexBuffer.FLOAT:
  29655. return 4;
  29656. default:
  29657. throw new Error("Invalid type '" + type + "'");
  29658. }
  29659. };
  29660. /**
  29661. * Enumerates each value of the given parameters as numbers.
  29662. * @param data the data to enumerate
  29663. * @param byteOffset the byte offset of the data
  29664. * @param byteStride the byte stride of the data
  29665. * @param componentCount the number of components per element
  29666. * @param componentType the type of the component
  29667. * @param count the total number of components
  29668. * @param normalized whether the data is normalized
  29669. * @param callback the callback function called for each value
  29670. */
  29671. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29672. if (data instanceof Array) {
  29673. var offset = byteOffset / 4;
  29674. var stride = byteStride / 4;
  29675. for (var index = 0; index < count; index += componentCount) {
  29676. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29677. callback(data[offset + componentIndex], index + componentIndex);
  29678. }
  29679. offset += stride;
  29680. }
  29681. }
  29682. else {
  29683. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29684. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29685. for (var index = 0; index < count; index += componentCount) {
  29686. var componentByteOffset = byteOffset;
  29687. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29688. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29689. callback(value, index + componentIndex);
  29690. componentByteOffset += componentByteLength;
  29691. }
  29692. byteOffset += byteStride;
  29693. }
  29694. }
  29695. };
  29696. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29697. switch (type) {
  29698. case VertexBuffer.BYTE: {
  29699. var value = dataView.getInt8(byteOffset);
  29700. if (normalized) {
  29701. value = Math.max(value / 127, -1);
  29702. }
  29703. return value;
  29704. }
  29705. case VertexBuffer.UNSIGNED_BYTE: {
  29706. var value = dataView.getUint8(byteOffset);
  29707. if (normalized) {
  29708. value = value / 255;
  29709. }
  29710. return value;
  29711. }
  29712. case VertexBuffer.SHORT: {
  29713. var value = dataView.getInt16(byteOffset, true);
  29714. if (normalized) {
  29715. value = Math.max(value / 16383, -1);
  29716. }
  29717. return value;
  29718. }
  29719. case VertexBuffer.UNSIGNED_SHORT: {
  29720. var value = dataView.getUint16(byteOffset, true);
  29721. if (normalized) {
  29722. value = value / 65535;
  29723. }
  29724. return value;
  29725. }
  29726. case VertexBuffer.FLOAT: {
  29727. return dataView.getFloat32(byteOffset, true);
  29728. }
  29729. default: {
  29730. throw new Error("Invalid component type " + type);
  29731. }
  29732. }
  29733. };
  29734. /**
  29735. * The byte type.
  29736. */
  29737. VertexBuffer.BYTE = 5120;
  29738. /**
  29739. * The unsigned byte type.
  29740. */
  29741. VertexBuffer.UNSIGNED_BYTE = 5121;
  29742. /**
  29743. * The short type.
  29744. */
  29745. VertexBuffer.SHORT = 5122;
  29746. /**
  29747. * The unsigned short type.
  29748. */
  29749. VertexBuffer.UNSIGNED_SHORT = 5123;
  29750. /**
  29751. * The integer type.
  29752. */
  29753. VertexBuffer.INT = 5124;
  29754. /**
  29755. * The unsigned integer type.
  29756. */
  29757. VertexBuffer.UNSIGNED_INT = 5125;
  29758. /**
  29759. * The float type.
  29760. */
  29761. VertexBuffer.FLOAT = 5126;
  29762. // Enums
  29763. VertexBuffer._PositionKind = "position";
  29764. VertexBuffer._NormalKind = "normal";
  29765. VertexBuffer._TangentKind = "tangent";
  29766. VertexBuffer._UVKind = "uv";
  29767. VertexBuffer._UV2Kind = "uv2";
  29768. VertexBuffer._UV3Kind = "uv3";
  29769. VertexBuffer._UV4Kind = "uv4";
  29770. VertexBuffer._UV5Kind = "uv5";
  29771. VertexBuffer._UV6Kind = "uv6";
  29772. VertexBuffer._ColorKind = "color";
  29773. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29774. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29775. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29776. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29777. return VertexBuffer;
  29778. }());
  29779. BABYLON.VertexBuffer = VertexBuffer;
  29780. })(BABYLON || (BABYLON = {}));
  29781. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29782. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29783. var BABYLON;
  29784. (function (BABYLON) {
  29785. /**
  29786. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29787. */
  29788. var DummyInternalTextureTracker = /** @class */ (function () {
  29789. function DummyInternalTextureTracker() {
  29790. /**
  29791. * Gets or set the previous tracker in the list
  29792. */
  29793. this.previous = null;
  29794. /**
  29795. * Gets or set the next tracker in the list
  29796. */
  29797. this.next = null;
  29798. }
  29799. return DummyInternalTextureTracker;
  29800. }());
  29801. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29802. })(BABYLON || (BABYLON = {}));
  29803. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29804. var BABYLON;
  29805. (function (BABYLON) {
  29806. /**
  29807. * Class used to store data associated with WebGL texture data for the engine
  29808. * This class should not be used directly
  29809. */
  29810. var InternalTexture = /** @class */ (function () {
  29811. /**
  29812. * Creates a new InternalTexture
  29813. * @param engine defines the engine to use
  29814. * @param dataSource defines the type of data that will be used
  29815. */
  29816. function InternalTexture(engine, dataSource) {
  29817. /**
  29818. * Observable called when the texture is loaded
  29819. */
  29820. this.onLoadedObservable = new BABYLON.Observable();
  29821. /**
  29822. * Gets or set the previous tracker in the list
  29823. */
  29824. this.previous = null;
  29825. /**
  29826. * Gets or set the next tracker in the list
  29827. */
  29828. this.next = null;
  29829. // Private
  29830. /** @hidden */
  29831. this._initialSlot = -1;
  29832. /** @hidden */
  29833. this._designatedSlot = -1;
  29834. /** @hidden */
  29835. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29836. /** @hidden */
  29837. this._comparisonFunction = 0;
  29838. /** @hidden */
  29839. this._sphericalPolynomial = null;
  29840. /** @hidden */
  29841. this._lodGenerationScale = 0;
  29842. /** @hidden */
  29843. this._lodGenerationOffset = 0;
  29844. /** @hidden */
  29845. this._isRGBD = false;
  29846. /** @hidden */
  29847. this._references = 1;
  29848. this._engine = engine;
  29849. this._dataSource = dataSource;
  29850. this._webGLTexture = engine._createTexture();
  29851. }
  29852. /**
  29853. * Gets the Engine the texture belongs to.
  29854. * @returns The babylon engine
  29855. */
  29856. InternalTexture.prototype.getEngine = function () {
  29857. return this._engine;
  29858. };
  29859. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29860. /**
  29861. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29862. */
  29863. get: function () {
  29864. return this._dataSource;
  29865. },
  29866. enumerable: true,
  29867. configurable: true
  29868. });
  29869. /**
  29870. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29871. */
  29872. InternalTexture.prototype.incrementReferences = function () {
  29873. this._references++;
  29874. };
  29875. /**
  29876. * Change the size of the texture (not the size of the content)
  29877. * @param width defines the new width
  29878. * @param height defines the new height
  29879. * @param depth defines the new depth (1 by default)
  29880. */
  29881. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29882. if (depth === void 0) { depth = 1; }
  29883. this.width = width;
  29884. this.height = height;
  29885. this.depth = depth;
  29886. this.baseWidth = width;
  29887. this.baseHeight = height;
  29888. this.baseDepth = depth;
  29889. this._size = width * height * depth;
  29890. };
  29891. /** @hidden */
  29892. InternalTexture.prototype._rebuild = function () {
  29893. var _this = this;
  29894. var proxy;
  29895. this.isReady = false;
  29896. this._cachedCoordinatesMode = null;
  29897. this._cachedWrapU = null;
  29898. this._cachedWrapV = null;
  29899. this._cachedAnisotropicFilteringLevel = null;
  29900. switch (this._dataSource) {
  29901. case InternalTexture.DATASOURCE_TEMP:
  29902. return;
  29903. case InternalTexture.DATASOURCE_URL:
  29904. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29905. _this.isReady = true;
  29906. }, null, this._buffer, undefined, this.format);
  29907. proxy._swapAndDie(this);
  29908. return;
  29909. case InternalTexture.DATASOURCE_RAW:
  29910. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29911. proxy._swapAndDie(this);
  29912. this.isReady = true;
  29913. return;
  29914. case InternalTexture.DATASOURCE_RAW3D:
  29915. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29916. proxy._swapAndDie(this);
  29917. this.isReady = true;
  29918. return;
  29919. case InternalTexture.DATASOURCE_DYNAMIC:
  29920. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29921. proxy._swapAndDie(this);
  29922. // The engine will make sure to update content so no need to flag it as isReady = true
  29923. return;
  29924. case InternalTexture.DATASOURCE_RENDERTARGET:
  29925. var options = new BABYLON.RenderTargetCreationOptions();
  29926. options.generateDepthBuffer = this._generateDepthBuffer;
  29927. options.generateMipMaps = this.generateMipMaps;
  29928. options.generateStencilBuffer = this._generateStencilBuffer;
  29929. options.samplingMode = this.samplingMode;
  29930. options.type = this.type;
  29931. if (this.isCube) {
  29932. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29933. }
  29934. else {
  29935. var size = {
  29936. width: this.width,
  29937. height: this.height
  29938. };
  29939. proxy = this._engine.createRenderTargetTexture(size, options);
  29940. }
  29941. proxy._swapAndDie(this);
  29942. this.isReady = true;
  29943. return;
  29944. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29945. var depthTextureOptions = {
  29946. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29947. comparisonFunction: this._comparisonFunction,
  29948. generateStencil: this._generateStencilBuffer,
  29949. isCube: this.isCube
  29950. };
  29951. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29952. proxy._swapAndDie(this);
  29953. this.isReady = true;
  29954. return;
  29955. case InternalTexture.DATASOURCE_CUBE:
  29956. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29957. _this.isReady = true;
  29958. }, null, this.format, this._extension);
  29959. proxy._swapAndDie(this);
  29960. return;
  29961. case InternalTexture.DATASOURCE_CUBERAW:
  29962. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29963. proxy._swapAndDie(this);
  29964. this.isReady = true;
  29965. return;
  29966. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29967. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29968. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29969. _this.isReady = true;
  29970. });
  29971. proxy._swapAndDie(this);
  29972. return;
  29973. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29974. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29975. if (proxy) {
  29976. proxy._swapAndDie(_this);
  29977. }
  29978. _this.isReady = true;
  29979. }, null, this.format, this._extension);
  29980. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29981. return;
  29982. }
  29983. };
  29984. /** @hidden */
  29985. InternalTexture.prototype._swapAndDie = function (target) {
  29986. target._webGLTexture = this._webGLTexture;
  29987. if (this._framebuffer) {
  29988. target._framebuffer = this._framebuffer;
  29989. }
  29990. if (this._depthStencilBuffer) {
  29991. target._depthStencilBuffer = this._depthStencilBuffer;
  29992. }
  29993. if (this._lodTextureHigh) {
  29994. if (target._lodTextureHigh) {
  29995. target._lodTextureHigh.dispose();
  29996. }
  29997. target._lodTextureHigh = this._lodTextureHigh;
  29998. }
  29999. if (this._lodTextureMid) {
  30000. if (target._lodTextureMid) {
  30001. target._lodTextureMid.dispose();
  30002. }
  30003. target._lodTextureMid = this._lodTextureMid;
  30004. }
  30005. if (this._lodTextureLow) {
  30006. if (target._lodTextureLow) {
  30007. target._lodTextureLow.dispose();
  30008. }
  30009. target._lodTextureLow = this._lodTextureLow;
  30010. }
  30011. var cache = this._engine.getLoadedTexturesCache();
  30012. var index = cache.indexOf(this);
  30013. if (index !== -1) {
  30014. cache.splice(index, 1);
  30015. }
  30016. };
  30017. /**
  30018. * Dispose the current allocated resources
  30019. */
  30020. InternalTexture.prototype.dispose = function () {
  30021. if (!this._webGLTexture) {
  30022. return;
  30023. }
  30024. this._references--;
  30025. if (this._references === 0) {
  30026. this._engine._releaseTexture(this);
  30027. this._webGLTexture = null;
  30028. this.previous = null;
  30029. this.next = null;
  30030. }
  30031. };
  30032. /**
  30033. * The source of the texture data is unknown
  30034. */
  30035. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30036. /**
  30037. * Texture data comes from an URL
  30038. */
  30039. InternalTexture.DATASOURCE_URL = 1;
  30040. /**
  30041. * Texture data is only used for temporary storage
  30042. */
  30043. InternalTexture.DATASOURCE_TEMP = 2;
  30044. /**
  30045. * Texture data comes from raw data (ArrayBuffer)
  30046. */
  30047. InternalTexture.DATASOURCE_RAW = 3;
  30048. /**
  30049. * Texture content is dynamic (video or dynamic texture)
  30050. */
  30051. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30052. /**
  30053. * Texture content is generated by rendering to it
  30054. */
  30055. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30056. /**
  30057. * Texture content is part of a multi render target process
  30058. */
  30059. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30060. /**
  30061. * Texture data comes from a cube data file
  30062. */
  30063. InternalTexture.DATASOURCE_CUBE = 7;
  30064. /**
  30065. * Texture data comes from a raw cube data
  30066. */
  30067. InternalTexture.DATASOURCE_CUBERAW = 8;
  30068. /**
  30069. * Texture data come from a prefiltered cube data file
  30070. */
  30071. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30072. /**
  30073. * Texture content is raw 3D data
  30074. */
  30075. InternalTexture.DATASOURCE_RAW3D = 10;
  30076. /**
  30077. * Texture content is a depth texture
  30078. */
  30079. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30080. /**
  30081. * Texture data comes from a raw cube data encoded with RGBD
  30082. */
  30083. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30084. return InternalTexture;
  30085. }());
  30086. BABYLON.InternalTexture = InternalTexture;
  30087. })(BABYLON || (BABYLON = {}));
  30088. //# sourceMappingURL=babylon.internalTexture.js.map
  30089. var BABYLON;
  30090. (function (BABYLON) {
  30091. var BaseTexture = /** @class */ (function () {
  30092. function BaseTexture(scene) {
  30093. this._hasAlpha = false;
  30094. this.getAlphaFromRGB = false;
  30095. this.level = 1;
  30096. this.coordinatesIndex = 0;
  30097. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30098. /**
  30099. * | Value | Type | Description |
  30100. * | ----- | ------------------ | ----------- |
  30101. * | 0 | CLAMP_ADDRESSMODE | |
  30102. * | 1 | WRAP_ADDRESSMODE | |
  30103. * | 2 | MIRROR_ADDRESSMODE | |
  30104. */
  30105. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30106. /**
  30107. * | Value | Type | Description |
  30108. * | ----- | ------------------ | ----------- |
  30109. * | 0 | CLAMP_ADDRESSMODE | |
  30110. * | 1 | WRAP_ADDRESSMODE | |
  30111. * | 2 | MIRROR_ADDRESSMODE | |
  30112. */
  30113. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30114. /**
  30115. * | Value | Type | Description |
  30116. * | ----- | ------------------ | ----------- |
  30117. * | 0 | CLAMP_ADDRESSMODE | |
  30118. * | 1 | WRAP_ADDRESSMODE | |
  30119. * | 2 | MIRROR_ADDRESSMODE | |
  30120. */
  30121. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30122. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30123. this.isCube = false;
  30124. this.is3D = false;
  30125. this.gammaSpace = true;
  30126. this.invertZ = false;
  30127. this.lodLevelInAlpha = false;
  30128. this.isRenderTarget = false;
  30129. this.animations = new Array();
  30130. /**
  30131. * An event triggered when the texture is disposed.
  30132. */
  30133. this.onDisposeObservable = new BABYLON.Observable();
  30134. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30135. this._cachedSize = BABYLON.Size.Zero();
  30136. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30137. if (this._scene) {
  30138. this._scene.textures.push(this);
  30139. }
  30140. this._uid = null;
  30141. }
  30142. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30143. get: function () {
  30144. return this._hasAlpha;
  30145. },
  30146. set: function (value) {
  30147. if (this._hasAlpha === value) {
  30148. return;
  30149. }
  30150. this._hasAlpha = value;
  30151. if (this._scene) {
  30152. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30153. }
  30154. },
  30155. enumerable: true,
  30156. configurable: true
  30157. });
  30158. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30159. get: function () {
  30160. return this._coordinatesMode;
  30161. },
  30162. /**
  30163. * How a texture is mapped.
  30164. *
  30165. * | Value | Type | Description |
  30166. * | ----- | ----------------------------------- | ----------- |
  30167. * | 0 | EXPLICIT_MODE | |
  30168. * | 1 | SPHERICAL_MODE | |
  30169. * | 2 | PLANAR_MODE | |
  30170. * | 3 | CUBIC_MODE | |
  30171. * | 4 | PROJECTION_MODE | |
  30172. * | 5 | SKYBOX_MODE | |
  30173. * | 6 | INVCUBIC_MODE | |
  30174. * | 7 | EQUIRECTANGULAR_MODE | |
  30175. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30176. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30177. */
  30178. set: function (value) {
  30179. if (this._coordinatesMode === value) {
  30180. return;
  30181. }
  30182. this._coordinatesMode = value;
  30183. if (this._scene) {
  30184. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30185. }
  30186. },
  30187. enumerable: true,
  30188. configurable: true
  30189. });
  30190. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30191. /**
  30192. * Gets whether or not the texture contains RGBD data.
  30193. */
  30194. get: function () {
  30195. return this._texture != null && this._texture._isRGBD;
  30196. },
  30197. enumerable: true,
  30198. configurable: true
  30199. });
  30200. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30201. get: function () {
  30202. if (this._texture)
  30203. return this._texture._lodGenerationOffset;
  30204. return 0.0;
  30205. },
  30206. set: function (value) {
  30207. if (this._texture)
  30208. this._texture._lodGenerationOffset = value;
  30209. },
  30210. enumerable: true,
  30211. configurable: true
  30212. });
  30213. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30214. get: function () {
  30215. if (this._texture)
  30216. return this._texture._lodGenerationScale;
  30217. return 0.0;
  30218. },
  30219. set: function (value) {
  30220. if (this._texture)
  30221. this._texture._lodGenerationScale = value;
  30222. },
  30223. enumerable: true,
  30224. configurable: true
  30225. });
  30226. Object.defineProperty(BaseTexture.prototype, "uid", {
  30227. get: function () {
  30228. if (!this._uid) {
  30229. this._uid = BABYLON.Tools.RandomId();
  30230. }
  30231. return this._uid;
  30232. },
  30233. enumerable: true,
  30234. configurable: true
  30235. });
  30236. BaseTexture.prototype.toString = function () {
  30237. return this.name;
  30238. };
  30239. BaseTexture.prototype.getClassName = function () {
  30240. return "BaseTexture";
  30241. };
  30242. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30243. set: function (callback) {
  30244. if (this._onDisposeObserver) {
  30245. this.onDisposeObservable.remove(this._onDisposeObserver);
  30246. }
  30247. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30248. },
  30249. enumerable: true,
  30250. configurable: true
  30251. });
  30252. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30253. get: function () {
  30254. return true;
  30255. },
  30256. enumerable: true,
  30257. configurable: true
  30258. });
  30259. BaseTexture.prototype.getScene = function () {
  30260. return this._scene;
  30261. };
  30262. BaseTexture.prototype.getTextureMatrix = function () {
  30263. return BABYLON.Matrix.IdentityReadOnly;
  30264. };
  30265. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30266. return BABYLON.Matrix.IdentityReadOnly;
  30267. };
  30268. BaseTexture.prototype.getInternalTexture = function () {
  30269. return this._texture;
  30270. };
  30271. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30272. return !this.isBlocking || this.isReady();
  30273. };
  30274. BaseTexture.prototype.isReady = function () {
  30275. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30276. this.delayLoad();
  30277. return false;
  30278. }
  30279. if (this._texture) {
  30280. return this._texture.isReady;
  30281. }
  30282. return false;
  30283. };
  30284. BaseTexture.prototype.getSize = function () {
  30285. if (this._texture) {
  30286. if (this._texture.width) {
  30287. this._cachedSize.width = this._texture.width;
  30288. this._cachedSize.height = this._texture.height;
  30289. return this._cachedSize;
  30290. }
  30291. if (this._texture._size) {
  30292. this._cachedSize.width = this._texture._size;
  30293. this._cachedSize.height = this._texture._size;
  30294. return this._cachedSize;
  30295. }
  30296. }
  30297. return this._cachedSize;
  30298. };
  30299. BaseTexture.prototype.getBaseSize = function () {
  30300. if (!this.isReady() || !this._texture)
  30301. return BABYLON.Size.Zero();
  30302. if (this._texture._size) {
  30303. return new BABYLON.Size(this._texture._size, this._texture._size);
  30304. }
  30305. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30306. };
  30307. BaseTexture.prototype.scale = function (ratio) {
  30308. };
  30309. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30310. get: function () {
  30311. return false;
  30312. },
  30313. enumerable: true,
  30314. configurable: true
  30315. });
  30316. /** @hidden */
  30317. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30318. if (!this._scene) {
  30319. return null;
  30320. }
  30321. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30322. for (var index = 0; index < texturesCache.length; index++) {
  30323. var texturesCacheEntry = texturesCache[index];
  30324. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30325. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30326. texturesCacheEntry.incrementReferences();
  30327. return texturesCacheEntry;
  30328. }
  30329. }
  30330. }
  30331. return null;
  30332. };
  30333. /** @hidden */
  30334. BaseTexture.prototype._rebuild = function () {
  30335. };
  30336. BaseTexture.prototype.delayLoad = function () {
  30337. };
  30338. BaseTexture.prototype.clone = function () {
  30339. return null;
  30340. };
  30341. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30342. get: function () {
  30343. if (!this._texture) {
  30344. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30345. }
  30346. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30347. },
  30348. enumerable: true,
  30349. configurable: true
  30350. });
  30351. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30352. get: function () {
  30353. if (!this._texture) {
  30354. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30355. }
  30356. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30357. },
  30358. enumerable: true,
  30359. configurable: true
  30360. });
  30361. /**
  30362. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30363. * This will returns an RGBA array buffer containing either in values (0-255) or
  30364. * float values (0-1) depending of the underlying buffer type.
  30365. * @param faceIndex The face of the texture to read (in case of cube texture)
  30366. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30367. * @returns The Array buffer containing the pixels data.
  30368. */
  30369. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30370. if (faceIndex === void 0) { faceIndex = 0; }
  30371. if (level === void 0) { level = 0; }
  30372. if (!this._texture) {
  30373. return null;
  30374. }
  30375. var size = this.getSize();
  30376. var width = size.width;
  30377. var height = size.height;
  30378. var scene = this.getScene();
  30379. if (!scene) {
  30380. return null;
  30381. }
  30382. var engine = scene.getEngine();
  30383. if (level != 0) {
  30384. width = width / Math.pow(2, level);
  30385. height = height / Math.pow(2, level);
  30386. width = Math.round(width);
  30387. height = Math.round(height);
  30388. }
  30389. if (this._texture.isCube) {
  30390. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30391. }
  30392. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30393. };
  30394. BaseTexture.prototype.releaseInternalTexture = function () {
  30395. if (this._texture) {
  30396. this._texture.dispose();
  30397. this._texture = null;
  30398. }
  30399. };
  30400. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30401. get: function () {
  30402. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30403. return null;
  30404. }
  30405. if (!this._texture._sphericalPolynomial) {
  30406. this._texture._sphericalPolynomial =
  30407. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30408. }
  30409. return this._texture._sphericalPolynomial;
  30410. },
  30411. set: function (value) {
  30412. if (this._texture) {
  30413. this._texture._sphericalPolynomial = value;
  30414. }
  30415. },
  30416. enumerable: true,
  30417. configurable: true
  30418. });
  30419. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30420. get: function () {
  30421. if (this._texture) {
  30422. return this._texture._lodTextureHigh;
  30423. }
  30424. return null;
  30425. },
  30426. enumerable: true,
  30427. configurable: true
  30428. });
  30429. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30430. get: function () {
  30431. if (this._texture) {
  30432. return this._texture._lodTextureMid;
  30433. }
  30434. return null;
  30435. },
  30436. enumerable: true,
  30437. configurable: true
  30438. });
  30439. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30440. get: function () {
  30441. if (this._texture) {
  30442. return this._texture._lodTextureLow;
  30443. }
  30444. return null;
  30445. },
  30446. enumerable: true,
  30447. configurable: true
  30448. });
  30449. BaseTexture.prototype.dispose = function () {
  30450. if (!this._scene) {
  30451. return;
  30452. }
  30453. // Animations
  30454. this._scene.stopAnimation(this);
  30455. // Remove from scene
  30456. this._scene._removePendingData(this);
  30457. var index = this._scene.textures.indexOf(this);
  30458. if (index >= 0) {
  30459. this._scene.textures.splice(index, 1);
  30460. }
  30461. if (this._texture === undefined) {
  30462. return;
  30463. }
  30464. // Release
  30465. this.releaseInternalTexture();
  30466. // Callback
  30467. this.onDisposeObservable.notifyObservers(this);
  30468. this.onDisposeObservable.clear();
  30469. };
  30470. BaseTexture.prototype.serialize = function () {
  30471. if (!this.name) {
  30472. return null;
  30473. }
  30474. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30475. // Animations
  30476. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30477. return serializationObject;
  30478. };
  30479. BaseTexture.WhenAllReady = function (textures, callback) {
  30480. var numRemaining = textures.length;
  30481. if (numRemaining === 0) {
  30482. callback();
  30483. return;
  30484. }
  30485. var _loop_1 = function () {
  30486. texture = textures[i];
  30487. if (texture.isReady()) {
  30488. if (--numRemaining === 0) {
  30489. callback();
  30490. }
  30491. }
  30492. else {
  30493. onLoadObservable = texture.onLoadObservable;
  30494. var onLoadCallback_1 = function () {
  30495. onLoadObservable.removeCallback(onLoadCallback_1);
  30496. if (--numRemaining === 0) {
  30497. callback();
  30498. }
  30499. };
  30500. onLoadObservable.add(onLoadCallback_1);
  30501. }
  30502. };
  30503. var texture, onLoadObservable;
  30504. for (var i = 0; i < textures.length; i++) {
  30505. _loop_1();
  30506. }
  30507. };
  30508. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30509. __decorate([
  30510. BABYLON.serialize()
  30511. ], BaseTexture.prototype, "name", void 0);
  30512. __decorate([
  30513. BABYLON.serialize("hasAlpha")
  30514. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30515. __decorate([
  30516. BABYLON.serialize()
  30517. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30518. __decorate([
  30519. BABYLON.serialize()
  30520. ], BaseTexture.prototype, "level", void 0);
  30521. __decorate([
  30522. BABYLON.serialize()
  30523. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30524. __decorate([
  30525. BABYLON.serialize("coordinatesMode")
  30526. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30527. __decorate([
  30528. BABYLON.serialize()
  30529. ], BaseTexture.prototype, "wrapU", void 0);
  30530. __decorate([
  30531. BABYLON.serialize()
  30532. ], BaseTexture.prototype, "wrapV", void 0);
  30533. __decorate([
  30534. BABYLON.serialize()
  30535. ], BaseTexture.prototype, "wrapR", void 0);
  30536. __decorate([
  30537. BABYLON.serialize()
  30538. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30539. __decorate([
  30540. BABYLON.serialize()
  30541. ], BaseTexture.prototype, "isCube", void 0);
  30542. __decorate([
  30543. BABYLON.serialize()
  30544. ], BaseTexture.prototype, "is3D", void 0);
  30545. __decorate([
  30546. BABYLON.serialize()
  30547. ], BaseTexture.prototype, "gammaSpace", void 0);
  30548. __decorate([
  30549. BABYLON.serialize()
  30550. ], BaseTexture.prototype, "invertZ", void 0);
  30551. __decorate([
  30552. BABYLON.serialize()
  30553. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30554. __decorate([
  30555. BABYLON.serialize()
  30556. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30557. __decorate([
  30558. BABYLON.serialize()
  30559. ], BaseTexture.prototype, "lodGenerationScale", null);
  30560. __decorate([
  30561. BABYLON.serialize()
  30562. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30563. return BaseTexture;
  30564. }());
  30565. BABYLON.BaseTexture = BaseTexture;
  30566. })(BABYLON || (BABYLON = {}));
  30567. //# sourceMappingURL=babylon.baseTexture.js.map
  30568. var BABYLON;
  30569. (function (BABYLON) {
  30570. var Texture = /** @class */ (function (_super) {
  30571. __extends(Texture, _super);
  30572. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30573. if (noMipmap === void 0) { noMipmap = false; }
  30574. if (invertY === void 0) { invertY = true; }
  30575. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30576. if (onLoad === void 0) { onLoad = null; }
  30577. if (onError === void 0) { onError = null; }
  30578. if (buffer === void 0) { buffer = null; }
  30579. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30580. var _this = _super.call(this, scene) || this;
  30581. _this.uOffset = 0;
  30582. _this.vOffset = 0;
  30583. _this.uScale = 1.0;
  30584. _this.vScale = 1.0;
  30585. _this.uAng = 0;
  30586. _this.vAng = 0;
  30587. _this.wAng = 0;
  30588. /**
  30589. * Defines the center of rotation (U)
  30590. */
  30591. _this.uRotationCenter = 0.5;
  30592. /**
  30593. * Defines the center of rotation (V)
  30594. */
  30595. _this.vRotationCenter = 0.5;
  30596. /**
  30597. * Defines the center of rotation (W)
  30598. */
  30599. _this.wRotationCenter = 0.5;
  30600. _this._isBlocking = true;
  30601. _this.name = url || "";
  30602. _this.url = url;
  30603. _this._noMipmap = noMipmap;
  30604. _this._invertY = invertY;
  30605. _this._samplingMode = samplingMode;
  30606. _this._buffer = buffer;
  30607. _this._deleteBuffer = deleteBuffer;
  30608. if (format) {
  30609. _this._format = format;
  30610. }
  30611. scene = _this.getScene();
  30612. if (!scene) {
  30613. return _this;
  30614. }
  30615. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30616. var load = function () {
  30617. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30618. _this.onLoadObservable.notifyObservers(_this);
  30619. }
  30620. if (onLoad) {
  30621. onLoad();
  30622. }
  30623. if (!_this.isBlocking && scene) {
  30624. scene.resetCachedMaterial();
  30625. }
  30626. };
  30627. if (!_this.url) {
  30628. _this._delayedOnLoad = load;
  30629. _this._delayedOnError = onError;
  30630. return _this;
  30631. }
  30632. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30633. if (!_this._texture) {
  30634. if (!scene.useDelayedTextureLoading) {
  30635. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30636. if (deleteBuffer) {
  30637. delete _this._buffer;
  30638. }
  30639. }
  30640. else {
  30641. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30642. _this._delayedOnLoad = load;
  30643. _this._delayedOnError = onError;
  30644. }
  30645. }
  30646. else {
  30647. if (_this._texture.isReady) {
  30648. BABYLON.Tools.SetImmediate(function () { return load(); });
  30649. }
  30650. else {
  30651. _this._texture.onLoadedObservable.add(load);
  30652. }
  30653. }
  30654. return _this;
  30655. }
  30656. Object.defineProperty(Texture.prototype, "noMipmap", {
  30657. get: function () {
  30658. return this._noMipmap;
  30659. },
  30660. enumerable: true,
  30661. configurable: true
  30662. });
  30663. Object.defineProperty(Texture.prototype, "isBlocking", {
  30664. get: function () {
  30665. return this._isBlocking;
  30666. },
  30667. set: function (value) {
  30668. this._isBlocking = value;
  30669. },
  30670. enumerable: true,
  30671. configurable: true
  30672. });
  30673. Object.defineProperty(Texture.prototype, "samplingMode", {
  30674. get: function () {
  30675. return this._samplingMode;
  30676. },
  30677. enumerable: true,
  30678. configurable: true
  30679. });
  30680. /**
  30681. * Update the url (and optional buffer) of this texture if url was null during construction.
  30682. * @param url the url of the texture
  30683. * @param buffer the buffer of the texture (defaults to null)
  30684. */
  30685. Texture.prototype.updateURL = function (url, buffer) {
  30686. if (buffer === void 0) { buffer = null; }
  30687. if (this.url) {
  30688. throw new Error("URL is already set");
  30689. }
  30690. this.url = url;
  30691. this._buffer = buffer;
  30692. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30693. this.delayLoad();
  30694. };
  30695. Texture.prototype.delayLoad = function () {
  30696. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30697. return;
  30698. }
  30699. var scene = this.getScene();
  30700. if (!scene) {
  30701. return;
  30702. }
  30703. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30704. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30705. if (!this._texture) {
  30706. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30707. if (this._deleteBuffer) {
  30708. delete this._buffer;
  30709. }
  30710. }
  30711. else {
  30712. if (this._delayedOnLoad) {
  30713. if (this._texture.isReady) {
  30714. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30715. }
  30716. else {
  30717. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30718. }
  30719. }
  30720. }
  30721. this._delayedOnLoad = null;
  30722. this._delayedOnError = null;
  30723. };
  30724. /**
  30725. * Default is Trilinear mode.
  30726. *
  30727. * | Value | Type | Description |
  30728. * | ----- | ------------------ | ----------- |
  30729. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30730. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30731. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30732. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30733. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30734. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30735. * | 7 | NEAREST_LINEAR | |
  30736. * | 8 | NEAREST_NEAREST | |
  30737. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30738. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30739. * | 11 | LINEAR_LINEAR | |
  30740. * | 12 | LINEAR_NEAREST | |
  30741. *
  30742. * > _mag_: magnification filter (close to the viewer)
  30743. * > _min_: minification filter (far from the viewer)
  30744. * > _mip_: filter used between mip map levels
  30745. *
  30746. */
  30747. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30748. if (!this._texture) {
  30749. return;
  30750. }
  30751. var scene = this.getScene();
  30752. if (!scene) {
  30753. return;
  30754. }
  30755. this._samplingMode = samplingMode;
  30756. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30757. };
  30758. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30759. x *= this.uScale;
  30760. y *= this.vScale;
  30761. x -= this.uRotationCenter * this.uScale;
  30762. y -= this.vRotationCenter * this.vScale;
  30763. z -= this.wRotationCenter;
  30764. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30765. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30766. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30767. t.z += this.wRotationCenter;
  30768. };
  30769. Texture.prototype.getTextureMatrix = function () {
  30770. var _this = this;
  30771. if (this.uOffset === this._cachedUOffset &&
  30772. this.vOffset === this._cachedVOffset &&
  30773. this.uScale === this._cachedUScale &&
  30774. this.vScale === this._cachedVScale &&
  30775. this.uAng === this._cachedUAng &&
  30776. this.vAng === this._cachedVAng &&
  30777. this.wAng === this._cachedWAng) {
  30778. return this._cachedTextureMatrix;
  30779. }
  30780. this._cachedUOffset = this.uOffset;
  30781. this._cachedVOffset = this.vOffset;
  30782. this._cachedUScale = this.uScale;
  30783. this._cachedVScale = this.vScale;
  30784. this._cachedUAng = this.uAng;
  30785. this._cachedVAng = this.vAng;
  30786. this._cachedWAng = this.wAng;
  30787. if (!this._cachedTextureMatrix) {
  30788. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30789. this._rowGenerationMatrix = new BABYLON.Matrix();
  30790. this._t0 = BABYLON.Vector3.Zero();
  30791. this._t1 = BABYLON.Vector3.Zero();
  30792. this._t2 = BABYLON.Vector3.Zero();
  30793. }
  30794. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30795. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30796. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30797. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30798. this._t1.subtractInPlace(this._t0);
  30799. this._t2.subtractInPlace(this._t0);
  30800. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30801. this._cachedTextureMatrix.m[0] = this._t1.x;
  30802. this._cachedTextureMatrix.m[1] = this._t1.y;
  30803. this._cachedTextureMatrix.m[2] = this._t1.z;
  30804. this._cachedTextureMatrix.m[4] = this._t2.x;
  30805. this._cachedTextureMatrix.m[5] = this._t2.y;
  30806. this._cachedTextureMatrix.m[6] = this._t2.z;
  30807. this._cachedTextureMatrix.m[8] = this._t0.x;
  30808. this._cachedTextureMatrix.m[9] = this._t0.y;
  30809. this._cachedTextureMatrix.m[10] = this._t0.z;
  30810. var scene = this.getScene();
  30811. if (!scene) {
  30812. return this._cachedTextureMatrix;
  30813. }
  30814. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30815. return mat.hasTexture(_this);
  30816. });
  30817. return this._cachedTextureMatrix;
  30818. };
  30819. Texture.prototype.getReflectionTextureMatrix = function () {
  30820. var _this = this;
  30821. var scene = this.getScene();
  30822. if (!scene) {
  30823. return this._cachedTextureMatrix;
  30824. }
  30825. if (this.uOffset === this._cachedUOffset &&
  30826. this.vOffset === this._cachedVOffset &&
  30827. this.uScale === this._cachedUScale &&
  30828. this.vScale === this._cachedVScale &&
  30829. this.coordinatesMode === this._cachedCoordinatesMode) {
  30830. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30831. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30832. return this._cachedTextureMatrix;
  30833. }
  30834. }
  30835. else {
  30836. return this._cachedTextureMatrix;
  30837. }
  30838. }
  30839. if (!this._cachedTextureMatrix) {
  30840. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30841. }
  30842. if (!this._projectionModeMatrix) {
  30843. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30844. }
  30845. this._cachedUOffset = this.uOffset;
  30846. this._cachedVOffset = this.vOffset;
  30847. this._cachedUScale = this.uScale;
  30848. this._cachedVScale = this.vScale;
  30849. this._cachedCoordinatesMode = this.coordinatesMode;
  30850. switch (this.coordinatesMode) {
  30851. case Texture.PLANAR_MODE:
  30852. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30853. this._cachedTextureMatrix[0] = this.uScale;
  30854. this._cachedTextureMatrix[5] = this.vScale;
  30855. this._cachedTextureMatrix[12] = this.uOffset;
  30856. this._cachedTextureMatrix[13] = this.vOffset;
  30857. break;
  30858. case Texture.PROJECTION_MODE:
  30859. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30860. this._projectionModeMatrix.m[0] = 0.5;
  30861. this._projectionModeMatrix.m[5] = -0.5;
  30862. this._projectionModeMatrix.m[10] = 0.0;
  30863. this._projectionModeMatrix.m[12] = 0.5;
  30864. this._projectionModeMatrix.m[13] = 0.5;
  30865. this._projectionModeMatrix.m[14] = 1.0;
  30866. this._projectionModeMatrix.m[15] = 1.0;
  30867. var projectionMatrix = scene.getProjectionMatrix();
  30868. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30869. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30870. break;
  30871. default:
  30872. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30873. break;
  30874. }
  30875. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30876. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30877. });
  30878. return this._cachedTextureMatrix;
  30879. };
  30880. Texture.prototype.clone = function () {
  30881. var _this = this;
  30882. return BABYLON.SerializationHelper.Clone(function () {
  30883. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30884. }, this);
  30885. };
  30886. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30887. get: function () {
  30888. if (!this._onLoadObservable) {
  30889. this._onLoadObservable = new BABYLON.Observable();
  30890. }
  30891. return this._onLoadObservable;
  30892. },
  30893. enumerable: true,
  30894. configurable: true
  30895. });
  30896. Texture.prototype.serialize = function () {
  30897. var serializationObject = _super.prototype.serialize.call(this);
  30898. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30899. serializationObject.base64String = this._buffer;
  30900. serializationObject.name = serializationObject.name.replace("data:", "");
  30901. }
  30902. serializationObject.invertY = this._invertY;
  30903. serializationObject.samplingMode = this.samplingMode;
  30904. return serializationObject;
  30905. };
  30906. Texture.prototype.getClassName = function () {
  30907. return "Texture";
  30908. };
  30909. Texture.prototype.dispose = function () {
  30910. _super.prototype.dispose.call(this);
  30911. if (this._onLoadObservable) {
  30912. this._onLoadObservable.clear();
  30913. this._onLoadObservable = null;
  30914. }
  30915. this._delayedOnLoad = null;
  30916. this._delayedOnError = null;
  30917. };
  30918. // Statics
  30919. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30920. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30921. if (onLoad === void 0) { onLoad = null; }
  30922. if (onError === void 0) { onError = null; }
  30923. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30924. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30925. };
  30926. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30927. if (parsedTexture.customType) {
  30928. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30929. // Update Sampling Mode
  30930. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30931. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30932. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30933. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30934. }
  30935. }
  30936. return parsedCustomTexture;
  30937. }
  30938. if (parsedTexture.isCube) {
  30939. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30940. }
  30941. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30942. return null;
  30943. }
  30944. var texture = BABYLON.SerializationHelper.Parse(function () {
  30945. var generateMipMaps = true;
  30946. if (parsedTexture.noMipmap) {
  30947. generateMipMaps = false;
  30948. }
  30949. if (parsedTexture.mirrorPlane) {
  30950. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30951. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30952. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30953. return mirrorTexture;
  30954. }
  30955. else if (parsedTexture.isRenderTarget) {
  30956. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30957. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30958. return renderTargetTexture;
  30959. }
  30960. else {
  30961. var texture;
  30962. if (parsedTexture.base64String) {
  30963. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30964. }
  30965. else {
  30966. var url = rootUrl + parsedTexture.name;
  30967. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30968. url = parsedTexture.url;
  30969. }
  30970. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30971. }
  30972. return texture;
  30973. }
  30974. }, parsedTexture, scene);
  30975. // Update Sampling Mode
  30976. if (parsedTexture.samplingMode) {
  30977. var sampling = parsedTexture.samplingMode;
  30978. if (texture._samplingMode !== sampling) {
  30979. texture.updateSamplingMode(sampling);
  30980. }
  30981. }
  30982. // Animations
  30983. if (parsedTexture.animations) {
  30984. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30985. var parsedAnimation = parsedTexture.animations[animationIndex];
  30986. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30987. }
  30988. }
  30989. return texture;
  30990. };
  30991. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30992. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30993. if (noMipmap === void 0) { noMipmap = false; }
  30994. if (invertY === void 0) { invertY = true; }
  30995. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30996. if (onLoad === void 0) { onLoad = null; }
  30997. if (onError === void 0) { onError = null; }
  30998. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30999. if (name.substr(0, 5) !== "data:") {
  31000. name = "data:" + name;
  31001. }
  31002. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31003. };
  31004. // Constants
  31005. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31006. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31007. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31008. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31009. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31010. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31011. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31012. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31013. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31014. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31015. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31016. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31017. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31018. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31019. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31020. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31021. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31022. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31023. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31024. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31025. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31026. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31027. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31028. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31029. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31030. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31031. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31032. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31033. /**
  31034. * 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
  31035. */
  31036. Texture.UseSerializedUrlIfAny = false;
  31037. __decorate([
  31038. BABYLON.serialize()
  31039. ], Texture.prototype, "url", void 0);
  31040. __decorate([
  31041. BABYLON.serialize()
  31042. ], Texture.prototype, "uOffset", void 0);
  31043. __decorate([
  31044. BABYLON.serialize()
  31045. ], Texture.prototype, "vOffset", void 0);
  31046. __decorate([
  31047. BABYLON.serialize()
  31048. ], Texture.prototype, "uScale", void 0);
  31049. __decorate([
  31050. BABYLON.serialize()
  31051. ], Texture.prototype, "vScale", void 0);
  31052. __decorate([
  31053. BABYLON.serialize()
  31054. ], Texture.prototype, "uAng", void 0);
  31055. __decorate([
  31056. BABYLON.serialize()
  31057. ], Texture.prototype, "vAng", void 0);
  31058. __decorate([
  31059. BABYLON.serialize()
  31060. ], Texture.prototype, "wAng", void 0);
  31061. __decorate([
  31062. BABYLON.serialize()
  31063. ], Texture.prototype, "uRotationCenter", void 0);
  31064. __decorate([
  31065. BABYLON.serialize()
  31066. ], Texture.prototype, "vRotationCenter", void 0);
  31067. __decorate([
  31068. BABYLON.serialize()
  31069. ], Texture.prototype, "wRotationCenter", void 0);
  31070. __decorate([
  31071. BABYLON.serialize()
  31072. ], Texture.prototype, "isBlocking", null);
  31073. return Texture;
  31074. }(BABYLON.BaseTexture));
  31075. BABYLON.Texture = Texture;
  31076. })(BABYLON || (BABYLON = {}));
  31077. //# sourceMappingURL=babylon.texture.js.map
  31078. var BABYLON;
  31079. (function (BABYLON) {
  31080. /**
  31081. * @hidden
  31082. **/
  31083. var _InstancesBatch = /** @class */ (function () {
  31084. function _InstancesBatch() {
  31085. this.mustReturn = false;
  31086. this.visibleInstances = new Array();
  31087. this.renderSelf = new Array();
  31088. }
  31089. return _InstancesBatch;
  31090. }());
  31091. BABYLON._InstancesBatch = _InstancesBatch;
  31092. var Mesh = /** @class */ (function (_super) {
  31093. __extends(Mesh, _super);
  31094. /**
  31095. * @constructor
  31096. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31097. * @param {Scene} scene The scene to add this mesh to.
  31098. * @param {Node} parent The parent of this mesh, if it has one
  31099. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31100. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31101. * When false, achieved by calling a clone(), also passing False.
  31102. * This will make creation of children, recursive.
  31103. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31104. */
  31105. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31106. if (scene === void 0) { scene = null; }
  31107. if (parent === void 0) { parent = null; }
  31108. if (source === void 0) { source = null; }
  31109. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31110. var _this = _super.call(this, name, scene) || this;
  31111. // Members
  31112. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31113. _this.instances = new Array();
  31114. _this._LODLevels = new Array();
  31115. /** @hidden */
  31116. _this._visibleInstances = {};
  31117. _this._renderIdForInstances = new Array();
  31118. _this._batchCache = new _InstancesBatch();
  31119. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31120. // Use by builder only to know what orientation were the mesh build in.
  31121. /** @hidden */
  31122. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31123. _this.overrideMaterialSideOrientation = null;
  31124. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31125. // Will be used to save a source mesh reference, If any
  31126. _this._source = null;
  31127. scene = _this.getScene();
  31128. if (source) {
  31129. // Geometry
  31130. if (source._geometry) {
  31131. source._geometry.applyToMesh(_this);
  31132. }
  31133. // Deep copy
  31134. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31135. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31136. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31137. ], ["_poseMatrix"]);
  31138. // Source mesh
  31139. _this._source = source;
  31140. // Construction Params
  31141. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31142. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31143. var myAnyThis = _this;
  31144. var myAnySource = source;
  31145. myAnyThis._closePath = myAnySource._closePath;
  31146. myAnyThis._idx = myAnySource._idx;
  31147. myAnyThis.dashSize = myAnySource.dashSize;
  31148. myAnyThis.gapSize = myAnySource.gapSize;
  31149. myAnyThis.path3D = myAnySource.path3D;
  31150. myAnyThis.pathArray = myAnySource.pathArray;
  31151. myAnyThis.arc = myAnySource.arc;
  31152. myAnyThis.radius = myAnySource.radius;
  31153. // Animation ranges
  31154. if (_this._source._ranges) {
  31155. var ranges = _this._source._ranges;
  31156. for (var name in ranges) {
  31157. if (!ranges.hasOwnProperty(name)) {
  31158. continue;
  31159. }
  31160. if (!ranges[name]) {
  31161. continue;
  31162. }
  31163. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31164. }
  31165. }
  31166. // Metadata
  31167. if (source.metadata && source.metadata.clone) {
  31168. _this.metadata = source.metadata.clone();
  31169. }
  31170. else {
  31171. _this.metadata = source.metadata;
  31172. }
  31173. // Tags
  31174. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31175. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31176. }
  31177. // Parent
  31178. _this.parent = source.parent;
  31179. // Pivot
  31180. _this.setPivotMatrix(source.getPivotMatrix());
  31181. _this.id = name + "." + source.id;
  31182. // Material
  31183. _this.material = source.material;
  31184. var index;
  31185. if (!doNotCloneChildren) {
  31186. // Children
  31187. var directDescendants = source.getDescendants(true);
  31188. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31189. var child = directDescendants[index_1];
  31190. if (child.clone) {
  31191. child.clone(name + "." + child.name, _this);
  31192. }
  31193. }
  31194. }
  31195. // Physics clone
  31196. var physicsEngine = _this.getScene().getPhysicsEngine();
  31197. if (clonePhysicsImpostor && physicsEngine) {
  31198. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31199. if (impostor) {
  31200. _this.physicsImpostor = impostor.clone(_this);
  31201. }
  31202. }
  31203. // Particles
  31204. for (index = 0; index < scene.particleSystems.length; index++) {
  31205. var system = scene.particleSystems[index];
  31206. if (system.emitter === source) {
  31207. system.clone(system.name, _this);
  31208. }
  31209. }
  31210. _this.refreshBoundingInfo();
  31211. _this.computeWorldMatrix(true);
  31212. }
  31213. // Parent
  31214. if (parent !== null) {
  31215. _this.parent = parent;
  31216. }
  31217. return _this;
  31218. }
  31219. Object.defineProperty(Mesh, "FRONTSIDE", {
  31220. /**
  31221. * Mesh side orientation : usually the external or front surface
  31222. */
  31223. get: function () {
  31224. return Mesh._FRONTSIDE;
  31225. },
  31226. enumerable: true,
  31227. configurable: true
  31228. });
  31229. Object.defineProperty(Mesh, "BACKSIDE", {
  31230. /**
  31231. * Mesh side orientation : usually the internal or back surface
  31232. */
  31233. get: function () {
  31234. return Mesh._BACKSIDE;
  31235. },
  31236. enumerable: true,
  31237. configurable: true
  31238. });
  31239. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31240. /**
  31241. * Mesh side orientation : both internal and external or front and back surfaces
  31242. */
  31243. get: function () {
  31244. return Mesh._DOUBLESIDE;
  31245. },
  31246. enumerable: true,
  31247. configurable: true
  31248. });
  31249. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31250. /**
  31251. * Mesh side orientation : by default, `FRONTSIDE`
  31252. */
  31253. get: function () {
  31254. return Mesh._DEFAULTSIDE;
  31255. },
  31256. enumerable: true,
  31257. configurable: true
  31258. });
  31259. Object.defineProperty(Mesh, "NO_CAP", {
  31260. /**
  31261. * Mesh cap setting : no cap
  31262. */
  31263. get: function () {
  31264. return Mesh._NO_CAP;
  31265. },
  31266. enumerable: true,
  31267. configurable: true
  31268. });
  31269. Object.defineProperty(Mesh, "CAP_START", {
  31270. /**
  31271. * Mesh cap setting : one cap at the beginning of the mesh
  31272. */
  31273. get: function () {
  31274. return Mesh._CAP_START;
  31275. },
  31276. enumerable: true,
  31277. configurable: true
  31278. });
  31279. Object.defineProperty(Mesh, "CAP_END", {
  31280. /**
  31281. * Mesh cap setting : one cap at the end of the mesh
  31282. */
  31283. get: function () {
  31284. return Mesh._CAP_END;
  31285. },
  31286. enumerable: true,
  31287. configurable: true
  31288. });
  31289. Object.defineProperty(Mesh, "CAP_ALL", {
  31290. /**
  31291. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31292. */
  31293. get: function () {
  31294. return Mesh._CAP_ALL;
  31295. },
  31296. enumerable: true,
  31297. configurable: true
  31298. });
  31299. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31300. /**
  31301. * An event triggered before rendering the mesh
  31302. */
  31303. get: function () {
  31304. if (!this._onBeforeRenderObservable) {
  31305. this._onBeforeRenderObservable = new BABYLON.Observable();
  31306. }
  31307. return this._onBeforeRenderObservable;
  31308. },
  31309. enumerable: true,
  31310. configurable: true
  31311. });
  31312. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31313. /**
  31314. * An event triggered after rendering the mesh
  31315. */
  31316. get: function () {
  31317. if (!this._onAfterRenderObservable) {
  31318. this._onAfterRenderObservable = new BABYLON.Observable();
  31319. }
  31320. return this._onAfterRenderObservable;
  31321. },
  31322. enumerable: true,
  31323. configurable: true
  31324. });
  31325. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31326. /**
  31327. * An event triggered before drawing the mesh
  31328. */
  31329. get: function () {
  31330. if (!this._onBeforeDrawObservable) {
  31331. this._onBeforeDrawObservable = new BABYLON.Observable();
  31332. }
  31333. return this._onBeforeDrawObservable;
  31334. },
  31335. enumerable: true,
  31336. configurable: true
  31337. });
  31338. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31339. set: function (callback) {
  31340. if (this._onBeforeDrawObserver) {
  31341. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31342. }
  31343. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31344. },
  31345. enumerable: true,
  31346. configurable: true
  31347. });
  31348. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31349. get: function () {
  31350. return this._morphTargetManager;
  31351. },
  31352. set: function (value) {
  31353. if (this._morphTargetManager === value) {
  31354. return;
  31355. }
  31356. this._morphTargetManager = value;
  31357. this._syncGeometryWithMorphTargetManager();
  31358. },
  31359. enumerable: true,
  31360. configurable: true
  31361. });
  31362. Object.defineProperty(Mesh.prototype, "source", {
  31363. get: function () {
  31364. return this._source;
  31365. },
  31366. enumerable: true,
  31367. configurable: true
  31368. });
  31369. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31370. get: function () {
  31371. return this._unIndexed;
  31372. },
  31373. set: function (value) {
  31374. if (this._unIndexed !== value) {
  31375. this._unIndexed = value;
  31376. this._markSubMeshesAsAttributesDirty();
  31377. }
  31378. },
  31379. enumerable: true,
  31380. configurable: true
  31381. });
  31382. // Methods
  31383. /**
  31384. * Returns the string "Mesh".
  31385. */
  31386. Mesh.prototype.getClassName = function () {
  31387. return "Mesh";
  31388. };
  31389. /**
  31390. * Returns a string.
  31391. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31392. */
  31393. Mesh.prototype.toString = function (fullDetails) {
  31394. var ret = _super.prototype.toString.call(this, fullDetails);
  31395. ret += ", n vertices: " + this.getTotalVertices();
  31396. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31397. if (this.animations) {
  31398. for (var i = 0; i < this.animations.length; i++) {
  31399. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31400. }
  31401. }
  31402. if (fullDetails) {
  31403. if (this._geometry) {
  31404. var ib = this.getIndices();
  31405. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31406. if (vb && ib) {
  31407. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31408. }
  31409. }
  31410. else {
  31411. ret += ", flat shading: UNKNOWN";
  31412. }
  31413. }
  31414. return ret;
  31415. };
  31416. /** @hidden */
  31417. Mesh.prototype._unBindEffect = function () {
  31418. _super.prototype._unBindEffect.call(this);
  31419. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31420. var instance = _a[_i];
  31421. instance._unBindEffect();
  31422. }
  31423. };
  31424. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31425. /**
  31426. * True if the mesh has some Levels Of Details (LOD).
  31427. * Returns a boolean.
  31428. */
  31429. get: function () {
  31430. return this._LODLevels.length > 0;
  31431. },
  31432. enumerable: true,
  31433. configurable: true
  31434. });
  31435. /**
  31436. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31437. * @returns an array of {BABYLON.MeshLODLevel}
  31438. */
  31439. Mesh.prototype.getLODLevels = function () {
  31440. return this._LODLevels;
  31441. };
  31442. Mesh.prototype._sortLODLevels = function () {
  31443. this._LODLevels.sort(function (a, b) {
  31444. if (a.distance < b.distance) {
  31445. return 1;
  31446. }
  31447. if (a.distance > b.distance) {
  31448. return -1;
  31449. }
  31450. return 0;
  31451. });
  31452. };
  31453. /**
  31454. * Add a mesh as LOD level triggered at the given distance.
  31455. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31456. * @param distance The distance from the center of the object to show this level
  31457. * @param mesh The mesh to be added as LOD level (can be null)
  31458. * @return This mesh (for chaining)
  31459. */
  31460. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31461. if (mesh && mesh._masterMesh) {
  31462. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31463. return this;
  31464. }
  31465. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31466. this._LODLevels.push(level);
  31467. if (mesh) {
  31468. mesh._masterMesh = this;
  31469. }
  31470. this._sortLODLevels();
  31471. return this;
  31472. };
  31473. /**
  31474. * Returns the LOD level mesh at the passed distance or null if not found.
  31475. * It is related to the method `addLODLevel(distance, mesh)`.
  31476. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31477. * Returns an object Mesh or `null`.
  31478. */
  31479. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31480. for (var index = 0; index < this._LODLevels.length; index++) {
  31481. var level = this._LODLevels[index];
  31482. if (level.distance === distance) {
  31483. return level.mesh;
  31484. }
  31485. }
  31486. return null;
  31487. };
  31488. /**
  31489. * Remove a mesh from the LOD array
  31490. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31491. * @param {Mesh} mesh The mesh to be removed.
  31492. * @return {Mesh} This mesh (for chaining)
  31493. */
  31494. Mesh.prototype.removeLODLevel = function (mesh) {
  31495. for (var index = 0; index < this._LODLevels.length; index++) {
  31496. if (this._LODLevels[index].mesh === mesh) {
  31497. this._LODLevels.splice(index, 1);
  31498. if (mesh) {
  31499. mesh._masterMesh = null;
  31500. }
  31501. }
  31502. }
  31503. this._sortLODLevels();
  31504. return this;
  31505. };
  31506. /**
  31507. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31508. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31509. */
  31510. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31511. if (!this._LODLevels || this._LODLevels.length === 0) {
  31512. return this;
  31513. }
  31514. var bSphere;
  31515. if (boundingSphere) {
  31516. bSphere = boundingSphere;
  31517. }
  31518. else {
  31519. var boundingInfo = this.getBoundingInfo();
  31520. bSphere = boundingInfo.boundingSphere;
  31521. }
  31522. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31523. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31524. if (this.onLODLevelSelection) {
  31525. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31526. }
  31527. return this;
  31528. }
  31529. for (var index = 0; index < this._LODLevels.length; index++) {
  31530. var level = this._LODLevels[index];
  31531. if (level.distance < distanceToCamera) {
  31532. if (level.mesh) {
  31533. level.mesh._preActivate();
  31534. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31535. }
  31536. if (this.onLODLevelSelection) {
  31537. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31538. }
  31539. return level.mesh;
  31540. }
  31541. }
  31542. if (this.onLODLevelSelection) {
  31543. this.onLODLevelSelection(distanceToCamera, this, this);
  31544. }
  31545. return this;
  31546. };
  31547. Object.defineProperty(Mesh.prototype, "geometry", {
  31548. /**
  31549. * Returns the mesh internal Geometry object.
  31550. */
  31551. get: function () {
  31552. return this._geometry;
  31553. },
  31554. enumerable: true,
  31555. configurable: true
  31556. });
  31557. /**
  31558. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31559. */
  31560. Mesh.prototype.getTotalVertices = function () {
  31561. if (this._geometry === null || this._geometry === undefined) {
  31562. return 0;
  31563. }
  31564. return this._geometry.getTotalVertices();
  31565. };
  31566. /**
  31567. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31568. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31569. * You can force the copy with forceCopy === true
  31570. * Returns null if the mesh has no geometry or no vertex buffer.
  31571. * Possible `kind` values :
  31572. * - BABYLON.VertexBuffer.PositionKind
  31573. * - BABYLON.VertexBuffer.UVKind
  31574. * - BABYLON.VertexBuffer.UV2Kind
  31575. * - BABYLON.VertexBuffer.UV3Kind
  31576. * - BABYLON.VertexBuffer.UV4Kind
  31577. * - BABYLON.VertexBuffer.UV5Kind
  31578. * - BABYLON.VertexBuffer.UV6Kind
  31579. * - BABYLON.VertexBuffer.ColorKind
  31580. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31581. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31582. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31583. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31584. */
  31585. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31586. if (!this._geometry) {
  31587. return null;
  31588. }
  31589. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31590. };
  31591. /**
  31592. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31593. * Returns `null` if the mesh has no geometry.
  31594. * Possible `kind` values :
  31595. * - BABYLON.VertexBuffer.PositionKind
  31596. * - BABYLON.VertexBuffer.UVKind
  31597. * - BABYLON.VertexBuffer.UV2Kind
  31598. * - BABYLON.VertexBuffer.UV3Kind
  31599. * - BABYLON.VertexBuffer.UV4Kind
  31600. * - BABYLON.VertexBuffer.UV5Kind
  31601. * - BABYLON.VertexBuffer.UV6Kind
  31602. * - BABYLON.VertexBuffer.ColorKind
  31603. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31604. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31605. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31606. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31607. */
  31608. Mesh.prototype.getVertexBuffer = function (kind) {
  31609. if (!this._geometry) {
  31610. return null;
  31611. }
  31612. return this._geometry.getVertexBuffer(kind);
  31613. };
  31614. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31615. if (!this._geometry) {
  31616. if (this._delayInfo) {
  31617. return this._delayInfo.indexOf(kind) !== -1;
  31618. }
  31619. return false;
  31620. }
  31621. return this._geometry.isVerticesDataPresent(kind);
  31622. };
  31623. /**
  31624. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31625. * Possible `kind` values :
  31626. * - BABYLON.VertexBuffer.PositionKind
  31627. * - BABYLON.VertexBuffer.UVKind
  31628. * - BABYLON.VertexBuffer.UV2Kind
  31629. * - BABYLON.VertexBuffer.UV3Kind
  31630. * - BABYLON.VertexBuffer.UV4Kind
  31631. * - BABYLON.VertexBuffer.UV5Kind
  31632. * - BABYLON.VertexBuffer.UV6Kind
  31633. * - BABYLON.VertexBuffer.ColorKind
  31634. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31635. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31636. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31637. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31638. */
  31639. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31640. if (!this._geometry) {
  31641. if (this._delayInfo) {
  31642. return this._delayInfo.indexOf(kind) !== -1;
  31643. }
  31644. return false;
  31645. }
  31646. return this._geometry.isVertexBufferUpdatable(kind);
  31647. };
  31648. /**
  31649. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31650. * Possible `kind` values :
  31651. * - BABYLON.VertexBuffer.PositionKind
  31652. * - BABYLON.VertexBuffer.UVKind
  31653. * - BABYLON.VertexBuffer.UV2Kind
  31654. * - BABYLON.VertexBuffer.UV3Kind
  31655. * - BABYLON.VertexBuffer.UV4Kind
  31656. * - BABYLON.VertexBuffer.UV5Kind
  31657. * - BABYLON.VertexBuffer.UV6Kind
  31658. * - BABYLON.VertexBuffer.ColorKind
  31659. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31660. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31661. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31662. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31663. */
  31664. Mesh.prototype.getVerticesDataKinds = function () {
  31665. if (!this._geometry) {
  31666. var result = new Array();
  31667. if (this._delayInfo) {
  31668. this._delayInfo.forEach(function (kind, index, array) {
  31669. result.push(kind);
  31670. });
  31671. }
  31672. return result;
  31673. }
  31674. return this._geometry.getVerticesDataKinds();
  31675. };
  31676. /**
  31677. * Returns a positive integer : the total number of indices in this mesh geometry.
  31678. * Returns zero if the mesh has no geometry.
  31679. */
  31680. Mesh.prototype.getTotalIndices = function () {
  31681. if (!this._geometry) {
  31682. return 0;
  31683. }
  31684. return this._geometry.getTotalIndices();
  31685. };
  31686. /**
  31687. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31688. * @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.
  31689. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31690. * @returns the indices array or an empty array if the mesh has no geometry
  31691. */
  31692. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31693. if (!this._geometry) {
  31694. return [];
  31695. }
  31696. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31697. };
  31698. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31699. get: function () {
  31700. return this._masterMesh !== null && this._masterMesh !== undefined;
  31701. },
  31702. enumerable: true,
  31703. configurable: true
  31704. });
  31705. /**
  31706. * Determine if the current mesh is ready to be rendered
  31707. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31708. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31709. * @returns true if all associated assets are ready (material, textures, shaders)
  31710. */
  31711. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31712. if (completeCheck === void 0) { completeCheck = false; }
  31713. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31714. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31715. return false;
  31716. }
  31717. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31718. return false;
  31719. }
  31720. if (!this.subMeshes || this.subMeshes.length === 0) {
  31721. return true;
  31722. }
  31723. if (!completeCheck) {
  31724. return true;
  31725. }
  31726. var engine = this.getEngine();
  31727. var scene = this.getScene();
  31728. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31729. this.computeWorldMatrix();
  31730. var mat = this.material || scene.defaultMaterial;
  31731. if (mat) {
  31732. if (mat.storeEffectOnSubMeshes) {
  31733. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31734. var subMesh = _a[_i];
  31735. var effectiveMaterial = subMesh.getMaterial();
  31736. if (effectiveMaterial) {
  31737. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31738. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31739. return false;
  31740. }
  31741. }
  31742. else {
  31743. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31744. return false;
  31745. }
  31746. }
  31747. }
  31748. }
  31749. }
  31750. else {
  31751. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31752. return false;
  31753. }
  31754. }
  31755. }
  31756. // Shadows
  31757. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31758. var light = _c[_b];
  31759. var generator = light.getShadowGenerator();
  31760. if (generator) {
  31761. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31762. var subMesh = _e[_d];
  31763. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31764. return false;
  31765. }
  31766. }
  31767. }
  31768. }
  31769. // LOD
  31770. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31771. var lod = _g[_f];
  31772. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31773. return false;
  31774. }
  31775. }
  31776. return true;
  31777. };
  31778. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31779. /**
  31780. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31781. * This property is pertinent only for updatable parametric shapes.
  31782. */
  31783. get: function () {
  31784. return this._areNormalsFrozen;
  31785. },
  31786. enumerable: true,
  31787. configurable: true
  31788. });
  31789. /**
  31790. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31791. * It has no effect at all on other shapes.
  31792. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31793. * Returns the Mesh.
  31794. */
  31795. Mesh.prototype.freezeNormals = function () {
  31796. this._areNormalsFrozen = true;
  31797. return this;
  31798. };
  31799. /**
  31800. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31801. * It has no effect at all on other shapes.
  31802. * It reactivates the mesh normals computation if it was previously frozen.
  31803. * Returns the Mesh.
  31804. */
  31805. Mesh.prototype.unfreezeNormals = function () {
  31806. this._areNormalsFrozen = false;
  31807. return this;
  31808. };
  31809. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31810. /**
  31811. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31812. */
  31813. set: function (count) {
  31814. this._overridenInstanceCount = count;
  31815. },
  31816. enumerable: true,
  31817. configurable: true
  31818. });
  31819. // Methods
  31820. /** @hidden */
  31821. Mesh.prototype._preActivate = function () {
  31822. var sceneRenderId = this.getScene().getRenderId();
  31823. if (this._preActivateId === sceneRenderId) {
  31824. return this;
  31825. }
  31826. this._preActivateId = sceneRenderId;
  31827. this._visibleInstances = null;
  31828. return this;
  31829. };
  31830. /** @hidden */
  31831. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31832. if (this._visibleInstances) {
  31833. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31834. }
  31835. return this;
  31836. };
  31837. /** @hidden */
  31838. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31839. if (!this._visibleInstances) {
  31840. this._visibleInstances = {};
  31841. this._visibleInstances.defaultRenderId = renderId;
  31842. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31843. }
  31844. if (!this._visibleInstances[renderId]) {
  31845. this._visibleInstances[renderId] = new Array();
  31846. }
  31847. this._visibleInstances[renderId].push(instance);
  31848. return this;
  31849. };
  31850. /**
  31851. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31852. * This means the mesh underlying bounding box and sphere are recomputed.
  31853. * Returns the Mesh.
  31854. */
  31855. Mesh.prototype.refreshBoundingInfo = function () {
  31856. return this._refreshBoundingInfo(false);
  31857. };
  31858. /** @hidden */
  31859. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31860. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31861. return this;
  31862. }
  31863. var data = this._getPositionData(applySkeleton);
  31864. if (data) {
  31865. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31866. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31867. }
  31868. if (this.subMeshes) {
  31869. for (var index = 0; index < this.subMeshes.length; index++) {
  31870. this.subMeshes[index].refreshBoundingInfo();
  31871. }
  31872. }
  31873. this._updateBoundingInfo();
  31874. return this;
  31875. };
  31876. Mesh.prototype._getPositionData = function (applySkeleton) {
  31877. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31878. if (data && applySkeleton && this.skeleton) {
  31879. data = BABYLON.Tools.Slice(data);
  31880. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31881. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31882. if (matricesWeightsData && matricesIndicesData) {
  31883. var needExtras = this.numBoneInfluencers > 4;
  31884. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31885. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31886. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31887. var tempVector = BABYLON.Tmp.Vector3[0];
  31888. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31889. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31890. var matWeightIdx = 0;
  31891. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31892. finalMatrix.reset();
  31893. var inf;
  31894. var weight;
  31895. for (inf = 0; inf < 4; inf++) {
  31896. weight = matricesWeightsData[matWeightIdx + inf];
  31897. if (weight > 0) {
  31898. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31899. finalMatrix.addToSelf(tempMatrix);
  31900. }
  31901. }
  31902. if (needExtras) {
  31903. for (inf = 0; inf < 4; inf++) {
  31904. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31905. if (weight > 0) {
  31906. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31907. finalMatrix.addToSelf(tempMatrix);
  31908. }
  31909. }
  31910. }
  31911. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31912. tempVector.toArray(data, index);
  31913. }
  31914. }
  31915. }
  31916. return data;
  31917. };
  31918. /** @hidden */
  31919. Mesh.prototype._createGlobalSubMesh = function (force) {
  31920. var totalVertices = this.getTotalVertices();
  31921. if (!totalVertices || !this.getIndices()) {
  31922. return null;
  31923. }
  31924. // Check if we need to recreate the submeshes
  31925. if (this.subMeshes && this.subMeshes.length > 0) {
  31926. var ib = this.getIndices();
  31927. if (!ib) {
  31928. return null;
  31929. }
  31930. var totalIndices = ib.length;
  31931. var needToRecreate = false;
  31932. if (force) {
  31933. needToRecreate = true;
  31934. }
  31935. else {
  31936. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31937. var submesh = _a[_i];
  31938. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31939. needToRecreate = true;
  31940. break;
  31941. }
  31942. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31943. needToRecreate = true;
  31944. break;
  31945. }
  31946. }
  31947. }
  31948. if (!needToRecreate) {
  31949. return this.subMeshes[0];
  31950. }
  31951. }
  31952. this.releaseSubMeshes();
  31953. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31954. };
  31955. Mesh.prototype.subdivide = function (count) {
  31956. if (count < 1) {
  31957. return;
  31958. }
  31959. var totalIndices = this.getTotalIndices();
  31960. var subdivisionSize = (totalIndices / count) | 0;
  31961. var offset = 0;
  31962. // Ensure that subdivisionSize is a multiple of 3
  31963. while (subdivisionSize % 3 !== 0) {
  31964. subdivisionSize++;
  31965. }
  31966. this.releaseSubMeshes();
  31967. for (var index = 0; index < count; index++) {
  31968. if (offset >= totalIndices) {
  31969. break;
  31970. }
  31971. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31972. offset += subdivisionSize;
  31973. }
  31974. this.synchronizeInstances();
  31975. };
  31976. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31977. if (updatable === void 0) { updatable = false; }
  31978. if (!this._geometry) {
  31979. var vertexData = new BABYLON.VertexData();
  31980. vertexData.set(data, kind);
  31981. var scene = this.getScene();
  31982. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31983. }
  31984. else {
  31985. this._geometry.setVerticesData(kind, data, updatable, stride);
  31986. }
  31987. return this;
  31988. };
  31989. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31990. if (updatable === void 0) { updatable = true; }
  31991. var vb = this.getVertexBuffer(kind);
  31992. if (!vb || vb.isUpdatable() === updatable) {
  31993. return;
  31994. }
  31995. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31996. };
  31997. /**
  31998. * Sets the mesh VertexBuffer.
  31999. * Returns the Mesh.
  32000. */
  32001. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32002. if (!this._geometry) {
  32003. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32004. }
  32005. this._geometry.setVerticesBuffer(buffer);
  32006. return this;
  32007. };
  32008. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32009. if (!this._geometry) {
  32010. return this;
  32011. }
  32012. if (!makeItUnique) {
  32013. this._geometry.updateVerticesData(kind, data, updateExtends);
  32014. }
  32015. else {
  32016. this.makeGeometryUnique();
  32017. this.updateVerticesData(kind, data, updateExtends, false);
  32018. }
  32019. return this;
  32020. };
  32021. /**
  32022. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32023. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32024. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32025. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32026. * Returns the Mesh.
  32027. */
  32028. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32029. if (computeNormals === void 0) { computeNormals = true; }
  32030. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32031. if (!positions) {
  32032. return this;
  32033. }
  32034. positionFunction(positions);
  32035. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32036. if (computeNormals) {
  32037. var indices = this.getIndices();
  32038. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32039. if (!normals) {
  32040. return this;
  32041. }
  32042. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32043. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32044. }
  32045. return this;
  32046. };
  32047. /**
  32048. * Creates a un-shared specific occurence of the geometry for the mesh.
  32049. * Returns the Mesh.
  32050. */
  32051. Mesh.prototype.makeGeometryUnique = function () {
  32052. if (!this._geometry) {
  32053. return this;
  32054. }
  32055. var oldGeometry = this._geometry;
  32056. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32057. oldGeometry.releaseForMesh(this, true);
  32058. geometry.applyToMesh(this);
  32059. return this;
  32060. };
  32061. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32062. if (totalVertices === void 0) { totalVertices = null; }
  32063. if (updatable === void 0) { updatable = false; }
  32064. if (!this._geometry) {
  32065. var vertexData = new BABYLON.VertexData();
  32066. vertexData.indices = indices;
  32067. var scene = this.getScene();
  32068. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32069. }
  32070. else {
  32071. this._geometry.setIndices(indices, totalVertices, updatable);
  32072. }
  32073. return this;
  32074. };
  32075. /**
  32076. * Update the current index buffer
  32077. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32078. * Returns the Mesh.
  32079. */
  32080. Mesh.prototype.updateIndices = function (indices, offset) {
  32081. if (!this._geometry) {
  32082. return this;
  32083. }
  32084. this._geometry.updateIndices(indices, offset);
  32085. return this;
  32086. };
  32087. /**
  32088. * Invert the geometry to move from a right handed system to a left handed one.
  32089. * Returns the Mesh.
  32090. */
  32091. Mesh.prototype.toLeftHanded = function () {
  32092. if (!this._geometry) {
  32093. return this;
  32094. }
  32095. this._geometry.toLeftHanded();
  32096. return this;
  32097. };
  32098. /** @hidden */
  32099. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32100. if (!this._geometry) {
  32101. return this;
  32102. }
  32103. var engine = this.getScene().getEngine();
  32104. // Wireframe
  32105. var indexToBind;
  32106. if (this._unIndexed) {
  32107. indexToBind = null;
  32108. }
  32109. else {
  32110. switch (fillMode) {
  32111. case BABYLON.Material.PointFillMode:
  32112. indexToBind = null;
  32113. break;
  32114. case BABYLON.Material.WireFrameFillMode:
  32115. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32116. break;
  32117. default:
  32118. case BABYLON.Material.TriangleFillMode:
  32119. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32120. break;
  32121. }
  32122. }
  32123. // VBOs
  32124. this._geometry._bind(effect, indexToBind);
  32125. return this;
  32126. };
  32127. /** @hidden */
  32128. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32129. if (alternate === void 0) { alternate = false; }
  32130. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32131. return this;
  32132. }
  32133. if (this._onBeforeDrawObservable) {
  32134. this._onBeforeDrawObservable.notifyObservers(this);
  32135. }
  32136. var scene = this.getScene();
  32137. var engine = scene.getEngine();
  32138. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32139. // or triangles as points
  32140. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32141. }
  32142. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32143. // Triangles as wireframe
  32144. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32145. }
  32146. else {
  32147. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32148. }
  32149. if (scene._isAlternateRenderingEnabled && !alternate) {
  32150. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32151. if (!effect || !scene.activeCamera) {
  32152. return this;
  32153. }
  32154. scene._switchToAlternateCameraConfiguration(true);
  32155. this._effectiveMaterial.bindView(effect);
  32156. this._effectiveMaterial.bindViewProjection(effect);
  32157. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32158. this._draw(subMesh, fillMode, instancesCount, true);
  32159. engine.setViewport(scene.activeCamera.viewport);
  32160. scene._switchToAlternateCameraConfiguration(false);
  32161. this._effectiveMaterial.bindView(effect);
  32162. this._effectiveMaterial.bindViewProjection(effect);
  32163. }
  32164. return this;
  32165. };
  32166. /**
  32167. * Registers for this mesh a javascript function called just before the rendering process.
  32168. * This function is passed the current mesh.
  32169. * Return the Mesh.
  32170. */
  32171. Mesh.prototype.registerBeforeRender = function (func) {
  32172. this.onBeforeRenderObservable.add(func);
  32173. return this;
  32174. };
  32175. /**
  32176. * Disposes a previously registered javascript function called before the rendering.
  32177. * This function is passed the current mesh.
  32178. * Returns the Mesh.
  32179. */
  32180. Mesh.prototype.unregisterBeforeRender = function (func) {
  32181. this.onBeforeRenderObservable.removeCallback(func);
  32182. return this;
  32183. };
  32184. /**
  32185. * Registers for this mesh a javascript function called just after the rendering is complete.
  32186. * This function is passed the current mesh.
  32187. * Returns the Mesh.
  32188. */
  32189. Mesh.prototype.registerAfterRender = function (func) {
  32190. this.onAfterRenderObservable.add(func);
  32191. return this;
  32192. };
  32193. /**
  32194. * Disposes a previously registered javascript function called after the rendering.
  32195. * This function is passed the current mesh.
  32196. * Return the Mesh.
  32197. */
  32198. Mesh.prototype.unregisterAfterRender = function (func) {
  32199. this.onAfterRenderObservable.removeCallback(func);
  32200. return this;
  32201. };
  32202. /** @hidden */
  32203. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32204. var scene = this.getScene();
  32205. this._batchCache.mustReturn = false;
  32206. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32207. this._batchCache.visibleInstances[subMeshId] = null;
  32208. if (this._visibleInstances) {
  32209. var currentRenderId = scene.getRenderId();
  32210. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32211. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32212. var selfRenderId = this._renderId;
  32213. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32214. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32215. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32216. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32217. }
  32218. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32219. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32220. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32221. this._batchCache.mustReturn = true;
  32222. return this._batchCache;
  32223. }
  32224. if (currentRenderId !== selfRenderId) {
  32225. this._batchCache.renderSelf[subMeshId] = false;
  32226. }
  32227. }
  32228. this._renderIdForInstances[subMeshId] = currentRenderId;
  32229. }
  32230. return this._batchCache;
  32231. };
  32232. /** @hidden */
  32233. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32234. var visibleInstances = batch.visibleInstances[subMesh._id];
  32235. if (!visibleInstances) {
  32236. return this;
  32237. }
  32238. var matricesCount = visibleInstances.length + 1;
  32239. var bufferSize = matricesCount * 16 * 4;
  32240. var currentInstancesBufferSize = this._instancesBufferSize;
  32241. var instancesBuffer = this._instancesBuffer;
  32242. while (this._instancesBufferSize < bufferSize) {
  32243. this._instancesBufferSize *= 2;
  32244. }
  32245. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32246. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32247. }
  32248. var offset = 0;
  32249. var instancesCount = 0;
  32250. var world = this.getWorldMatrix();
  32251. if (batch.renderSelf[subMesh._id]) {
  32252. world.copyToArray(this._instancesData, offset);
  32253. offset += 16;
  32254. instancesCount++;
  32255. }
  32256. if (visibleInstances) {
  32257. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32258. var instance = visibleInstances[instanceIndex];
  32259. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32260. offset += 16;
  32261. instancesCount++;
  32262. }
  32263. }
  32264. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32265. if (instancesBuffer) {
  32266. instancesBuffer.dispose();
  32267. }
  32268. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32269. this._instancesBuffer = instancesBuffer;
  32270. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32271. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32272. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32273. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32274. }
  32275. else {
  32276. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32277. }
  32278. this._bind(subMesh, effect, fillMode);
  32279. this._draw(subMesh, fillMode, instancesCount);
  32280. engine.unbindInstanceAttributes();
  32281. return this;
  32282. };
  32283. /** @hidden */
  32284. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32285. var scene = this.getScene();
  32286. var engine = scene.getEngine();
  32287. if (hardwareInstancedRendering) {
  32288. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32289. }
  32290. else {
  32291. if (batch.renderSelf[subMesh._id]) {
  32292. // Draw
  32293. if (onBeforeDraw) {
  32294. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32295. }
  32296. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32297. }
  32298. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32299. if (visibleInstancesForSubMesh) {
  32300. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32301. var instance = visibleInstancesForSubMesh[instanceIndex];
  32302. // World
  32303. var world = instance.getWorldMatrix();
  32304. if (onBeforeDraw) {
  32305. onBeforeDraw(true, world, effectiveMaterial);
  32306. }
  32307. // Draw
  32308. this._draw(subMesh, fillMode);
  32309. }
  32310. }
  32311. }
  32312. return this;
  32313. };
  32314. /**
  32315. * 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
  32316. * @param subMesh defines the subMesh to render
  32317. * @param enableAlphaMode defines if alpha mode can be changed
  32318. * @returns the current mesh
  32319. */
  32320. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32321. this._checkOcclusionQuery();
  32322. if (this._isOccluded) {
  32323. return this;
  32324. }
  32325. var scene = this.getScene();
  32326. // Managing instances
  32327. var batch = this._getInstancesRenderList(subMesh._id);
  32328. if (batch.mustReturn) {
  32329. return this;
  32330. }
  32331. // Checking geometry state
  32332. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32333. return this;
  32334. }
  32335. if (this._onBeforeRenderObservable) {
  32336. this._onBeforeRenderObservable.notifyObservers(this);
  32337. }
  32338. var engine = scene.getEngine();
  32339. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32340. // Material
  32341. var material = subMesh.getMaterial();
  32342. if (!material) {
  32343. return this;
  32344. }
  32345. this._effectiveMaterial = material;
  32346. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32347. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32348. return this;
  32349. }
  32350. }
  32351. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32352. return this;
  32353. }
  32354. // Alpha mode
  32355. if (enableAlphaMode) {
  32356. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32357. }
  32358. // Outline - step 1
  32359. var savedDepthWrite = engine.getDepthWrite();
  32360. if (this.renderOutline) {
  32361. engine.setDepthWrite(false);
  32362. scene.getOutlineRenderer().render(subMesh, batch);
  32363. engine.setDepthWrite(savedDepthWrite);
  32364. }
  32365. var effect;
  32366. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32367. effect = subMesh.effect;
  32368. }
  32369. else {
  32370. effect = this._effectiveMaterial.getEffect();
  32371. }
  32372. if (!effect) {
  32373. return this;
  32374. }
  32375. var sideOrientation = this.overrideMaterialSideOrientation;
  32376. if (sideOrientation == null) {
  32377. sideOrientation = this._effectiveMaterial.sideOrientation;
  32378. if (this._getWorldMatrixDeterminant() < 0) {
  32379. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32380. }
  32381. }
  32382. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32383. if (this._effectiveMaterial.forceDepthWrite) {
  32384. engine.setDepthWrite(true);
  32385. }
  32386. // Bind
  32387. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32388. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32389. this._bind(subMesh, effect, fillMode);
  32390. }
  32391. var world = this.getWorldMatrix();
  32392. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32393. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32394. }
  32395. else {
  32396. this._effectiveMaterial.bind(world, this);
  32397. }
  32398. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32399. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32400. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32401. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32402. }
  32403. // Draw
  32404. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32405. // Unbind
  32406. this._effectiveMaterial.unbind();
  32407. // Outline - step 2
  32408. if (this.renderOutline && savedDepthWrite) {
  32409. engine.setDepthWrite(true);
  32410. engine.setColorWrite(false);
  32411. scene.getOutlineRenderer().render(subMesh, batch);
  32412. engine.setColorWrite(true);
  32413. }
  32414. // Overlay
  32415. if (this.renderOverlay) {
  32416. var currentMode = engine.getAlphaMode();
  32417. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32418. scene.getOutlineRenderer().render(subMesh, batch, true);
  32419. engine.setAlphaMode(currentMode);
  32420. }
  32421. if (this._onAfterRenderObservable) {
  32422. this._onAfterRenderObservable.notifyObservers(this);
  32423. }
  32424. return this;
  32425. };
  32426. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32427. if (isInstance && effectiveMaterial) {
  32428. effectiveMaterial.bindOnlyWorldMatrix(world);
  32429. }
  32430. };
  32431. /**
  32432. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32433. */
  32434. Mesh.prototype.getEmittedParticleSystems = function () {
  32435. var results = new Array();
  32436. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32437. var particleSystem = this.getScene().particleSystems[index];
  32438. if (particleSystem.emitter === this) {
  32439. results.push(particleSystem);
  32440. }
  32441. }
  32442. return results;
  32443. };
  32444. /**
  32445. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32446. */
  32447. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32448. var results = new Array();
  32449. var descendants = this.getDescendants();
  32450. descendants.push(this);
  32451. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32452. var particleSystem = this.getScene().particleSystems[index];
  32453. var emitter = particleSystem.emitter;
  32454. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32455. results.push(particleSystem);
  32456. }
  32457. }
  32458. return results;
  32459. };
  32460. /**
  32461. * Normalize matrix weights so that all vertices have a total weight set to 1
  32462. */
  32463. Mesh.prototype.cleanMatrixWeights = function () {
  32464. var epsilon = 1e-3;
  32465. var noInfluenceBoneIndex = 0.0;
  32466. if (this.skeleton) {
  32467. noInfluenceBoneIndex = this.skeleton.bones.length;
  32468. }
  32469. else {
  32470. return;
  32471. }
  32472. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32473. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32474. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32475. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32476. var influencers = this.numBoneInfluencers;
  32477. var size = matricesWeights.length;
  32478. for (var i = 0; i < size; i += 4) {
  32479. var weight = 0.0;
  32480. var firstZeroWeight = -1;
  32481. for (var j = 0; j < 4; j++) {
  32482. var w = matricesWeights[i + j];
  32483. weight += w;
  32484. if (w < epsilon && firstZeroWeight < 0) {
  32485. firstZeroWeight = j;
  32486. }
  32487. }
  32488. if (matricesWeightsExtra) {
  32489. for (var j = 0; j < 4; j++) {
  32490. var w = matricesWeightsExtra[i + j];
  32491. weight += w;
  32492. if (w < epsilon && firstZeroWeight < 0) {
  32493. firstZeroWeight = j + 4;
  32494. }
  32495. }
  32496. }
  32497. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32498. firstZeroWeight = influencers - 1;
  32499. }
  32500. if (weight > epsilon) {
  32501. var mweight = 1.0 / weight;
  32502. for (var j = 0; j < 4; j++) {
  32503. matricesWeights[i + j] *= mweight;
  32504. }
  32505. if (matricesWeightsExtra) {
  32506. for (var j = 0; j < 4; j++) {
  32507. matricesWeightsExtra[i + j] *= mweight;
  32508. }
  32509. }
  32510. }
  32511. else {
  32512. if (firstZeroWeight >= 4) {
  32513. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32514. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32515. }
  32516. else {
  32517. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32518. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32519. }
  32520. }
  32521. }
  32522. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32523. if (matricesIndicesExtra) {
  32524. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32525. }
  32526. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32527. if (matricesWeightsExtra) {
  32528. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32529. }
  32530. };
  32531. /** @hidden */
  32532. Mesh.prototype._checkDelayState = function () {
  32533. var scene = this.getScene();
  32534. if (this._geometry) {
  32535. this._geometry.load(scene);
  32536. }
  32537. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32538. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32539. this._queueLoad(scene);
  32540. }
  32541. return this;
  32542. };
  32543. Mesh.prototype._queueLoad = function (scene) {
  32544. var _this = this;
  32545. scene._addPendingData(this);
  32546. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32547. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32548. if (data instanceof ArrayBuffer) {
  32549. _this._delayLoadingFunction(data, _this);
  32550. }
  32551. else {
  32552. _this._delayLoadingFunction(JSON.parse(data), _this);
  32553. }
  32554. _this.instances.forEach(function (instance) {
  32555. instance._syncSubMeshes();
  32556. });
  32557. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32558. scene._removePendingData(_this);
  32559. }, function () { }, scene.database, getBinaryData);
  32560. return this;
  32561. };
  32562. /**
  32563. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32564. * A mesh is in the frustum if its bounding box intersects the frustum
  32565. * @param frustumPlanes defines the frustum to test
  32566. * @returns true if the mesh is in the frustum planes
  32567. */
  32568. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32569. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32570. return false;
  32571. }
  32572. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32573. return false;
  32574. }
  32575. this._checkDelayState();
  32576. return true;
  32577. };
  32578. /**
  32579. * Sets the mesh material by the material or multiMaterial `id` property.
  32580. * The material `id` is a string identifying the material or the multiMaterial.
  32581. * This method returns the Mesh.
  32582. */
  32583. Mesh.prototype.setMaterialByID = function (id) {
  32584. var materials = this.getScene().materials;
  32585. var index;
  32586. for (index = materials.length - 1; index > -1; index--) {
  32587. if (materials[index].id === id) {
  32588. this.material = materials[index];
  32589. return this;
  32590. }
  32591. }
  32592. // Multi
  32593. var multiMaterials = this.getScene().multiMaterials;
  32594. for (index = multiMaterials.length - 1; index > -1; index--) {
  32595. if (multiMaterials[index].id === id) {
  32596. this.material = multiMaterials[index];
  32597. return this;
  32598. }
  32599. }
  32600. return this;
  32601. };
  32602. /**
  32603. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32604. */
  32605. Mesh.prototype.getAnimatables = function () {
  32606. var results = new Array();
  32607. if (this.material) {
  32608. results.push(this.material);
  32609. }
  32610. if (this.skeleton) {
  32611. results.push(this.skeleton);
  32612. }
  32613. return results;
  32614. };
  32615. /**
  32616. * Modifies the mesh geometry according to the passed transformation matrix.
  32617. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32618. * The mesh normals are modified using the same transformation.
  32619. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32620. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32621. * Returns the Mesh.
  32622. */
  32623. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32624. // Position
  32625. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32626. return this;
  32627. }
  32628. var submeshes = this.subMeshes.splice(0);
  32629. this._resetPointsArrayCache();
  32630. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32631. var temp = new Array();
  32632. var index;
  32633. for (index = 0; index < data.length; index += 3) {
  32634. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32635. }
  32636. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32637. // Normals
  32638. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32639. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32640. temp = [];
  32641. for (index = 0; index < data.length; index += 3) {
  32642. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32643. }
  32644. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32645. }
  32646. // flip faces?
  32647. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32648. this.flipFaces();
  32649. }
  32650. // Restore submeshes
  32651. this.releaseSubMeshes();
  32652. this.subMeshes = submeshes;
  32653. return this;
  32654. };
  32655. /**
  32656. * Modifies the mesh geometry according to its own current World Matrix.
  32657. * The mesh World Matrix is then reset.
  32658. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32659. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32660. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32661. * Returns the Mesh.
  32662. */
  32663. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32664. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32665. this.scaling.copyFromFloats(1, 1, 1);
  32666. this.position.copyFromFloats(0, 0, 0);
  32667. this.rotation.copyFromFloats(0, 0, 0);
  32668. //only if quaternion is already set
  32669. if (this.rotationQuaternion) {
  32670. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32671. }
  32672. this._worldMatrix = BABYLON.Matrix.Identity();
  32673. return this;
  32674. };
  32675. Object.defineProperty(Mesh.prototype, "_positions", {
  32676. // Cache
  32677. get: function () {
  32678. if (this._geometry) {
  32679. return this._geometry._positions;
  32680. }
  32681. return null;
  32682. },
  32683. enumerable: true,
  32684. configurable: true
  32685. });
  32686. /** @hidden */
  32687. Mesh.prototype._resetPointsArrayCache = function () {
  32688. if (this._geometry) {
  32689. this._geometry._resetPointsArrayCache();
  32690. }
  32691. return this;
  32692. };
  32693. /** @hidden */
  32694. Mesh.prototype._generatePointsArray = function () {
  32695. if (this._geometry) {
  32696. return this._geometry._generatePointsArray();
  32697. }
  32698. return false;
  32699. };
  32700. /**
  32701. * Returns a new Mesh object generated from the current mesh properties.
  32702. * This method must not get confused with createInstance().
  32703. * The parameter `name` is a string, the name given to the new mesh.
  32704. * The optional parameter `newParent` can be any Node object (default `null`).
  32705. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32706. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32707. */
  32708. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32709. if (name === void 0) { name = ""; }
  32710. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32711. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32712. };
  32713. /**
  32714. * Releases resources associated with this mesh.
  32715. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32716. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32717. */
  32718. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32719. var _this = this;
  32720. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32721. this.morphTargetManager = null;
  32722. if (this._geometry) {
  32723. this._geometry.releaseForMesh(this, true);
  32724. }
  32725. if (this._onBeforeDrawObservable) {
  32726. this._onBeforeDrawObservable.clear();
  32727. }
  32728. if (this._onBeforeRenderObservable) {
  32729. this._onBeforeRenderObservable.clear();
  32730. }
  32731. if (this._onAfterRenderObservable) {
  32732. this._onAfterRenderObservable.clear();
  32733. }
  32734. // Sources
  32735. var meshes = this.getScene().meshes;
  32736. meshes.forEach(function (abstractMesh) {
  32737. var mesh = abstractMesh;
  32738. if (mesh._source && mesh._source === _this) {
  32739. mesh._source = null;
  32740. }
  32741. });
  32742. this._source = null;
  32743. // Instances
  32744. if (this._instancesBuffer) {
  32745. this._instancesBuffer.dispose();
  32746. this._instancesBuffer = null;
  32747. }
  32748. while (this.instances.length) {
  32749. this.instances[0].dispose();
  32750. }
  32751. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32752. };
  32753. /**
  32754. * Modifies the mesh geometry according to a displacement map.
  32755. * 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.
  32756. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32757. * This method returns nothing.
  32758. * @param url is a string, the URL from the image file is to be downloaded.
  32759. * @param minHeight is the lower limit of the displacement.
  32760. * @param maxHeight is the upper limit of the displacement.
  32761. * @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.
  32762. * @param uvOffset is an optional vector2 used to offset UV.
  32763. * @param uvScale is an optional vector2 used to scale UV.
  32764. * @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.
  32765. * @returns the Mesh.
  32766. */
  32767. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32768. var _this = this;
  32769. if (forceUpdate === void 0) { forceUpdate = false; }
  32770. var scene = this.getScene();
  32771. var onload = function (img) {
  32772. // Getting height map data
  32773. var canvas = document.createElement("canvas");
  32774. var context = canvas.getContext("2d");
  32775. var heightMapWidth = img.width;
  32776. var heightMapHeight = img.height;
  32777. canvas.width = heightMapWidth;
  32778. canvas.height = heightMapHeight;
  32779. context.drawImage(img, 0, 0);
  32780. // Create VertexData from map data
  32781. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32782. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32783. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32784. //execute success callback, if set
  32785. if (onSuccess) {
  32786. onSuccess(_this);
  32787. }
  32788. };
  32789. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32790. return this;
  32791. };
  32792. /**
  32793. * Modifies the mesh geometry according to a displacementMap buffer.
  32794. * 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.
  32795. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32796. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32797. * @param heightMapWidth is the width of the buffer image.
  32798. * @param heightMapHeight is the height of the buffer image.
  32799. * @param minHeight is the lower limit of the displacement.
  32800. * @param maxHeight is the upper limit of the displacement.
  32801. * @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.
  32802. * @param uvOffset is an optional vector2 used to offset UV.
  32803. * @param uvScale is an optional vector2 used to scale UV.
  32804. * @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.
  32805. * @returns the Mesh.
  32806. */
  32807. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32808. if (forceUpdate === void 0) { forceUpdate = false; }
  32809. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32810. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32811. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32812. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32813. return this;
  32814. }
  32815. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32816. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32817. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32818. var position = BABYLON.Vector3.Zero();
  32819. var normal = BABYLON.Vector3.Zero();
  32820. var uv = BABYLON.Vector2.Zero();
  32821. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32822. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32823. for (var index = 0; index < positions.length; index += 3) {
  32824. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32825. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32826. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32827. // Compute height
  32828. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32829. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32830. var pos = (u + v * heightMapWidth) * 4;
  32831. var r = buffer[pos] / 255.0;
  32832. var g = buffer[pos + 1] / 255.0;
  32833. var b = buffer[pos + 2] / 255.0;
  32834. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32835. normal.normalize();
  32836. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32837. position = position.add(normal);
  32838. position.toArray(positions, index);
  32839. }
  32840. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32841. if (forceUpdate) {
  32842. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32843. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32844. }
  32845. else {
  32846. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32847. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32848. }
  32849. return this;
  32850. };
  32851. /**
  32852. * Modify the mesh to get a flat shading rendering.
  32853. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32854. * This method returns the Mesh.
  32855. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32856. */
  32857. Mesh.prototype.convertToFlatShadedMesh = function () {
  32858. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32859. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32860. var kinds = this.getVerticesDataKinds();
  32861. var vbs = {};
  32862. var data = {};
  32863. var newdata = {};
  32864. var updatableNormals = false;
  32865. var kindIndex;
  32866. var kind;
  32867. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32868. kind = kinds[kindIndex];
  32869. var vertexBuffer = this.getVertexBuffer(kind);
  32870. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32871. updatableNormals = vertexBuffer.isUpdatable();
  32872. kinds.splice(kindIndex, 1);
  32873. kindIndex--;
  32874. continue;
  32875. }
  32876. vbs[kind] = vertexBuffer;
  32877. data[kind] = vbs[kind].getData();
  32878. newdata[kind] = [];
  32879. }
  32880. // Save previous submeshes
  32881. var previousSubmeshes = this.subMeshes.slice(0);
  32882. var indices = this.getIndices();
  32883. var totalIndices = this.getTotalIndices();
  32884. // Generating unique vertices per face
  32885. var index;
  32886. for (index = 0; index < totalIndices; index++) {
  32887. var vertexIndex = indices[index];
  32888. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32889. kind = kinds[kindIndex];
  32890. var stride = vbs[kind].getStrideSize();
  32891. for (var offset = 0; offset < stride; offset++) {
  32892. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32893. }
  32894. }
  32895. }
  32896. // Updating faces & normal
  32897. var normals = [];
  32898. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32899. for (index = 0; index < totalIndices; index += 3) {
  32900. indices[index] = index;
  32901. indices[index + 1] = index + 1;
  32902. indices[index + 2] = index + 2;
  32903. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32904. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32905. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32906. var p1p2 = p1.subtract(p2);
  32907. var p3p2 = p3.subtract(p2);
  32908. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32909. // Store same normals for every vertex
  32910. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32911. normals.push(normal.x);
  32912. normals.push(normal.y);
  32913. normals.push(normal.z);
  32914. }
  32915. }
  32916. this.setIndices(indices);
  32917. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32918. // Updating vertex buffers
  32919. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32920. kind = kinds[kindIndex];
  32921. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32922. }
  32923. // Updating submeshes
  32924. this.releaseSubMeshes();
  32925. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32926. var previousOne = previousSubmeshes[submeshIndex];
  32927. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32928. }
  32929. this.synchronizeInstances();
  32930. return this;
  32931. };
  32932. /**
  32933. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32934. * In other words, more vertices, no more indices and a single bigger VBO.
  32935. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32936. * Returns the Mesh.
  32937. */
  32938. Mesh.prototype.convertToUnIndexedMesh = function () {
  32939. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32940. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32941. var kinds = this.getVerticesDataKinds();
  32942. var vbs = {};
  32943. var data = {};
  32944. var newdata = {};
  32945. var kindIndex;
  32946. var kind;
  32947. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32948. kind = kinds[kindIndex];
  32949. var vertexBuffer = this.getVertexBuffer(kind);
  32950. vbs[kind] = vertexBuffer;
  32951. data[kind] = vbs[kind].getData();
  32952. newdata[kind] = [];
  32953. }
  32954. // Save previous submeshes
  32955. var previousSubmeshes = this.subMeshes.slice(0);
  32956. var indices = this.getIndices();
  32957. var totalIndices = this.getTotalIndices();
  32958. // Generating unique vertices per face
  32959. var index;
  32960. for (index = 0; index < totalIndices; index++) {
  32961. var vertexIndex = indices[index];
  32962. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32963. kind = kinds[kindIndex];
  32964. var stride = vbs[kind].getStrideSize();
  32965. for (var offset = 0; offset < stride; offset++) {
  32966. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32967. }
  32968. }
  32969. }
  32970. // Updating indices
  32971. for (index = 0; index < totalIndices; index += 3) {
  32972. indices[index] = index;
  32973. indices[index + 1] = index + 1;
  32974. indices[index + 2] = index + 2;
  32975. }
  32976. this.setIndices(indices);
  32977. // Updating vertex buffers
  32978. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32979. kind = kinds[kindIndex];
  32980. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32981. }
  32982. // Updating submeshes
  32983. this.releaseSubMeshes();
  32984. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32985. var previousOne = previousSubmeshes[submeshIndex];
  32986. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32987. }
  32988. this._unIndexed = true;
  32989. this.synchronizeInstances();
  32990. return this;
  32991. };
  32992. /**
  32993. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32994. * This method returns the Mesh.
  32995. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32996. */
  32997. Mesh.prototype.flipFaces = function (flipNormals) {
  32998. if (flipNormals === void 0) { flipNormals = false; }
  32999. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33000. var i;
  33001. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33002. for (i = 0; i < vertex_data.normals.length; i++) {
  33003. vertex_data.normals[i] *= -1;
  33004. }
  33005. }
  33006. if (vertex_data.indices) {
  33007. var temp;
  33008. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33009. // reassign indices
  33010. temp = vertex_data.indices[i + 1];
  33011. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33012. vertex_data.indices[i + 2] = temp;
  33013. }
  33014. }
  33015. vertex_data.applyToMesh(this);
  33016. return this;
  33017. };
  33018. // Instances
  33019. /**
  33020. * Creates a new InstancedMesh object from the mesh model.
  33021. * An instance shares the same properties and the same material than its model.
  33022. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  33023. * Only these properties of each instance can then be set individually :
  33024. * - position
  33025. * - rotation
  33026. * - rotationQuaternion
  33027. * - setPivotMatrix
  33028. * - scaling
  33029. *
  33030. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33031. * Warning : this method is not supported for Line mesh and LineSystem
  33032. */
  33033. Mesh.prototype.createInstance = function (name) {
  33034. return new BABYLON.InstancedMesh(name, this);
  33035. };
  33036. /**
  33037. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33038. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33039. * This method returns the Mesh.
  33040. */
  33041. Mesh.prototype.synchronizeInstances = function () {
  33042. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33043. var instance = this.instances[instanceIndex];
  33044. instance._syncSubMeshes();
  33045. }
  33046. return this;
  33047. };
  33048. /**
  33049. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33050. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33051. * This should be used together with the simplification to avoid disappearing triangles.
  33052. * Returns the Mesh.
  33053. * @param successCallback an optional success callback to be called after the optimization finished.
  33054. */
  33055. Mesh.prototype.optimizeIndices = function (successCallback) {
  33056. var _this = this;
  33057. var indices = this.getIndices();
  33058. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33059. if (!positions || !indices) {
  33060. return this;
  33061. }
  33062. var vectorPositions = new Array();
  33063. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33064. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33065. }
  33066. var dupes = new Array();
  33067. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33068. var realPos = vectorPositions.length - 1 - iteration;
  33069. var testedPosition = vectorPositions[realPos];
  33070. for (var j = 0; j < realPos; ++j) {
  33071. var againstPosition = vectorPositions[j];
  33072. if (testedPosition.equals(againstPosition)) {
  33073. dupes[realPos] = j;
  33074. break;
  33075. }
  33076. }
  33077. }, function () {
  33078. for (var i = 0; i < indices.length; ++i) {
  33079. indices[i] = dupes[indices[i]] || indices[i];
  33080. }
  33081. //indices are now reordered
  33082. var originalSubMeshes = _this.subMeshes.slice(0);
  33083. _this.setIndices(indices);
  33084. _this.subMeshes = originalSubMeshes;
  33085. if (successCallback) {
  33086. successCallback(_this);
  33087. }
  33088. });
  33089. return this;
  33090. };
  33091. Mesh.prototype.serialize = function (serializationObject) {
  33092. serializationObject.name = this.name;
  33093. serializationObject.id = this.id;
  33094. serializationObject.type = this.getClassName();
  33095. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33096. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33097. }
  33098. serializationObject.position = this.position.asArray();
  33099. if (this.rotationQuaternion) {
  33100. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33101. }
  33102. else if (this.rotation) {
  33103. serializationObject.rotation = this.rotation.asArray();
  33104. }
  33105. serializationObject.scaling = this.scaling.asArray();
  33106. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33107. serializationObject.isEnabled = this.isEnabled(false);
  33108. serializationObject.isVisible = this.isVisible;
  33109. serializationObject.infiniteDistance = this.infiniteDistance;
  33110. serializationObject.pickable = this.isPickable;
  33111. serializationObject.receiveShadows = this.receiveShadows;
  33112. serializationObject.billboardMode = this.billboardMode;
  33113. serializationObject.visibility = this.visibility;
  33114. serializationObject.checkCollisions = this.checkCollisions;
  33115. serializationObject.isBlocker = this.isBlocker;
  33116. // Parent
  33117. if (this.parent) {
  33118. serializationObject.parentId = this.parent.id;
  33119. }
  33120. // Geometry
  33121. serializationObject.isUnIndexed = this.isUnIndexed;
  33122. var geometry = this._geometry;
  33123. if (geometry) {
  33124. var geometryId = geometry.id;
  33125. serializationObject.geometryId = geometryId;
  33126. // SubMeshes
  33127. serializationObject.subMeshes = [];
  33128. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33129. var subMesh = this.subMeshes[subIndex];
  33130. serializationObject.subMeshes.push({
  33131. materialIndex: subMesh.materialIndex,
  33132. verticesStart: subMesh.verticesStart,
  33133. verticesCount: subMesh.verticesCount,
  33134. indexStart: subMesh.indexStart,
  33135. indexCount: subMesh.indexCount
  33136. });
  33137. }
  33138. }
  33139. // Material
  33140. if (this.material) {
  33141. serializationObject.materialId = this.material.id;
  33142. }
  33143. else {
  33144. this.material = null;
  33145. }
  33146. // Morph targets
  33147. if (this.morphTargetManager) {
  33148. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33149. }
  33150. // Skeleton
  33151. if (this.skeleton) {
  33152. serializationObject.skeletonId = this.skeleton.id;
  33153. }
  33154. // Physics
  33155. //TODO implement correct serialization for physics impostors.
  33156. var impostor = this.getPhysicsImpostor();
  33157. if (impostor) {
  33158. serializationObject.physicsMass = impostor.getParam("mass");
  33159. serializationObject.physicsFriction = impostor.getParam("friction");
  33160. serializationObject.physicsRestitution = impostor.getParam("mass");
  33161. serializationObject.physicsImpostor = impostor.type;
  33162. }
  33163. // Metadata
  33164. if (this.metadata) {
  33165. serializationObject.metadata = this.metadata;
  33166. }
  33167. // Instances
  33168. serializationObject.instances = [];
  33169. for (var index = 0; index < this.instances.length; index++) {
  33170. var instance = this.instances[index];
  33171. var serializationInstance = {
  33172. name: instance.name,
  33173. id: instance.id,
  33174. position: instance.position.asArray(),
  33175. scaling: instance.scaling.asArray()
  33176. };
  33177. if (instance.parent) {
  33178. serializationInstance.parentId = instance.parent.id;
  33179. }
  33180. if (instance.rotationQuaternion) {
  33181. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33182. }
  33183. else if (instance.rotation) {
  33184. serializationInstance.rotation = instance.rotation.asArray();
  33185. }
  33186. serializationObject.instances.push(serializationInstance);
  33187. // Animations
  33188. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33189. serializationInstance.ranges = instance.serializeAnimationRanges();
  33190. }
  33191. //
  33192. // Animations
  33193. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33194. serializationObject.ranges = this.serializeAnimationRanges();
  33195. // Layer mask
  33196. serializationObject.layerMask = this.layerMask;
  33197. // Alpha
  33198. serializationObject.alphaIndex = this.alphaIndex;
  33199. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33200. // Overlay
  33201. serializationObject.overlayAlpha = this.overlayAlpha;
  33202. serializationObject.overlayColor = this.overlayColor.asArray();
  33203. serializationObject.renderOverlay = this.renderOverlay;
  33204. // Fog
  33205. serializationObject.applyFog = this.applyFog;
  33206. // Action Manager
  33207. if (this.actionManager) {
  33208. serializationObject.actions = this.actionManager.serialize(this.name);
  33209. }
  33210. };
  33211. /** @hidden */
  33212. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33213. if (!this.geometry) {
  33214. return;
  33215. }
  33216. this._markSubMeshesAsAttributesDirty();
  33217. var morphTargetManager = this._morphTargetManager;
  33218. if (morphTargetManager && morphTargetManager.vertexCount) {
  33219. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33220. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33221. this.morphTargetManager = null;
  33222. return;
  33223. }
  33224. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33225. var morphTarget = morphTargetManager.getActiveTarget(index);
  33226. var positions = morphTarget.getPositions();
  33227. if (!positions) {
  33228. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33229. return;
  33230. }
  33231. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33232. var normals = morphTarget.getNormals();
  33233. if (normals) {
  33234. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33235. }
  33236. var tangents = morphTarget.getTangents();
  33237. if (tangents) {
  33238. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33239. }
  33240. }
  33241. }
  33242. else {
  33243. var index = 0;
  33244. // Positions
  33245. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33246. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33247. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33248. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33249. }
  33250. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33251. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33252. }
  33253. index++;
  33254. }
  33255. }
  33256. };
  33257. // Statics
  33258. /**
  33259. * Returns a new Mesh object parsed from the source provided.
  33260. * The parameter `parsedMesh` is the source.
  33261. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33262. */
  33263. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33264. var mesh;
  33265. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33266. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33267. }
  33268. else {
  33269. mesh = new Mesh(parsedMesh.name, scene);
  33270. }
  33271. mesh.id = parsedMesh.id;
  33272. if (BABYLON.Tags) {
  33273. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33274. }
  33275. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33276. if (parsedMesh.metadata !== undefined) {
  33277. mesh.metadata = parsedMesh.metadata;
  33278. }
  33279. if (parsedMesh.rotationQuaternion) {
  33280. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33281. }
  33282. else if (parsedMesh.rotation) {
  33283. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33284. }
  33285. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33286. if (parsedMesh.localMatrix) {
  33287. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33288. }
  33289. else if (parsedMesh.pivotMatrix) {
  33290. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33291. }
  33292. mesh.setEnabled(parsedMesh.isEnabled);
  33293. mesh.isVisible = parsedMesh.isVisible;
  33294. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33295. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33296. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33297. if (parsedMesh.applyFog !== undefined) {
  33298. mesh.applyFog = parsedMesh.applyFog;
  33299. }
  33300. if (parsedMesh.pickable !== undefined) {
  33301. mesh.isPickable = parsedMesh.pickable;
  33302. }
  33303. if (parsedMesh.alphaIndex !== undefined) {
  33304. mesh.alphaIndex = parsedMesh.alphaIndex;
  33305. }
  33306. mesh.receiveShadows = parsedMesh.receiveShadows;
  33307. mesh.billboardMode = parsedMesh.billboardMode;
  33308. if (parsedMesh.visibility !== undefined) {
  33309. mesh.visibility = parsedMesh.visibility;
  33310. }
  33311. mesh.checkCollisions = parsedMesh.checkCollisions;
  33312. if (parsedMesh.isBlocker !== undefined) {
  33313. mesh.isBlocker = parsedMesh.isBlocker;
  33314. }
  33315. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33316. // freezeWorldMatrix
  33317. if (parsedMesh.freezeWorldMatrix) {
  33318. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33319. }
  33320. // Parent
  33321. if (parsedMesh.parentId) {
  33322. mesh._waitingParentId = parsedMesh.parentId;
  33323. }
  33324. // Actions
  33325. if (parsedMesh.actions !== undefined) {
  33326. mesh._waitingActions = parsedMesh.actions;
  33327. }
  33328. // Overlay
  33329. if (parsedMesh.overlayAlpha !== undefined) {
  33330. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33331. }
  33332. if (parsedMesh.overlayColor !== undefined) {
  33333. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33334. }
  33335. if (parsedMesh.renderOverlay !== undefined) {
  33336. mesh.renderOverlay = parsedMesh.renderOverlay;
  33337. }
  33338. // Geometry
  33339. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33340. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33341. if (parsedMesh.delayLoadingFile) {
  33342. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33343. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33344. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33345. if (parsedMesh._binaryInfo) {
  33346. mesh._binaryInfo = parsedMesh._binaryInfo;
  33347. }
  33348. mesh._delayInfo = [];
  33349. if (parsedMesh.hasUVs) {
  33350. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33351. }
  33352. if (parsedMesh.hasUVs2) {
  33353. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33354. }
  33355. if (parsedMesh.hasUVs3) {
  33356. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33357. }
  33358. if (parsedMesh.hasUVs4) {
  33359. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33360. }
  33361. if (parsedMesh.hasUVs5) {
  33362. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33363. }
  33364. if (parsedMesh.hasUVs6) {
  33365. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33366. }
  33367. if (parsedMesh.hasColors) {
  33368. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33369. }
  33370. if (parsedMesh.hasMatricesIndices) {
  33371. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33372. }
  33373. if (parsedMesh.hasMatricesWeights) {
  33374. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33375. }
  33376. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33377. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33378. mesh._checkDelayState();
  33379. }
  33380. }
  33381. else {
  33382. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33383. }
  33384. // Material
  33385. if (parsedMesh.materialId) {
  33386. mesh.setMaterialByID(parsedMesh.materialId);
  33387. }
  33388. else {
  33389. mesh.material = null;
  33390. }
  33391. // Morph targets
  33392. if (parsedMesh.morphTargetManagerId > -1) {
  33393. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33394. }
  33395. // Skeleton
  33396. if (parsedMesh.skeletonId > -1) {
  33397. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33398. if (parsedMesh.numBoneInfluencers) {
  33399. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33400. }
  33401. }
  33402. // Animations
  33403. if (parsedMesh.animations) {
  33404. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33405. var parsedAnimation = parsedMesh.animations[animationIndex];
  33406. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33407. }
  33408. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33409. }
  33410. if (parsedMesh.autoAnimate) {
  33411. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33412. }
  33413. // Layer Mask
  33414. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33415. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33416. }
  33417. else {
  33418. mesh.layerMask = 0x0FFFFFFF;
  33419. }
  33420. // Physics
  33421. if (parsedMesh.physicsImpostor) {
  33422. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33423. mass: parsedMesh.physicsMass,
  33424. friction: parsedMesh.physicsFriction,
  33425. restitution: parsedMesh.physicsRestitution
  33426. }, scene);
  33427. }
  33428. // Instances
  33429. if (parsedMesh.instances) {
  33430. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33431. var parsedInstance = parsedMesh.instances[index];
  33432. var instance = mesh.createInstance(parsedInstance.name);
  33433. if (parsedInstance.id) {
  33434. instance.id = parsedInstance.id;
  33435. }
  33436. if (BABYLON.Tags) {
  33437. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33438. }
  33439. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33440. if (parsedInstance.parentId) {
  33441. instance._waitingParentId = parsedInstance.parentId;
  33442. }
  33443. if (parsedInstance.rotationQuaternion) {
  33444. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33445. }
  33446. else if (parsedInstance.rotation) {
  33447. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33448. }
  33449. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33450. instance.checkCollisions = mesh.checkCollisions;
  33451. if (parsedMesh.animations) {
  33452. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33453. parsedAnimation = parsedMesh.animations[animationIndex];
  33454. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33455. }
  33456. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33457. if (parsedMesh.autoAnimate) {
  33458. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33459. }
  33460. }
  33461. }
  33462. }
  33463. return mesh;
  33464. };
  33465. /**
  33466. * Creates a ribbon mesh.
  33467. * Please consider using the same method from the MeshBuilder class instead.
  33468. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33469. *
  33470. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33471. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33472. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33473. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33474. * 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.
  33475. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  33476. * 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
  33477. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33478. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33479. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33480. */
  33481. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33482. if (closeArray === void 0) { closeArray = false; }
  33483. if (updatable === void 0) { updatable = false; }
  33484. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33485. pathArray: pathArray,
  33486. closeArray: closeArray,
  33487. closePath: closePath,
  33488. offset: offset,
  33489. updatable: updatable,
  33490. sideOrientation: sideOrientation,
  33491. instance: instance
  33492. }, scene);
  33493. };
  33494. /**
  33495. * Creates a plane polygonal mesh. By default, this is a disc.
  33496. * Please consider using the same method from the MeshBuilder class instead.
  33497. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33498. * 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.
  33499. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33500. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33501. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33502. */
  33503. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33504. if (scene === void 0) { scene = null; }
  33505. var options = {
  33506. radius: radius,
  33507. tessellation: tessellation,
  33508. sideOrientation: sideOrientation,
  33509. updatable: updatable
  33510. };
  33511. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33512. };
  33513. /**
  33514. * Creates a box mesh.
  33515. * Please consider using the same method from the MeshBuilder class instead.
  33516. * The parameter `size` sets the size (float) of each box side (default 1).
  33517. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33518. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33519. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33520. */
  33521. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33522. if (scene === void 0) { scene = null; }
  33523. var options = {
  33524. size: size,
  33525. sideOrientation: sideOrientation,
  33526. updatable: updatable
  33527. };
  33528. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33529. };
  33530. /**
  33531. * Creates a sphere mesh.
  33532. * Please consider using the same method from the MeshBuilder class instead.
  33533. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33534. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33535. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33536. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33537. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33538. */
  33539. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33540. var options = {
  33541. segments: segments,
  33542. diameterX: diameter,
  33543. diameterY: diameter,
  33544. diameterZ: diameter,
  33545. sideOrientation: sideOrientation,
  33546. updatable: updatable
  33547. };
  33548. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33549. };
  33550. /**
  33551. * Creates a cylinder or a cone mesh.
  33552. * Please consider using the same method from the MeshBuilder class instead.
  33553. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33554. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33555. * 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.
  33556. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33557. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33558. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33559. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33560. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33561. */
  33562. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33563. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33564. if (scene !== undefined) {
  33565. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33566. updatable = scene;
  33567. }
  33568. scene = subdivisions;
  33569. subdivisions = 1;
  33570. }
  33571. var options = {
  33572. height: height,
  33573. diameterTop: diameterTop,
  33574. diameterBottom: diameterBottom,
  33575. tessellation: tessellation,
  33576. subdivisions: subdivisions,
  33577. sideOrientation: sideOrientation,
  33578. updatable: updatable
  33579. };
  33580. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33581. };
  33582. // Torus (Code from SharpDX.org)
  33583. /**
  33584. * Creates a torus mesh.
  33585. * Please consider using the same method from the MeshBuilder class instead.
  33586. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33587. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33588. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33589. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33590. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33591. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33592. */
  33593. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33594. var options = {
  33595. diameter: diameter,
  33596. thickness: thickness,
  33597. tessellation: tessellation,
  33598. sideOrientation: sideOrientation,
  33599. updatable: updatable
  33600. };
  33601. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33602. };
  33603. /**
  33604. * Creates a torus knot mesh.
  33605. * Please consider using the same method from the MeshBuilder class instead.
  33606. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33607. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33608. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33609. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33610. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33611. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33612. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33613. */
  33614. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33615. var options = {
  33616. radius: radius,
  33617. tube: tube,
  33618. radialSegments: radialSegments,
  33619. tubularSegments: tubularSegments,
  33620. p: p,
  33621. q: q,
  33622. sideOrientation: sideOrientation,
  33623. updatable: updatable
  33624. };
  33625. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33626. };
  33627. /**
  33628. * Creates a line mesh.
  33629. * Please consider using the same method from the MeshBuilder class instead.
  33630. * 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.
  33631. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33632. * The parameter `points` is an array successive Vector3.
  33633. * 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
  33634. * When updating an instance, remember that only point positions can change, not the number of points.
  33635. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33636. */
  33637. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33638. if (scene === void 0) { scene = null; }
  33639. if (updatable === void 0) { updatable = false; }
  33640. if (instance === void 0) { instance = null; }
  33641. var options = {
  33642. points: points,
  33643. updatable: updatable,
  33644. instance: instance
  33645. };
  33646. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33647. };
  33648. /**
  33649. * Creates a dashed line mesh.
  33650. * Please consider using the same method from the MeshBuilder class instead.
  33651. * 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.
  33652. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33653. * The parameter `points` is an array successive Vector3.
  33654. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33655. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33656. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33657. * 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
  33658. * When updating an instance, remember that only point positions can change, not the number of points.
  33659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33660. */
  33661. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33662. if (scene === void 0) { scene = null; }
  33663. var options = {
  33664. points: points,
  33665. dashSize: dashSize,
  33666. gapSize: gapSize,
  33667. dashNb: dashNb,
  33668. updatable: updatable,
  33669. instance: instance
  33670. };
  33671. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33672. };
  33673. /**
  33674. * Creates a polygon mesh.
  33675. * Please consider using the same method from the MeshBuilder class instead.
  33676. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33677. * 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.
  33678. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33679. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33680. * Remember you can only change the shape positions, not their number when updating a polygon.
  33681. */
  33682. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33683. var options = {
  33684. shape: shape,
  33685. holes: holes,
  33686. updatable: updatable,
  33687. sideOrientation: sideOrientation
  33688. };
  33689. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33690. };
  33691. /**
  33692. * Creates an extruded polygon mesh, with depth in the Y direction.
  33693. * Please consider using the same method from the MeshBuilder class instead.
  33694. */
  33695. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33696. var options = {
  33697. shape: shape,
  33698. holes: holes,
  33699. depth: depth,
  33700. updatable: updatable,
  33701. sideOrientation: sideOrientation
  33702. };
  33703. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33704. };
  33705. /**
  33706. * Creates an extruded shape mesh.
  33707. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33708. * Please consider using the same method from the MeshBuilder class instead.
  33709. *
  33710. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33711. * 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
  33712. * extruded along the Z axis.
  33713. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33714. * 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.
  33715. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33716. * 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
  33717. * 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
  33718. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33719. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33720. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33721. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33722. */
  33723. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33724. if (scene === void 0) { scene = null; }
  33725. var options = {
  33726. shape: shape,
  33727. path: path,
  33728. scale: scale,
  33729. rotation: rotation,
  33730. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33731. sideOrientation: sideOrientation,
  33732. instance: instance,
  33733. updatable: updatable
  33734. };
  33735. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33736. };
  33737. /**
  33738. * Creates an custom extruded shape mesh.
  33739. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33740. * Please consider using the same method from the MeshBuilder class instead.
  33741. *
  33742. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33743. * 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
  33744. * extruded along the Z axis.
  33745. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33746. * 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
  33747. * and the distance of this point from the begining of the path :
  33748. * ```javascript
  33749. * var rotationFunction = function(i, distance) {
  33750. * // do things
  33751. * return rotationValue; }
  33752. * ```
  33753. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33754. * 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
  33755. * and the distance of this point from the begining of the path :
  33756. * ```javascript
  33757. * var scaleFunction = function(i, distance) {
  33758. * // do things
  33759. * return scaleValue;}
  33760. * ```
  33761. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33762. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33763. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33764. * 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
  33765. * 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
  33766. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33767. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33768. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33770. */
  33771. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33772. var options = {
  33773. shape: shape,
  33774. path: path,
  33775. scaleFunction: scaleFunction,
  33776. rotationFunction: rotationFunction,
  33777. ribbonCloseArray: ribbonCloseArray,
  33778. ribbonClosePath: ribbonClosePath,
  33779. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33780. sideOrientation: sideOrientation,
  33781. instance: instance,
  33782. updatable: updatable
  33783. };
  33784. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33785. };
  33786. /**
  33787. * Creates lathe mesh.
  33788. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33789. * Please consider using the same method from the MeshBuilder class instead.
  33790. * 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
  33791. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33792. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33793. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33794. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33795. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33796. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33797. */
  33798. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33799. var options = {
  33800. shape: shape,
  33801. radius: radius,
  33802. tessellation: tessellation,
  33803. sideOrientation: sideOrientation,
  33804. updatable: updatable
  33805. };
  33806. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33807. };
  33808. /**
  33809. * Creates a plane mesh.
  33810. * Please consider using the same method from the MeshBuilder class instead.
  33811. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33812. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33813. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33814. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33815. */
  33816. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33817. var options = {
  33818. size: size,
  33819. width: size,
  33820. height: size,
  33821. sideOrientation: sideOrientation,
  33822. updatable: updatable
  33823. };
  33824. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33825. };
  33826. /**
  33827. * Creates a ground mesh.
  33828. * Please consider using the same method from the MeshBuilder class instead.
  33829. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33830. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33831. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33832. */
  33833. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33834. var options = {
  33835. width: width,
  33836. height: height,
  33837. subdivisions: subdivisions,
  33838. updatable: updatable
  33839. };
  33840. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33841. };
  33842. /**
  33843. * Creates a tiled ground mesh.
  33844. * Please consider using the same method from the MeshBuilder class instead.
  33845. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33846. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33847. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33848. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33849. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33850. * numbers of subdivisions on the ground width and height of each tile.
  33851. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33852. */
  33853. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33854. var options = {
  33855. xmin: xmin,
  33856. zmin: zmin,
  33857. xmax: xmax,
  33858. zmax: zmax,
  33859. subdivisions: subdivisions,
  33860. precision: precision,
  33861. updatable: updatable
  33862. };
  33863. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33864. };
  33865. /**
  33866. * Creates a ground mesh from a height map.
  33867. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33868. * Please consider using the same method from the MeshBuilder class instead.
  33869. * The parameter `url` sets the URL of the height map image resource.
  33870. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33871. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33872. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33873. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33874. * 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).
  33875. * This function is passed the newly built mesh :
  33876. * ```javascript
  33877. * function(mesh) { // do things
  33878. * return; }
  33879. * ```
  33880. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33881. */
  33882. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33883. var options = {
  33884. width: width,
  33885. height: height,
  33886. subdivisions: subdivisions,
  33887. minHeight: minHeight,
  33888. maxHeight: maxHeight,
  33889. updatable: updatable,
  33890. onReady: onReady
  33891. };
  33892. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33893. };
  33894. /**
  33895. * Creates a tube mesh.
  33896. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33897. * Please consider using the same method from the MeshBuilder class instead.
  33898. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33899. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33900. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33901. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33902. * 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.
  33903. * It must return a radius value (positive float) :
  33904. * ```javascript
  33905. * var radiusFunction = function(i, distance) {
  33906. * // do things
  33907. * return radius; }
  33908. * ```
  33909. * 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
  33910. * 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
  33911. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33912. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33913. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33914. */
  33915. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33916. var options = {
  33917. path: path,
  33918. radius: radius,
  33919. tessellation: tessellation,
  33920. radiusFunction: radiusFunction,
  33921. arc: 1,
  33922. cap: cap,
  33923. updatable: updatable,
  33924. sideOrientation: sideOrientation,
  33925. instance: instance
  33926. };
  33927. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33928. };
  33929. /**
  33930. * Creates a polyhedron mesh.
  33931. * Please consider using the same method from the MeshBuilder class instead.
  33932. * 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
  33933. * to choose the wanted type.
  33934. * The parameter `size` (positive float, default 1) sets the polygon size.
  33935. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33936. * 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`.
  33937. * 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
  33938. * 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)`).
  33939. * 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
  33940. * 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.
  33941. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33942. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33944. */
  33945. Mesh.CreatePolyhedron = function (name, options, scene) {
  33946. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33947. };
  33948. /**
  33949. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33950. * Please consider using the same method from the MeshBuilder class instead.
  33951. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33952. * 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`).
  33953. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33954. * 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.
  33955. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33956. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33957. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33958. */
  33959. Mesh.CreateIcoSphere = function (name, options, scene) {
  33960. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33961. };
  33962. /**
  33963. * Creates a decal mesh.
  33964. * Please consider using the same method from the MeshBuilder class instead.
  33965. * 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.
  33966. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33967. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33968. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33969. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33970. */
  33971. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33972. var options = {
  33973. position: position,
  33974. normal: normal,
  33975. size: size,
  33976. angle: angle
  33977. };
  33978. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33979. };
  33980. // Skeletons
  33981. /**
  33982. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33983. */
  33984. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33985. if (!this._sourcePositions) {
  33986. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33987. if (!source) {
  33988. return this._sourcePositions;
  33989. }
  33990. this._sourcePositions = new Float32Array(source);
  33991. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33992. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33993. }
  33994. }
  33995. return this._sourcePositions;
  33996. };
  33997. /**
  33998. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33999. */
  34000. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34001. if (!this._sourceNormals) {
  34002. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34003. if (!source) {
  34004. return this._sourceNormals;
  34005. }
  34006. this._sourceNormals = new Float32Array(source);
  34007. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34008. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34009. }
  34010. }
  34011. return this._sourceNormals;
  34012. };
  34013. /**
  34014. * Updates the vertex buffer by applying transformation from the bones.
  34015. * Returns the Mesh.
  34016. *
  34017. * @param {skeleton} skeleton to apply
  34018. */
  34019. Mesh.prototype.applySkeleton = function (skeleton) {
  34020. if (!this.geometry) {
  34021. return this;
  34022. }
  34023. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34024. return this;
  34025. }
  34026. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34027. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34028. return this;
  34029. }
  34030. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34031. return this;
  34032. }
  34033. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34034. return this;
  34035. }
  34036. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34037. return this;
  34038. }
  34039. if (!this._sourcePositions) {
  34040. var submeshes = this.subMeshes.slice();
  34041. this.setPositionsForCPUSkinning();
  34042. this.subMeshes = submeshes;
  34043. }
  34044. if (!this._sourceNormals) {
  34045. this.setNormalsForCPUSkinning();
  34046. }
  34047. // positionsData checks for not being Float32Array will only pass at most once
  34048. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34049. if (!positionsData) {
  34050. return this;
  34051. }
  34052. if (!(positionsData instanceof Float32Array)) {
  34053. positionsData = new Float32Array(positionsData);
  34054. }
  34055. // normalsData checks for not being Float32Array will only pass at most once
  34056. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34057. if (!normalsData) {
  34058. return this;
  34059. }
  34060. if (!(normalsData instanceof Float32Array)) {
  34061. normalsData = new Float32Array(normalsData);
  34062. }
  34063. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34064. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34065. if (!matricesWeightsData || !matricesIndicesData) {
  34066. return this;
  34067. }
  34068. var needExtras = this.numBoneInfluencers > 4;
  34069. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34070. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34071. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34072. var tempVector3 = BABYLON.Vector3.Zero();
  34073. var finalMatrix = new BABYLON.Matrix();
  34074. var tempMatrix = new BABYLON.Matrix();
  34075. var matWeightIdx = 0;
  34076. var inf;
  34077. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34078. var weight;
  34079. for (inf = 0; inf < 4; inf++) {
  34080. weight = matricesWeightsData[matWeightIdx + inf];
  34081. if (weight > 0) {
  34082. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34083. finalMatrix.addToSelf(tempMatrix);
  34084. }
  34085. }
  34086. if (needExtras) {
  34087. for (inf = 0; inf < 4; inf++) {
  34088. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34089. if (weight > 0) {
  34090. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34091. finalMatrix.addToSelf(tempMatrix);
  34092. }
  34093. }
  34094. }
  34095. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34096. tempVector3.toArray(positionsData, index);
  34097. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34098. tempVector3.toArray(normalsData, index);
  34099. finalMatrix.reset();
  34100. }
  34101. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34102. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34103. return this;
  34104. };
  34105. // Tools
  34106. /**
  34107. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34108. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34109. */
  34110. Mesh.MinMax = function (meshes) {
  34111. var minVector = null;
  34112. var maxVector = null;
  34113. meshes.forEach(function (mesh, index, array) {
  34114. var boundingInfo = mesh.getBoundingInfo();
  34115. var boundingBox = boundingInfo.boundingBox;
  34116. if (!minVector || !maxVector) {
  34117. minVector = boundingBox.minimumWorld;
  34118. maxVector = boundingBox.maximumWorld;
  34119. }
  34120. else {
  34121. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34122. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34123. }
  34124. });
  34125. if (!minVector || !maxVector) {
  34126. return {
  34127. min: BABYLON.Vector3.Zero(),
  34128. max: BABYLON.Vector3.Zero()
  34129. };
  34130. }
  34131. return {
  34132. min: minVector,
  34133. max: maxVector
  34134. };
  34135. };
  34136. /**
  34137. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34138. */
  34139. Mesh.Center = function (meshesOrMinMaxVector) {
  34140. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34141. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34142. };
  34143. /**
  34144. * Merge the array of meshes into a single mesh for performance reasons.
  34145. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  34146. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  34147. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34148. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34149. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34150. */
  34151. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34152. if (disposeSource === void 0) { disposeSource = true; }
  34153. var index;
  34154. if (!allow32BitsIndices) {
  34155. var totalVertices = 0;
  34156. // Counting vertices
  34157. for (index = 0; index < meshes.length; index++) {
  34158. if (meshes[index]) {
  34159. totalVertices += meshes[index].getTotalVertices();
  34160. if (totalVertices > 65536) {
  34161. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34162. return null;
  34163. }
  34164. }
  34165. }
  34166. }
  34167. // Merge
  34168. var vertexData = null;
  34169. var otherVertexData;
  34170. var indiceArray = new Array();
  34171. var source = null;
  34172. for (index = 0; index < meshes.length; index++) {
  34173. if (meshes[index]) {
  34174. var wm = meshes[index].computeWorldMatrix(true);
  34175. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34176. otherVertexData.transform(wm);
  34177. if (vertexData) {
  34178. vertexData.merge(otherVertexData, allow32BitsIndices);
  34179. }
  34180. else {
  34181. vertexData = otherVertexData;
  34182. source = meshes[index];
  34183. }
  34184. if (subdivideWithSubMeshes) {
  34185. indiceArray.push(meshes[index].getTotalIndices());
  34186. }
  34187. }
  34188. }
  34189. source = source;
  34190. if (!meshSubclass) {
  34191. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34192. }
  34193. vertexData.applyToMesh(meshSubclass);
  34194. // Setting properties
  34195. meshSubclass.material = source.material;
  34196. meshSubclass.checkCollisions = source.checkCollisions;
  34197. // Cleaning
  34198. if (disposeSource) {
  34199. for (index = 0; index < meshes.length; index++) {
  34200. if (meshes[index]) {
  34201. meshes[index].dispose();
  34202. }
  34203. }
  34204. }
  34205. // Subdivide
  34206. if (subdivideWithSubMeshes) {
  34207. //-- removal of global submesh
  34208. meshSubclass.releaseSubMeshes();
  34209. index = 0;
  34210. var offset = 0;
  34211. //-- apply subdivision according to index table
  34212. while (index < indiceArray.length) {
  34213. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34214. offset += indiceArray[index];
  34215. index++;
  34216. }
  34217. }
  34218. return meshSubclass;
  34219. };
  34220. // Consts
  34221. Mesh._FRONTSIDE = 0;
  34222. Mesh._BACKSIDE = 1;
  34223. Mesh._DOUBLESIDE = 2;
  34224. Mesh._DEFAULTSIDE = 0;
  34225. Mesh._NO_CAP = 0;
  34226. Mesh._CAP_START = 1;
  34227. Mesh._CAP_END = 2;
  34228. Mesh._CAP_ALL = 3;
  34229. return Mesh;
  34230. }(BABYLON.AbstractMesh));
  34231. BABYLON.Mesh = Mesh;
  34232. })(BABYLON || (BABYLON = {}));
  34233. //# sourceMappingURL=babylon.mesh.js.map
  34234. var BABYLON;
  34235. (function (BABYLON) {
  34236. var BaseSubMesh = /** @class */ (function () {
  34237. function BaseSubMesh() {
  34238. }
  34239. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34240. get: function () {
  34241. return this._materialEffect;
  34242. },
  34243. enumerable: true,
  34244. configurable: true
  34245. });
  34246. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34247. if (defines === void 0) { defines = null; }
  34248. if (this._materialEffect === effect) {
  34249. if (!effect) {
  34250. this._materialDefines = null;
  34251. }
  34252. return;
  34253. }
  34254. this._materialDefines = defines;
  34255. this._materialEffect = effect;
  34256. };
  34257. return BaseSubMesh;
  34258. }());
  34259. BABYLON.BaseSubMesh = BaseSubMesh;
  34260. var SubMesh = /** @class */ (function (_super) {
  34261. __extends(SubMesh, _super);
  34262. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34263. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34264. var _this = _super.call(this) || this;
  34265. _this.materialIndex = materialIndex;
  34266. _this.verticesStart = verticesStart;
  34267. _this.verticesCount = verticesCount;
  34268. _this.indexStart = indexStart;
  34269. _this.indexCount = indexCount;
  34270. /** @hidden */
  34271. _this._renderId = 0;
  34272. _this._mesh = mesh;
  34273. _this._renderingMesh = renderingMesh || mesh;
  34274. mesh.subMeshes.push(_this);
  34275. _this._trianglePlanes = [];
  34276. _this._id = mesh.subMeshes.length - 1;
  34277. if (createBoundingBox) {
  34278. _this.refreshBoundingInfo();
  34279. mesh.computeWorldMatrix(true);
  34280. }
  34281. return _this;
  34282. }
  34283. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34284. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34285. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34286. };
  34287. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34288. get: function () {
  34289. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34290. },
  34291. enumerable: true,
  34292. configurable: true
  34293. });
  34294. /**
  34295. * Returns the submesh BoudingInfo object.
  34296. */
  34297. SubMesh.prototype.getBoundingInfo = function () {
  34298. if (this.IsGlobal) {
  34299. return this._mesh.getBoundingInfo();
  34300. }
  34301. return this._boundingInfo;
  34302. };
  34303. /**
  34304. * Sets the submesh BoundingInfo.
  34305. * Return the SubMesh.
  34306. */
  34307. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34308. this._boundingInfo = boundingInfo;
  34309. return this;
  34310. };
  34311. /**
  34312. * Returns the mesh of the current submesh.
  34313. */
  34314. SubMesh.prototype.getMesh = function () {
  34315. return this._mesh;
  34316. };
  34317. /**
  34318. * Returns the rendering mesh of the submesh.
  34319. */
  34320. SubMesh.prototype.getRenderingMesh = function () {
  34321. return this._renderingMesh;
  34322. };
  34323. /**
  34324. * Returns the submesh material.
  34325. */
  34326. SubMesh.prototype.getMaterial = function () {
  34327. var rootMaterial = this._renderingMesh.material;
  34328. if (rootMaterial === null || rootMaterial === undefined) {
  34329. return this._mesh.getScene().defaultMaterial;
  34330. }
  34331. else if (rootMaterial.getSubMaterial) {
  34332. var multiMaterial = rootMaterial;
  34333. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34334. if (this._currentMaterial !== effectiveMaterial) {
  34335. this._currentMaterial = effectiveMaterial;
  34336. this._materialDefines = null;
  34337. }
  34338. return effectiveMaterial;
  34339. }
  34340. return rootMaterial;
  34341. };
  34342. // Methods
  34343. /**
  34344. * Sets a new updated BoundingInfo object to the submesh.
  34345. * Returns the SubMesh.
  34346. */
  34347. SubMesh.prototype.refreshBoundingInfo = function () {
  34348. this._lastColliderWorldVertices = null;
  34349. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34350. return this;
  34351. }
  34352. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34353. if (!data) {
  34354. this._boundingInfo = this._mesh.getBoundingInfo();
  34355. return this;
  34356. }
  34357. var indices = this._renderingMesh.getIndices();
  34358. var extend;
  34359. //is this the only submesh?
  34360. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34361. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34362. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34363. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34364. }
  34365. else {
  34366. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34367. }
  34368. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34369. return this;
  34370. };
  34371. /** @hidden */
  34372. SubMesh.prototype._checkCollision = function (collider) {
  34373. var boundingInfo = this.getBoundingInfo();
  34374. return boundingInfo._checkCollision(collider);
  34375. };
  34376. /**
  34377. * Updates the submesh BoundingInfo.
  34378. * Returns the Submesh.
  34379. */
  34380. SubMesh.prototype.updateBoundingInfo = function (world) {
  34381. var boundingInfo = this.getBoundingInfo();
  34382. if (!boundingInfo) {
  34383. this.refreshBoundingInfo();
  34384. boundingInfo = this.getBoundingInfo();
  34385. }
  34386. boundingInfo.update(world);
  34387. return this;
  34388. };
  34389. /**
  34390. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34391. * Boolean returned.
  34392. */
  34393. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34394. var boundingInfo = this.getBoundingInfo();
  34395. if (!boundingInfo) {
  34396. return false;
  34397. }
  34398. return boundingInfo.isInFrustum(frustumPlanes);
  34399. };
  34400. /**
  34401. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34402. * Boolean returned.
  34403. */
  34404. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34405. var boundingInfo = this.getBoundingInfo();
  34406. if (!boundingInfo) {
  34407. return false;
  34408. }
  34409. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34410. };
  34411. /**
  34412. * Renders the submesh.
  34413. * Returns it.
  34414. */
  34415. SubMesh.prototype.render = function (enableAlphaMode) {
  34416. this._renderingMesh.render(this, enableAlphaMode);
  34417. return this;
  34418. };
  34419. /**
  34420. * Returns a new Index Buffer.
  34421. * Type returned : WebGLBuffer.
  34422. */
  34423. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34424. if (!this._linesIndexBuffer) {
  34425. var linesIndices = [];
  34426. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34427. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34428. }
  34429. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34430. this.linesIndexCount = linesIndices.length;
  34431. }
  34432. return this._linesIndexBuffer;
  34433. };
  34434. /**
  34435. * True is the passed Ray intersects the submesh bounding box.
  34436. * Boolean returned.
  34437. */
  34438. SubMesh.prototype.canIntersects = function (ray) {
  34439. var boundingInfo = this.getBoundingInfo();
  34440. if (!boundingInfo) {
  34441. return false;
  34442. }
  34443. return ray.intersectsBox(boundingInfo.boundingBox);
  34444. };
  34445. /**
  34446. * Returns an object IntersectionInfo.
  34447. */
  34448. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34449. var intersectInfo = null;
  34450. var material = this.getMaterial();
  34451. if (!material) {
  34452. return null;
  34453. }
  34454. switch (material.fillMode) {
  34455. case BABYLON.Material.PointListDrawMode:
  34456. case BABYLON.Material.LineListDrawMode:
  34457. case BABYLON.Material.LineLoopDrawMode:
  34458. case BABYLON.Material.LineStripDrawMode:
  34459. case BABYLON.Material.TriangleFanDrawMode:
  34460. case BABYLON.Material.TriangleStripDrawMode:
  34461. return null;
  34462. }
  34463. // LineMesh first as it's also a Mesh...
  34464. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34465. var lineMesh = this._mesh;
  34466. // Line test
  34467. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34468. var p0 = positions[indices[index]];
  34469. var p1 = positions[indices[index + 1]];
  34470. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34471. if (length < 0) {
  34472. continue;
  34473. }
  34474. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34475. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34476. if (fastCheck) {
  34477. break;
  34478. }
  34479. }
  34480. }
  34481. }
  34482. else {
  34483. // Triangles test
  34484. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34485. var p0 = positions[indices[index]];
  34486. var p1 = positions[indices[index + 1]];
  34487. var p2 = positions[indices[index + 2]];
  34488. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34489. if (currentIntersectInfo) {
  34490. if (currentIntersectInfo.distance < 0) {
  34491. continue;
  34492. }
  34493. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34494. intersectInfo = currentIntersectInfo;
  34495. intersectInfo.faceId = index / 3;
  34496. if (fastCheck) {
  34497. break;
  34498. }
  34499. }
  34500. }
  34501. }
  34502. }
  34503. return intersectInfo;
  34504. };
  34505. /** @hidden */
  34506. SubMesh.prototype._rebuild = function () {
  34507. if (this._linesIndexBuffer) {
  34508. this._linesIndexBuffer = null;
  34509. }
  34510. };
  34511. // Clone
  34512. /**
  34513. * Creates a new Submesh from the passed Mesh.
  34514. */
  34515. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34516. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34517. if (!this.IsGlobal) {
  34518. var boundingInfo = this.getBoundingInfo();
  34519. if (!boundingInfo) {
  34520. return result;
  34521. }
  34522. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34523. }
  34524. return result;
  34525. };
  34526. // Dispose
  34527. /**
  34528. * Disposes the Submesh.
  34529. * Returns nothing.
  34530. */
  34531. SubMesh.prototype.dispose = function () {
  34532. if (this._linesIndexBuffer) {
  34533. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34534. this._linesIndexBuffer = null;
  34535. }
  34536. // Remove from mesh
  34537. var index = this._mesh.subMeshes.indexOf(this);
  34538. this._mesh.subMeshes.splice(index, 1);
  34539. };
  34540. // Statics
  34541. /**
  34542. * Creates a new Submesh from the passed parameters :
  34543. * - materialIndex (integer) : the index of the main mesh material.
  34544. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34545. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34546. * - mesh (Mesh) : the main mesh to create the submesh from.
  34547. * - renderingMesh (optional Mesh) : rendering mesh.
  34548. */
  34549. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34550. var minVertexIndex = Number.MAX_VALUE;
  34551. var maxVertexIndex = -Number.MAX_VALUE;
  34552. renderingMesh = (renderingMesh || mesh);
  34553. var indices = renderingMesh.getIndices();
  34554. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34555. var vertexIndex = indices[index];
  34556. if (vertexIndex < minVertexIndex)
  34557. minVertexIndex = vertexIndex;
  34558. if (vertexIndex > maxVertexIndex)
  34559. maxVertexIndex = vertexIndex;
  34560. }
  34561. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34562. };
  34563. return SubMesh;
  34564. }(BaseSubMesh));
  34565. BABYLON.SubMesh = SubMesh;
  34566. })(BABYLON || (BABYLON = {}));
  34567. //# sourceMappingURL=babylon.subMesh.js.map
  34568. var __assign = (this && this.__assign) || function () {
  34569. __assign = Object.assign || function(t) {
  34570. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34571. s = arguments[i];
  34572. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34573. t[p] = s[p];
  34574. }
  34575. return t;
  34576. };
  34577. return __assign.apply(this, arguments);
  34578. };
  34579. var BABYLON;
  34580. (function (BABYLON) {
  34581. /**
  34582. * Manages the defines for the Material
  34583. */
  34584. var MaterialDefines = /** @class */ (function () {
  34585. function MaterialDefines() {
  34586. this._isDirty = true;
  34587. /** @hidden */
  34588. this._areLightsDirty = true;
  34589. /** @hidden */
  34590. this._areAttributesDirty = true;
  34591. /** @hidden */
  34592. this._areTexturesDirty = true;
  34593. /** @hidden */
  34594. this._areFresnelDirty = true;
  34595. /** @hidden */
  34596. this._areMiscDirty = true;
  34597. /** @hidden */
  34598. this._areImageProcessingDirty = true;
  34599. /** @hidden */
  34600. this._normals = false;
  34601. /** @hidden */
  34602. this._uvs = false;
  34603. /** @hidden */
  34604. this._needNormals = false;
  34605. /** @hidden */
  34606. this._needUVs = false;
  34607. }
  34608. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34609. /**
  34610. * Specifies if the material needs to be re-calculated
  34611. */
  34612. get: function () {
  34613. return this._isDirty;
  34614. },
  34615. enumerable: true,
  34616. configurable: true
  34617. });
  34618. /**
  34619. * Marks the material to indicate that it has been re-calculated
  34620. */
  34621. MaterialDefines.prototype.markAsProcessed = function () {
  34622. this._isDirty = false;
  34623. this._areAttributesDirty = false;
  34624. this._areTexturesDirty = false;
  34625. this._areFresnelDirty = false;
  34626. this._areLightsDirty = false;
  34627. this._areMiscDirty = false;
  34628. this._areImageProcessingDirty = false;
  34629. };
  34630. /**
  34631. * Marks the material to indicate that it needs to be re-calculated
  34632. */
  34633. MaterialDefines.prototype.markAsUnprocessed = function () {
  34634. this._isDirty = true;
  34635. };
  34636. /**
  34637. * Marks the material to indicate all of its defines need to be re-calculated
  34638. */
  34639. MaterialDefines.prototype.markAllAsDirty = function () {
  34640. this._areTexturesDirty = true;
  34641. this._areAttributesDirty = true;
  34642. this._areLightsDirty = true;
  34643. this._areFresnelDirty = true;
  34644. this._areMiscDirty = true;
  34645. this._areImageProcessingDirty = true;
  34646. this._isDirty = true;
  34647. };
  34648. /**
  34649. * Marks the material to indicate that image processing needs to be re-calculated
  34650. */
  34651. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34652. this._areImageProcessingDirty = true;
  34653. this._isDirty = true;
  34654. };
  34655. /**
  34656. * Marks the material to indicate the lights need to be re-calculated
  34657. */
  34658. MaterialDefines.prototype.markAsLightDirty = function () {
  34659. this._areLightsDirty = true;
  34660. this._isDirty = true;
  34661. };
  34662. /**
  34663. * Marks the attribute state as changed
  34664. */
  34665. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34666. this._areAttributesDirty = true;
  34667. this._isDirty = true;
  34668. };
  34669. /**
  34670. * Marks the texture state as changed
  34671. */
  34672. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34673. this._areTexturesDirty = true;
  34674. this._isDirty = true;
  34675. };
  34676. /**
  34677. * Marks the fresnel state as changed
  34678. */
  34679. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34680. this._areFresnelDirty = true;
  34681. this._isDirty = true;
  34682. };
  34683. /**
  34684. * Marks the misc state as changed
  34685. */
  34686. MaterialDefines.prototype.markAsMiscDirty = function () {
  34687. this._areMiscDirty = true;
  34688. this._isDirty = true;
  34689. };
  34690. /**
  34691. * Rebuilds the material defines
  34692. */
  34693. MaterialDefines.prototype.rebuild = function () {
  34694. if (this._keys) {
  34695. delete this._keys;
  34696. }
  34697. this._keys = [];
  34698. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34699. var key = _a[_i];
  34700. if (key[0] === "_") {
  34701. continue;
  34702. }
  34703. this._keys.push(key);
  34704. }
  34705. };
  34706. /**
  34707. * Specifies if two material defines are equal
  34708. * @param other - A material define instance to compare to
  34709. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34710. */
  34711. MaterialDefines.prototype.isEqual = function (other) {
  34712. if (this._keys.length !== other._keys.length) {
  34713. return false;
  34714. }
  34715. for (var index = 0; index < this._keys.length; index++) {
  34716. var prop = this._keys[index];
  34717. if (this[prop] !== other[prop]) {
  34718. return false;
  34719. }
  34720. }
  34721. return true;
  34722. };
  34723. /**
  34724. * Clones this instance's defines to another instance
  34725. * @param other - material defines to clone values to
  34726. */
  34727. MaterialDefines.prototype.cloneTo = function (other) {
  34728. if (this._keys.length !== other._keys.length) {
  34729. other._keys = this._keys.slice(0);
  34730. }
  34731. for (var index = 0; index < this._keys.length; index++) {
  34732. var prop = this._keys[index];
  34733. other[prop] = this[prop];
  34734. }
  34735. };
  34736. /**
  34737. * Resets the material define values
  34738. */
  34739. MaterialDefines.prototype.reset = function () {
  34740. for (var index = 0; index < this._keys.length; index++) {
  34741. var prop = this._keys[index];
  34742. var type = typeof this[prop];
  34743. switch (type) {
  34744. case "number":
  34745. this[prop] = 0;
  34746. break;
  34747. case "string":
  34748. this[prop] = "";
  34749. break;
  34750. default:
  34751. this[prop] = false;
  34752. break;
  34753. }
  34754. }
  34755. };
  34756. /**
  34757. * Converts the material define values to a string
  34758. * @returns - String of material define information
  34759. */
  34760. MaterialDefines.prototype.toString = function () {
  34761. var result = "";
  34762. for (var index = 0; index < this._keys.length; index++) {
  34763. var prop = this._keys[index];
  34764. var value = this[prop];
  34765. var type = typeof value;
  34766. switch (type) {
  34767. case "number":
  34768. case "string":
  34769. result += "#define " + prop + " " + value + "\n";
  34770. break;
  34771. default:
  34772. if (value) {
  34773. result += "#define " + prop + "\n";
  34774. }
  34775. break;
  34776. }
  34777. }
  34778. return result;
  34779. };
  34780. return MaterialDefines;
  34781. }());
  34782. BABYLON.MaterialDefines = MaterialDefines;
  34783. /**
  34784. * Base class for the main features of a material in Babylon.js
  34785. */
  34786. var Material = /** @class */ (function () {
  34787. /**
  34788. * Creates a material instance
  34789. * @param name defines the name of the material
  34790. * @param scene defines the scene to reference
  34791. * @param doNotAdd specifies if the material should be added to the scene
  34792. */
  34793. function Material(name, scene, doNotAdd) {
  34794. /**
  34795. * Specifies if the ready state should be checked on each call
  34796. */
  34797. this.checkReadyOnEveryCall = false;
  34798. /**
  34799. * Specifies if the ready state should be checked once
  34800. */
  34801. this.checkReadyOnlyOnce = false;
  34802. /**
  34803. * The state of the material
  34804. */
  34805. this.state = "";
  34806. /**
  34807. * The alpha value of the material
  34808. */
  34809. this._alpha = 1.0;
  34810. /**
  34811. * Specifies if back face culling is enabled
  34812. */
  34813. this._backFaceCulling = true;
  34814. /**
  34815. * Specifies if the material should be serialized
  34816. */
  34817. this.doNotSerialize = false;
  34818. /**
  34819. * Specifies if the effect should be stored on sub meshes
  34820. */
  34821. this.storeEffectOnSubMeshes = false;
  34822. /**
  34823. * An event triggered when the material is disposed
  34824. */
  34825. this.onDisposeObservable = new BABYLON.Observable();
  34826. /**
  34827. * Stores the value of the alpha mode
  34828. */
  34829. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34830. /**
  34831. * Stores the state of the need depth pre-pass value
  34832. */
  34833. this._needDepthPrePass = false;
  34834. /**
  34835. * Specifies if depth writing should be disabled
  34836. */
  34837. this.disableDepthWrite = false;
  34838. /**
  34839. * Specifies if depth writing should be forced
  34840. */
  34841. this.forceDepthWrite = false;
  34842. /**
  34843. * Specifies if there should be a separate pass for culling
  34844. */
  34845. this.separateCullingPass = false;
  34846. /**
  34847. * Stores the state specifing if fog should be enabled
  34848. */
  34849. this._fogEnabled = true;
  34850. /**
  34851. * Stores the size of points
  34852. */
  34853. this.pointSize = 1.0;
  34854. /**
  34855. * Stores the z offset value
  34856. */
  34857. this.zOffset = 0;
  34858. /**
  34859. * @hidden
  34860. * Specifies if the material was previously ready
  34861. */
  34862. this._wasPreviouslyReady = false;
  34863. /**
  34864. * Stores the fill mode state
  34865. */
  34866. this._fillMode = Material.TriangleFillMode;
  34867. this.name = name;
  34868. this.id = name || BABYLON.Tools.RandomId();
  34869. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34870. this.uniqueId = this._scene.getUniqueId();
  34871. if (this._scene.useRightHandedSystem) {
  34872. this.sideOrientation = Material.ClockWiseSideOrientation;
  34873. }
  34874. else {
  34875. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34876. }
  34877. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34878. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34879. if (!doNotAdd) {
  34880. this._scene.materials.push(this);
  34881. }
  34882. }
  34883. Object.defineProperty(Material, "TriangleFillMode", {
  34884. /**
  34885. * Returns the triangle fill mode
  34886. */
  34887. get: function () {
  34888. return Material._TriangleFillMode;
  34889. },
  34890. enumerable: true,
  34891. configurable: true
  34892. });
  34893. Object.defineProperty(Material, "WireFrameFillMode", {
  34894. /**
  34895. * Returns the wireframe mode
  34896. */
  34897. get: function () {
  34898. return Material._WireFrameFillMode;
  34899. },
  34900. enumerable: true,
  34901. configurable: true
  34902. });
  34903. Object.defineProperty(Material, "PointFillMode", {
  34904. /**
  34905. * Returns the point fill mode
  34906. */
  34907. get: function () {
  34908. return Material._PointFillMode;
  34909. },
  34910. enumerable: true,
  34911. configurable: true
  34912. });
  34913. Object.defineProperty(Material, "PointListDrawMode", {
  34914. /**
  34915. * Returns the point list draw mode
  34916. */
  34917. get: function () {
  34918. return Material._PointListDrawMode;
  34919. },
  34920. enumerable: true,
  34921. configurable: true
  34922. });
  34923. Object.defineProperty(Material, "LineListDrawMode", {
  34924. /**
  34925. * Returns the line list draw mode
  34926. */
  34927. get: function () {
  34928. return Material._LineListDrawMode;
  34929. },
  34930. enumerable: true,
  34931. configurable: true
  34932. });
  34933. Object.defineProperty(Material, "LineLoopDrawMode", {
  34934. /**
  34935. * Returns the line loop draw mode
  34936. */
  34937. get: function () {
  34938. return Material._LineLoopDrawMode;
  34939. },
  34940. enumerable: true,
  34941. configurable: true
  34942. });
  34943. Object.defineProperty(Material, "LineStripDrawMode", {
  34944. /**
  34945. * Returns the line strip draw mode
  34946. */
  34947. get: function () {
  34948. return Material._LineStripDrawMode;
  34949. },
  34950. enumerable: true,
  34951. configurable: true
  34952. });
  34953. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34954. /**
  34955. * Returns the triangle strip draw mode
  34956. */
  34957. get: function () {
  34958. return Material._TriangleStripDrawMode;
  34959. },
  34960. enumerable: true,
  34961. configurable: true
  34962. });
  34963. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34964. /**
  34965. * Returns the triangle fan draw mode
  34966. */
  34967. get: function () {
  34968. return Material._TriangleFanDrawMode;
  34969. },
  34970. enumerable: true,
  34971. configurable: true
  34972. });
  34973. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34974. /**
  34975. * Returns the clock-wise side orientation
  34976. */
  34977. get: function () {
  34978. return Material._ClockWiseSideOrientation;
  34979. },
  34980. enumerable: true,
  34981. configurable: true
  34982. });
  34983. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34984. /**
  34985. * Returns the counter clock-wise side orientation
  34986. */
  34987. get: function () {
  34988. return Material._CounterClockWiseSideOrientation;
  34989. },
  34990. enumerable: true,
  34991. configurable: true
  34992. });
  34993. Object.defineProperty(Material, "TextureDirtyFlag", {
  34994. /**
  34995. * Returns the dirty texture flag value
  34996. */
  34997. get: function () {
  34998. return Material._TextureDirtyFlag;
  34999. },
  35000. enumerable: true,
  35001. configurable: true
  35002. });
  35003. Object.defineProperty(Material, "LightDirtyFlag", {
  35004. /**
  35005. * Returns the dirty light flag value
  35006. */
  35007. get: function () {
  35008. return Material._LightDirtyFlag;
  35009. },
  35010. enumerable: true,
  35011. configurable: true
  35012. });
  35013. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35014. /**
  35015. * Returns the dirty fresnel flag value
  35016. */
  35017. get: function () {
  35018. return Material._FresnelDirtyFlag;
  35019. },
  35020. enumerable: true,
  35021. configurable: true
  35022. });
  35023. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35024. /**
  35025. * Returns the dirty attributes flag value
  35026. */
  35027. get: function () {
  35028. return Material._AttributesDirtyFlag;
  35029. },
  35030. enumerable: true,
  35031. configurable: true
  35032. });
  35033. Object.defineProperty(Material, "MiscDirtyFlag", {
  35034. /**
  35035. * Returns the dirty misc flag value
  35036. */
  35037. get: function () {
  35038. return Material._MiscDirtyFlag;
  35039. },
  35040. enumerable: true,
  35041. configurable: true
  35042. });
  35043. Object.defineProperty(Material.prototype, "alpha", {
  35044. /**
  35045. * Gets the alpha value of the material
  35046. */
  35047. get: function () {
  35048. return this._alpha;
  35049. },
  35050. /**
  35051. * Sets the alpha value of the material
  35052. */
  35053. set: function (value) {
  35054. if (this._alpha === value) {
  35055. return;
  35056. }
  35057. this._alpha = value;
  35058. this.markAsDirty(Material.MiscDirtyFlag);
  35059. },
  35060. enumerable: true,
  35061. configurable: true
  35062. });
  35063. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35064. /**
  35065. * Gets the back-face culling state
  35066. */
  35067. get: function () {
  35068. return this._backFaceCulling;
  35069. },
  35070. /**
  35071. * Sets the back-face culling state
  35072. */
  35073. set: function (value) {
  35074. if (this._backFaceCulling === value) {
  35075. return;
  35076. }
  35077. this._backFaceCulling = value;
  35078. this.markAsDirty(Material.TextureDirtyFlag);
  35079. },
  35080. enumerable: true,
  35081. configurable: true
  35082. });
  35083. Object.defineProperty(Material.prototype, "onDispose", {
  35084. /**
  35085. * Called during a dispose event
  35086. */
  35087. set: function (callback) {
  35088. if (this._onDisposeObserver) {
  35089. this.onDisposeObservable.remove(this._onDisposeObserver);
  35090. }
  35091. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35092. },
  35093. enumerable: true,
  35094. configurable: true
  35095. });
  35096. Object.defineProperty(Material.prototype, "onBindObservable", {
  35097. /**
  35098. * An event triggered when the material is bound
  35099. */
  35100. get: function () {
  35101. if (!this._onBindObservable) {
  35102. this._onBindObservable = new BABYLON.Observable();
  35103. }
  35104. return this._onBindObservable;
  35105. },
  35106. enumerable: true,
  35107. configurable: true
  35108. });
  35109. Object.defineProperty(Material.prototype, "onBind", {
  35110. /**
  35111. * Called during a bind event
  35112. */
  35113. set: function (callback) {
  35114. if (this._onBindObserver) {
  35115. this.onBindObservable.remove(this._onBindObserver);
  35116. }
  35117. this._onBindObserver = this.onBindObservable.add(callback);
  35118. },
  35119. enumerable: true,
  35120. configurable: true
  35121. });
  35122. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35123. /**
  35124. * An event triggered when the material is unbound
  35125. */
  35126. get: function () {
  35127. if (!this._onUnBindObservable) {
  35128. this._onUnBindObservable = new BABYLON.Observable();
  35129. }
  35130. return this._onUnBindObservable;
  35131. },
  35132. enumerable: true,
  35133. configurable: true
  35134. });
  35135. Object.defineProperty(Material.prototype, "alphaMode", {
  35136. /**
  35137. * Gets the value of the alpha mode
  35138. */
  35139. get: function () {
  35140. return this._alphaMode;
  35141. },
  35142. /**
  35143. * Sets the value of the alpha mode.
  35144. *
  35145. * | Value | Type | Description |
  35146. * | --- | --- | --- |
  35147. * | 0 | ALPHA_DISABLE | |
  35148. * | 1 | ALPHA_ADD | |
  35149. * | 2 | ALPHA_COMBINE | |
  35150. * | 3 | ALPHA_SUBTRACT | |
  35151. * | 4 | ALPHA_MULTIPLY | |
  35152. * | 5 | ALPHA_MAXIMIZED | |
  35153. * | 6 | ALPHA_ONEONE | |
  35154. * | 7 | ALPHA_PREMULTIPLIED | |
  35155. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35156. * | 9 | ALPHA_INTERPOLATE | |
  35157. * | 10 | ALPHA_SCREENMODE | |
  35158. *
  35159. */
  35160. set: function (value) {
  35161. if (this._alphaMode === value) {
  35162. return;
  35163. }
  35164. this._alphaMode = value;
  35165. this.markAsDirty(Material.TextureDirtyFlag);
  35166. },
  35167. enumerable: true,
  35168. configurable: true
  35169. });
  35170. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35171. /**
  35172. * Gets the depth pre-pass value
  35173. */
  35174. get: function () {
  35175. return this._needDepthPrePass;
  35176. },
  35177. /**
  35178. * Sets the need depth pre-pass value
  35179. */
  35180. set: function (value) {
  35181. if (this._needDepthPrePass === value) {
  35182. return;
  35183. }
  35184. this._needDepthPrePass = value;
  35185. if (this._needDepthPrePass) {
  35186. this.checkReadyOnEveryCall = true;
  35187. }
  35188. },
  35189. enumerable: true,
  35190. configurable: true
  35191. });
  35192. Object.defineProperty(Material.prototype, "fogEnabled", {
  35193. /**
  35194. * Gets the value of the fog enabled state
  35195. */
  35196. get: function () {
  35197. return this._fogEnabled;
  35198. },
  35199. /**
  35200. * Sets the state for enabling fog
  35201. */
  35202. set: function (value) {
  35203. if (this._fogEnabled === value) {
  35204. return;
  35205. }
  35206. this._fogEnabled = value;
  35207. this.markAsDirty(Material.MiscDirtyFlag);
  35208. },
  35209. enumerable: true,
  35210. configurable: true
  35211. });
  35212. Object.defineProperty(Material.prototype, "wireframe", {
  35213. /**
  35214. * Gets a value specifying if wireframe mode is enabled
  35215. */
  35216. get: function () {
  35217. switch (this._fillMode) {
  35218. case Material.WireFrameFillMode:
  35219. case Material.LineListDrawMode:
  35220. case Material.LineLoopDrawMode:
  35221. case Material.LineStripDrawMode:
  35222. return true;
  35223. }
  35224. return this._scene.forceWireframe;
  35225. },
  35226. /**
  35227. * Sets the state of wireframe mode
  35228. */
  35229. set: function (value) {
  35230. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35231. },
  35232. enumerable: true,
  35233. configurable: true
  35234. });
  35235. Object.defineProperty(Material.prototype, "pointsCloud", {
  35236. /**
  35237. * Gets the value specifying if point clouds are enabled
  35238. */
  35239. get: function () {
  35240. switch (this._fillMode) {
  35241. case Material.PointFillMode:
  35242. case Material.PointListDrawMode:
  35243. return true;
  35244. }
  35245. return this._scene.forcePointsCloud;
  35246. },
  35247. /**
  35248. * Sets the state of point cloud mode
  35249. */
  35250. set: function (value) {
  35251. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35252. },
  35253. enumerable: true,
  35254. configurable: true
  35255. });
  35256. Object.defineProperty(Material.prototype, "fillMode", {
  35257. /**
  35258. * Gets the material fill mode
  35259. */
  35260. get: function () {
  35261. return this._fillMode;
  35262. },
  35263. /**
  35264. * Sets the material fill mode
  35265. */
  35266. set: function (value) {
  35267. if (this._fillMode === value) {
  35268. return;
  35269. }
  35270. this._fillMode = value;
  35271. this.markAsDirty(Material.MiscDirtyFlag);
  35272. },
  35273. enumerable: true,
  35274. configurable: true
  35275. });
  35276. /**
  35277. * Returns a string representation of the current material
  35278. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35279. * @returns a string with material information
  35280. */
  35281. Material.prototype.toString = function (fullDetails) {
  35282. var ret = "Name: " + this.name;
  35283. if (fullDetails) {
  35284. }
  35285. return ret;
  35286. };
  35287. /**
  35288. * Gets the class name of the material
  35289. * @returns a string with the class name of the material
  35290. */
  35291. Material.prototype.getClassName = function () {
  35292. return "Material";
  35293. };
  35294. Object.defineProperty(Material.prototype, "isFrozen", {
  35295. /**
  35296. * Specifies if updates for the material been locked
  35297. */
  35298. get: function () {
  35299. return this.checkReadyOnlyOnce;
  35300. },
  35301. enumerable: true,
  35302. configurable: true
  35303. });
  35304. /**
  35305. * Locks updates for the material
  35306. */
  35307. Material.prototype.freeze = function () {
  35308. this.checkReadyOnlyOnce = true;
  35309. };
  35310. /**
  35311. * Unlocks updates for the material
  35312. */
  35313. Material.prototype.unfreeze = function () {
  35314. this.checkReadyOnlyOnce = false;
  35315. };
  35316. /**
  35317. * Specifies if the material is ready to be used
  35318. * @param mesh defines the mesh to check
  35319. * @param useInstances specifies if instances should be used
  35320. * @returns a boolean indicating if the material is ready to be used
  35321. */
  35322. Material.prototype.isReady = function (mesh, useInstances) {
  35323. return true;
  35324. };
  35325. /**
  35326. * Specifies that the submesh is ready to be used
  35327. * @param mesh defines the mesh to check
  35328. * @param subMesh defines which submesh to check
  35329. * @param useInstances specifies that instances should be used
  35330. * @returns a boolean indicating that the submesh is ready or not
  35331. */
  35332. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35333. return false;
  35334. };
  35335. /**
  35336. * Returns the material effect
  35337. * @returns the effect associated with the material
  35338. */
  35339. Material.prototype.getEffect = function () {
  35340. return this._effect;
  35341. };
  35342. /**
  35343. * Returns the current scene
  35344. * @returns a Scene
  35345. */
  35346. Material.prototype.getScene = function () {
  35347. return this._scene;
  35348. };
  35349. /**
  35350. * Specifies if the material will require alpha blending
  35351. * @returns a boolean specifying if alpha blending is needed
  35352. */
  35353. Material.prototype.needAlphaBlending = function () {
  35354. return (this.alpha < 1.0);
  35355. };
  35356. /**
  35357. * Specifies if the mesh will require alpha blending
  35358. * @param mesh defines the mesh to check
  35359. * @returns a boolean specifying if alpha blending is needed for the mesh
  35360. */
  35361. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35362. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35363. };
  35364. /**
  35365. * Specifies if this material should be rendered in alpha test mode
  35366. * @returns a boolean specifying if an alpha test is needed.
  35367. */
  35368. Material.prototype.needAlphaTesting = function () {
  35369. return false;
  35370. };
  35371. /**
  35372. * Gets the texture used for the alpha test
  35373. * @returns the texture to use for alpha testing
  35374. */
  35375. Material.prototype.getAlphaTestTexture = function () {
  35376. return null;
  35377. };
  35378. /**
  35379. * Marks the material to indicate that it needs to be re-calculated
  35380. */
  35381. Material.prototype.markDirty = function () {
  35382. this._wasPreviouslyReady = false;
  35383. };
  35384. /** @hidden */
  35385. Material.prototype._preBind = function (effect, overrideOrientation) {
  35386. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35387. var engine = this._scene.getEngine();
  35388. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35389. var reverse = orientation === Material.ClockWiseSideOrientation;
  35390. engine.enableEffect(effect ? effect : this._effect);
  35391. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35392. return reverse;
  35393. };
  35394. /**
  35395. * Binds the material to the mesh
  35396. * @param world defines the world transformation matrix
  35397. * @param mesh defines the mesh to bind the material to
  35398. */
  35399. Material.prototype.bind = function (world, mesh) {
  35400. };
  35401. /**
  35402. * Binds the submesh to the material
  35403. * @param world defines the world transformation matrix
  35404. * @param mesh defines the mesh containing the submesh
  35405. * @param subMesh defines the submesh to bind the material to
  35406. */
  35407. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35408. };
  35409. /**
  35410. * Binds the world matrix to the material
  35411. * @param world defines the world transformation matrix
  35412. */
  35413. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35414. };
  35415. /**
  35416. * Binds the scene's uniform buffer to the effect.
  35417. * @param effect defines the effect to bind to the scene uniform buffer
  35418. * @param sceneUbo defines the uniform buffer storing scene data
  35419. */
  35420. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35421. sceneUbo.bindToEffect(effect, "Scene");
  35422. };
  35423. /**
  35424. * Binds the view matrix to the effect
  35425. * @param effect defines the effect to bind the view matrix to
  35426. */
  35427. Material.prototype.bindView = function (effect) {
  35428. if (!this._useUBO) {
  35429. effect.setMatrix("view", this.getScene().getViewMatrix());
  35430. }
  35431. else {
  35432. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35433. }
  35434. };
  35435. /**
  35436. * Binds the view projection matrix to the effect
  35437. * @param effect defines the effect to bind the view projection matrix to
  35438. */
  35439. Material.prototype.bindViewProjection = function (effect) {
  35440. if (!this._useUBO) {
  35441. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35442. }
  35443. else {
  35444. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35445. }
  35446. };
  35447. /**
  35448. * Specifies if material alpha testing should be turned on for the mesh
  35449. * @param mesh defines the mesh to check
  35450. */
  35451. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35452. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35453. };
  35454. /**
  35455. * Processes to execute after binding the material to a mesh
  35456. * @param mesh defines the rendered mesh
  35457. */
  35458. Material.prototype._afterBind = function (mesh) {
  35459. this._scene._cachedMaterial = this;
  35460. if (mesh) {
  35461. this._scene._cachedVisibility = mesh.visibility;
  35462. }
  35463. else {
  35464. this._scene._cachedVisibility = 1;
  35465. }
  35466. if (this._onBindObservable && mesh) {
  35467. this._onBindObservable.notifyObservers(mesh);
  35468. }
  35469. if (this.disableDepthWrite) {
  35470. var engine = this._scene.getEngine();
  35471. this._cachedDepthWriteState = engine.getDepthWrite();
  35472. engine.setDepthWrite(false);
  35473. }
  35474. };
  35475. /**
  35476. * Unbinds the material from the mesh
  35477. */
  35478. Material.prototype.unbind = function () {
  35479. if (this._onUnBindObservable) {
  35480. this._onUnBindObservable.notifyObservers(this);
  35481. }
  35482. if (this.disableDepthWrite) {
  35483. var engine = this._scene.getEngine();
  35484. engine.setDepthWrite(this._cachedDepthWriteState);
  35485. }
  35486. };
  35487. /**
  35488. * Gets the active textures from the material
  35489. * @returns an array of textures
  35490. */
  35491. Material.prototype.getActiveTextures = function () {
  35492. return [];
  35493. };
  35494. /**
  35495. * Specifies if the material uses a texture
  35496. * @param texture defines the texture to check against the material
  35497. * @returns a boolean specifying if the material uses the texture
  35498. */
  35499. Material.prototype.hasTexture = function (texture) {
  35500. return false;
  35501. };
  35502. /**
  35503. * Makes a duplicate of the material, and gives it a new name
  35504. * @param name defines the new name for the duplicated material
  35505. * @returns the cloned material
  35506. */
  35507. Material.prototype.clone = function (name) {
  35508. return null;
  35509. };
  35510. /**
  35511. * Gets the meshes bound to the material
  35512. * @returns an array of meshes bound to the material
  35513. */
  35514. Material.prototype.getBindedMeshes = function () {
  35515. var result = new Array();
  35516. for (var index = 0; index < this._scene.meshes.length; index++) {
  35517. var mesh = this._scene.meshes[index];
  35518. if (mesh.material === this) {
  35519. result.push(mesh);
  35520. }
  35521. }
  35522. return result;
  35523. };
  35524. /**
  35525. * Force shader compilation
  35526. * @param mesh defines the mesh associated with this material
  35527. * @param onCompiled defines a function to execute once the material is compiled
  35528. * @param options defines the options to configure the compilation
  35529. */
  35530. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35531. var _this = this;
  35532. var localOptions = __assign({ clipPlane: false }, options);
  35533. var subMesh = new BABYLON.BaseSubMesh();
  35534. var scene = this.getScene();
  35535. var checkReady = function () {
  35536. if (!_this._scene || !_this._scene.getEngine()) {
  35537. return;
  35538. }
  35539. if (subMesh._materialDefines) {
  35540. subMesh._materialDefines._renderId = -1;
  35541. }
  35542. var clipPlaneState = scene.clipPlane;
  35543. if (localOptions.clipPlane) {
  35544. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35545. }
  35546. if (_this.storeEffectOnSubMeshes) {
  35547. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35548. if (onCompiled) {
  35549. onCompiled(_this);
  35550. }
  35551. }
  35552. else {
  35553. setTimeout(checkReady, 16);
  35554. }
  35555. }
  35556. else {
  35557. if (_this.isReady(mesh)) {
  35558. if (onCompiled) {
  35559. onCompiled(_this);
  35560. }
  35561. }
  35562. else {
  35563. setTimeout(checkReady, 16);
  35564. }
  35565. }
  35566. if (localOptions.clipPlane) {
  35567. scene.clipPlane = clipPlaneState;
  35568. }
  35569. };
  35570. checkReady();
  35571. };
  35572. /**
  35573. * Force shader compilation
  35574. * @param mesh defines the mesh that will use this material
  35575. * @param options defines additional options for compiling the shaders
  35576. * @returns a promise that resolves when the compilation completes
  35577. */
  35578. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35579. var _this = this;
  35580. return new Promise(function (resolve) {
  35581. _this.forceCompilation(mesh, function () {
  35582. resolve();
  35583. }, options);
  35584. });
  35585. };
  35586. /**
  35587. * Marks a define in the material to indicate that it needs to be re-computed
  35588. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35589. */
  35590. Material.prototype.markAsDirty = function (flag) {
  35591. if (flag & Material.TextureDirtyFlag) {
  35592. this._markAllSubMeshesAsTexturesDirty();
  35593. }
  35594. if (flag & Material.LightDirtyFlag) {
  35595. this._markAllSubMeshesAsLightsDirty();
  35596. }
  35597. if (flag & Material.FresnelDirtyFlag) {
  35598. this._markAllSubMeshesAsFresnelDirty();
  35599. }
  35600. if (flag & Material.AttributesDirtyFlag) {
  35601. this._markAllSubMeshesAsAttributesDirty();
  35602. }
  35603. if (flag & Material.MiscDirtyFlag) {
  35604. this._markAllSubMeshesAsMiscDirty();
  35605. }
  35606. this.getScene().resetCachedMaterial();
  35607. };
  35608. /**
  35609. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35610. * @param func defines a function which checks material defines against the submeshes
  35611. */
  35612. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35613. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35614. var mesh = _a[_i];
  35615. if (!mesh.subMeshes) {
  35616. continue;
  35617. }
  35618. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35619. var subMesh = _c[_b];
  35620. if (subMesh.getMaterial() !== this) {
  35621. continue;
  35622. }
  35623. if (!subMesh._materialDefines) {
  35624. continue;
  35625. }
  35626. func(subMesh._materialDefines);
  35627. }
  35628. }
  35629. };
  35630. /**
  35631. * Indicates that image processing needs to be re-calculated for all submeshes
  35632. */
  35633. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35634. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35635. };
  35636. /**
  35637. * Indicates that textures need to be re-calculated for all submeshes
  35638. */
  35639. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35640. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35641. };
  35642. /**
  35643. * Indicates that fresnel needs to be re-calculated for all submeshes
  35644. */
  35645. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35646. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35647. };
  35648. /**
  35649. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35650. */
  35651. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35652. this._markAllSubMeshesAsDirty(function (defines) {
  35653. defines.markAsFresnelDirty();
  35654. defines.markAsMiscDirty();
  35655. });
  35656. };
  35657. /**
  35658. * Indicates that lights need to be re-calculated for all submeshes
  35659. */
  35660. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35661. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35662. };
  35663. /**
  35664. * Indicates that attributes need to be re-calculated for all submeshes
  35665. */
  35666. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35667. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35668. };
  35669. /**
  35670. * Indicates that misc needs to be re-calculated for all submeshes
  35671. */
  35672. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35673. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35674. };
  35675. /**
  35676. * Indicates that textures and misc need to be re-calculated for all submeshes
  35677. */
  35678. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35679. this._markAllSubMeshesAsDirty(function (defines) {
  35680. defines.markAsTexturesDirty();
  35681. defines.markAsMiscDirty();
  35682. });
  35683. };
  35684. /**
  35685. * Disposes the material
  35686. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35687. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35688. */
  35689. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35690. // Animations
  35691. this.getScene().stopAnimation(this);
  35692. this.getScene().freeProcessedMaterials();
  35693. // Remove from scene
  35694. var index = this._scene.materials.indexOf(this);
  35695. if (index >= 0) {
  35696. this._scene.materials.splice(index, 1);
  35697. }
  35698. // Remove from meshes
  35699. for (index = 0; index < this._scene.meshes.length; index++) {
  35700. var mesh = this._scene.meshes[index];
  35701. if (mesh.material === this) {
  35702. mesh.material = null;
  35703. if (mesh.geometry) {
  35704. var geometry = (mesh.geometry);
  35705. if (this.storeEffectOnSubMeshes) {
  35706. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35707. var subMesh = _a[_i];
  35708. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35709. if (forceDisposeEffect && subMesh._materialEffect) {
  35710. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35711. }
  35712. }
  35713. }
  35714. else {
  35715. geometry._releaseVertexArrayObject(this._effect);
  35716. }
  35717. }
  35718. }
  35719. }
  35720. this._uniformBuffer.dispose();
  35721. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35722. if (forceDisposeEffect && this._effect) {
  35723. if (!this.storeEffectOnSubMeshes) {
  35724. this._scene.getEngine()._releaseEffect(this._effect);
  35725. }
  35726. this._effect = null;
  35727. }
  35728. // Callback
  35729. this.onDisposeObservable.notifyObservers(this);
  35730. this.onDisposeObservable.clear();
  35731. if (this._onBindObservable) {
  35732. this._onBindObservable.clear();
  35733. }
  35734. if (this._onUnBindObservable) {
  35735. this._onUnBindObservable.clear();
  35736. }
  35737. };
  35738. /**
  35739. * Serializes this material
  35740. * @returns the serialized material object
  35741. */
  35742. Material.prototype.serialize = function () {
  35743. return BABYLON.SerializationHelper.Serialize(this);
  35744. };
  35745. /**
  35746. * Creates a MultiMaterial from parsed MultiMaterial data.
  35747. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35748. * @param scene defines the hosting scene
  35749. * @returns a new MultiMaterial
  35750. */
  35751. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35752. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35753. multiMaterial.id = parsedMultiMaterial.id;
  35754. if (BABYLON.Tags) {
  35755. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35756. }
  35757. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35758. var subMatId = parsedMultiMaterial.materials[matIndex];
  35759. if (subMatId) {
  35760. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35761. }
  35762. else {
  35763. multiMaterial.subMaterials.push(null);
  35764. }
  35765. }
  35766. return multiMaterial;
  35767. };
  35768. /**
  35769. * Creates a material from parsed material data
  35770. * @param parsedMaterial defines parsed material data
  35771. * @param scene defines the hosting scene
  35772. * @param rootUrl defines the root URL to use to load textures
  35773. * @returns a new material
  35774. */
  35775. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35776. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35777. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35778. }
  35779. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35780. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35781. if (!BABYLON.LegacyPBRMaterial) {
  35782. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35783. return;
  35784. }
  35785. }
  35786. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35787. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35788. };
  35789. // Triangle views
  35790. Material._TriangleFillMode = 0;
  35791. Material._WireFrameFillMode = 1;
  35792. Material._PointFillMode = 2;
  35793. // Draw modes
  35794. Material._PointListDrawMode = 3;
  35795. Material._LineListDrawMode = 4;
  35796. Material._LineLoopDrawMode = 5;
  35797. Material._LineStripDrawMode = 6;
  35798. Material._TriangleStripDrawMode = 7;
  35799. Material._TriangleFanDrawMode = 8;
  35800. /**
  35801. * Stores the clock-wise side orientation
  35802. */
  35803. Material._ClockWiseSideOrientation = 0;
  35804. /**
  35805. * Stores the counter clock-wise side orientation
  35806. */
  35807. Material._CounterClockWiseSideOrientation = 1;
  35808. /**
  35809. * The dirty texture flag value
  35810. */
  35811. Material._TextureDirtyFlag = 1;
  35812. /**
  35813. * The dirty light flag value
  35814. */
  35815. Material._LightDirtyFlag = 2;
  35816. /**
  35817. * The dirty fresnel flag value
  35818. */
  35819. Material._FresnelDirtyFlag = 4;
  35820. /**
  35821. * The dirty attribute flag value
  35822. */
  35823. Material._AttributesDirtyFlag = 8;
  35824. /**
  35825. * The dirty misc flag value
  35826. */
  35827. Material._MiscDirtyFlag = 16;
  35828. __decorate([
  35829. BABYLON.serialize()
  35830. ], Material.prototype, "id", void 0);
  35831. __decorate([
  35832. BABYLON.serialize()
  35833. ], Material.prototype, "uniqueId", void 0);
  35834. __decorate([
  35835. BABYLON.serialize()
  35836. ], Material.prototype, "name", void 0);
  35837. __decorate([
  35838. BABYLON.serialize()
  35839. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35840. __decorate([
  35841. BABYLON.serialize()
  35842. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35843. __decorate([
  35844. BABYLON.serialize()
  35845. ], Material.prototype, "state", void 0);
  35846. __decorate([
  35847. BABYLON.serialize("alpha")
  35848. ], Material.prototype, "_alpha", void 0);
  35849. __decorate([
  35850. BABYLON.serialize("backFaceCulling")
  35851. ], Material.prototype, "_backFaceCulling", void 0);
  35852. __decorate([
  35853. BABYLON.serialize()
  35854. ], Material.prototype, "sideOrientation", void 0);
  35855. __decorate([
  35856. BABYLON.serialize("alphaMode")
  35857. ], Material.prototype, "_alphaMode", void 0);
  35858. __decorate([
  35859. BABYLON.serialize()
  35860. ], Material.prototype, "_needDepthPrePass", void 0);
  35861. __decorate([
  35862. BABYLON.serialize()
  35863. ], Material.prototype, "disableDepthWrite", void 0);
  35864. __decorate([
  35865. BABYLON.serialize()
  35866. ], Material.prototype, "forceDepthWrite", void 0);
  35867. __decorate([
  35868. BABYLON.serialize()
  35869. ], Material.prototype, "separateCullingPass", void 0);
  35870. __decorate([
  35871. BABYLON.serialize("fogEnabled")
  35872. ], Material.prototype, "_fogEnabled", void 0);
  35873. __decorate([
  35874. BABYLON.serialize()
  35875. ], Material.prototype, "pointSize", void 0);
  35876. __decorate([
  35877. BABYLON.serialize()
  35878. ], Material.prototype, "zOffset", void 0);
  35879. __decorate([
  35880. BABYLON.serialize()
  35881. ], Material.prototype, "wireframe", null);
  35882. __decorate([
  35883. BABYLON.serialize()
  35884. ], Material.prototype, "pointsCloud", null);
  35885. __decorate([
  35886. BABYLON.serialize()
  35887. ], Material.prototype, "fillMode", null);
  35888. return Material;
  35889. }());
  35890. BABYLON.Material = Material;
  35891. })(BABYLON || (BABYLON = {}));
  35892. //# sourceMappingURL=babylon.material.js.map
  35893. var BABYLON;
  35894. (function (BABYLON) {
  35895. var UniformBuffer = /** @class */ (function () {
  35896. /**
  35897. * Uniform buffer objects.
  35898. *
  35899. * Handles blocks of uniform on the GPU.
  35900. *
  35901. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35902. *
  35903. * For more information, please refer to :
  35904. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35905. */
  35906. function UniformBuffer(engine, data, dynamic) {
  35907. this._engine = engine;
  35908. this._noUBO = !engine.supportsUniformBuffers;
  35909. this._dynamic = dynamic;
  35910. this._data = data || [];
  35911. this._uniformLocations = {};
  35912. this._uniformSizes = {};
  35913. this._uniformLocationPointer = 0;
  35914. this._needSync = false;
  35915. if (this._noUBO) {
  35916. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35917. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35918. this.updateFloat = this._updateFloatForEffect;
  35919. this.updateFloat2 = this._updateFloat2ForEffect;
  35920. this.updateFloat3 = this._updateFloat3ForEffect;
  35921. this.updateFloat4 = this._updateFloat4ForEffect;
  35922. this.updateMatrix = this._updateMatrixForEffect;
  35923. this.updateVector3 = this._updateVector3ForEffect;
  35924. this.updateVector4 = this._updateVector4ForEffect;
  35925. this.updateColor3 = this._updateColor3ForEffect;
  35926. this.updateColor4 = this._updateColor4ForEffect;
  35927. }
  35928. else {
  35929. this._engine._uniformBuffers.push(this);
  35930. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35931. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35932. this.updateFloat = this._updateFloatForUniform;
  35933. this.updateFloat2 = this._updateFloat2ForUniform;
  35934. this.updateFloat3 = this._updateFloat3ForUniform;
  35935. this.updateFloat4 = this._updateFloat4ForUniform;
  35936. this.updateMatrix = this._updateMatrixForUniform;
  35937. this.updateVector3 = this._updateVector3ForUniform;
  35938. this.updateVector4 = this._updateVector4ForUniform;
  35939. this.updateColor3 = this._updateColor3ForUniform;
  35940. this.updateColor4 = this._updateColor4ForUniform;
  35941. }
  35942. }
  35943. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35944. // Properties
  35945. /**
  35946. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35947. * or just falling back on setUniformXXX calls.
  35948. */
  35949. get: function () {
  35950. return !this._noUBO;
  35951. },
  35952. enumerable: true,
  35953. configurable: true
  35954. });
  35955. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35956. /**
  35957. * Indicates if the WebGL underlying uniform buffer is in sync
  35958. * with the javascript cache data.
  35959. */
  35960. get: function () {
  35961. return !this._needSync;
  35962. },
  35963. enumerable: true,
  35964. configurable: true
  35965. });
  35966. /**
  35967. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35968. * Also, a dynamic UniformBuffer will disable cache verification and always
  35969. * update the underlying WebGL uniform buffer to the GPU.
  35970. */
  35971. UniformBuffer.prototype.isDynamic = function () {
  35972. return this._dynamic !== undefined;
  35973. };
  35974. /**
  35975. * The data cache on JS side.
  35976. */
  35977. UniformBuffer.prototype.getData = function () {
  35978. return this._bufferData;
  35979. };
  35980. /**
  35981. * The underlying WebGL Uniform buffer.
  35982. */
  35983. UniformBuffer.prototype.getBuffer = function () {
  35984. return this._buffer;
  35985. };
  35986. /**
  35987. * std140 layout specifies how to align data within an UBO structure.
  35988. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35989. * for specs.
  35990. */
  35991. UniformBuffer.prototype._fillAlignment = function (size) {
  35992. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35993. // and 4x4 matrices
  35994. // TODO : change if other types are used
  35995. var alignment;
  35996. if (size <= 2) {
  35997. alignment = size;
  35998. }
  35999. else {
  36000. alignment = 4;
  36001. }
  36002. if ((this._uniformLocationPointer % alignment) !== 0) {
  36003. var oldPointer = this._uniformLocationPointer;
  36004. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36005. var diff = this._uniformLocationPointer - oldPointer;
  36006. for (var i = 0; i < diff; i++) {
  36007. this._data.push(0);
  36008. }
  36009. }
  36010. };
  36011. /**
  36012. * Adds an uniform in the buffer.
  36013. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36014. * for the layout to be correct !
  36015. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36016. * @param {number|number[]} size Data size, or data directly.
  36017. */
  36018. UniformBuffer.prototype.addUniform = function (name, size) {
  36019. if (this._noUBO) {
  36020. return;
  36021. }
  36022. if (this._uniformLocations[name] !== undefined) {
  36023. // Already existing uniform
  36024. return;
  36025. }
  36026. // This function must be called in the order of the shader layout !
  36027. // size can be the size of the uniform, or data directly
  36028. var data;
  36029. if (size instanceof Array) {
  36030. data = size;
  36031. size = data.length;
  36032. }
  36033. else {
  36034. size = size;
  36035. data = [];
  36036. // Fill with zeros
  36037. for (var i = 0; i < size; i++) {
  36038. data.push(0);
  36039. }
  36040. }
  36041. this._fillAlignment(size);
  36042. this._uniformSizes[name] = size;
  36043. this._uniformLocations[name] = this._uniformLocationPointer;
  36044. this._uniformLocationPointer += size;
  36045. for (var i = 0; i < size; i++) {
  36046. this._data.push(data[i]);
  36047. }
  36048. this._needSync = true;
  36049. };
  36050. /**
  36051. * Wrapper for addUniform.
  36052. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36053. * @param {Matrix} mat A 4x4 matrix.
  36054. */
  36055. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36056. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36057. };
  36058. /**
  36059. * Wrapper for addUniform.
  36060. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36061. * @param {number} x
  36062. * @param {number} y
  36063. */
  36064. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36065. var temp = [x, y];
  36066. this.addUniform(name, temp);
  36067. };
  36068. /**
  36069. * Wrapper for addUniform.
  36070. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36071. * @param {number} x
  36072. * @param {number} y
  36073. * @param {number} z
  36074. */
  36075. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36076. var temp = [x, y, z];
  36077. this.addUniform(name, temp);
  36078. };
  36079. /**
  36080. * Wrapper for addUniform.
  36081. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36082. * @param {Color3} color
  36083. */
  36084. UniformBuffer.prototype.addColor3 = function (name, color) {
  36085. var temp = new Array();
  36086. color.toArray(temp);
  36087. this.addUniform(name, temp);
  36088. };
  36089. /**
  36090. * Wrapper for addUniform.
  36091. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36092. * @param {Color3} color
  36093. * @param {number} alpha
  36094. */
  36095. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36096. var temp = new Array();
  36097. color.toArray(temp);
  36098. temp.push(alpha);
  36099. this.addUniform(name, temp);
  36100. };
  36101. /**
  36102. * Wrapper for addUniform.
  36103. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36104. * @param {Vector3} vector
  36105. */
  36106. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36107. var temp = new Array();
  36108. vector.toArray(temp);
  36109. this.addUniform(name, temp);
  36110. };
  36111. /**
  36112. * Wrapper for addUniform.
  36113. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36114. */
  36115. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36116. this.addUniform(name, 12);
  36117. };
  36118. /**
  36119. * Wrapper for addUniform.
  36120. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36121. */
  36122. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36123. this.addUniform(name, 8);
  36124. };
  36125. /**
  36126. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36127. */
  36128. UniformBuffer.prototype.create = function () {
  36129. if (this._noUBO) {
  36130. return;
  36131. }
  36132. if (this._buffer) {
  36133. return; // nothing to do
  36134. }
  36135. // See spec, alignment must be filled as a vec4
  36136. this._fillAlignment(4);
  36137. this._bufferData = new Float32Array(this._data);
  36138. this._rebuild();
  36139. this._needSync = true;
  36140. };
  36141. /** @hidden */
  36142. UniformBuffer.prototype._rebuild = function () {
  36143. if (this._noUBO) {
  36144. return;
  36145. }
  36146. if (this._dynamic) {
  36147. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36148. }
  36149. else {
  36150. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36151. }
  36152. };
  36153. /**
  36154. * Updates the WebGL Uniform Buffer on the GPU.
  36155. * If the `dynamic` flag is set to true, no cache comparison is done.
  36156. * Otherwise, the buffer will be updated only if the cache differs.
  36157. */
  36158. UniformBuffer.prototype.update = function () {
  36159. if (!this._buffer) {
  36160. this.create();
  36161. return;
  36162. }
  36163. if (!this._dynamic && !this._needSync) {
  36164. return;
  36165. }
  36166. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36167. this._needSync = false;
  36168. };
  36169. /**
  36170. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36171. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36172. * @param {number[]|Float32Array} data Flattened data
  36173. * @param {number} size Size of the data.
  36174. */
  36175. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36176. var location = this._uniformLocations[uniformName];
  36177. if (location === undefined) {
  36178. if (this._buffer) {
  36179. // Cannot add an uniform if the buffer is already created
  36180. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36181. return;
  36182. }
  36183. this.addUniform(uniformName, size);
  36184. location = this._uniformLocations[uniformName];
  36185. }
  36186. if (!this._buffer) {
  36187. this.create();
  36188. }
  36189. if (!this._dynamic) {
  36190. // Cache for static uniform buffers
  36191. var changed = false;
  36192. for (var i = 0; i < size; i++) {
  36193. if (this._bufferData[location + i] !== data[i]) {
  36194. changed = true;
  36195. this._bufferData[location + i] = data[i];
  36196. }
  36197. }
  36198. this._needSync = this._needSync || changed;
  36199. }
  36200. else {
  36201. // No cache for dynamic
  36202. for (var i = 0; i < size; i++) {
  36203. this._bufferData[location + i] = data[i];
  36204. }
  36205. }
  36206. };
  36207. // Update methods
  36208. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36209. // To match std140, matrix must be realigned
  36210. for (var i = 0; i < 3; i++) {
  36211. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36212. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36213. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36214. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36215. }
  36216. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36217. };
  36218. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36219. this._currentEffect.setMatrix3x3(name, matrix);
  36220. };
  36221. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36222. this._currentEffect.setMatrix2x2(name, matrix);
  36223. };
  36224. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36225. // To match std140, matrix must be realigned
  36226. for (var i = 0; i < 2; i++) {
  36227. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36228. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36229. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36230. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36231. }
  36232. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36233. };
  36234. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36235. this._currentEffect.setFloat(name, x);
  36236. };
  36237. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36238. UniformBuffer._tempBuffer[0] = x;
  36239. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36240. };
  36241. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36242. if (suffix === void 0) { suffix = ""; }
  36243. this._currentEffect.setFloat2(name + suffix, x, y);
  36244. };
  36245. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36246. if (suffix === void 0) { suffix = ""; }
  36247. UniformBuffer._tempBuffer[0] = x;
  36248. UniformBuffer._tempBuffer[1] = y;
  36249. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36250. };
  36251. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36252. if (suffix === void 0) { suffix = ""; }
  36253. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36254. };
  36255. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36256. if (suffix === void 0) { suffix = ""; }
  36257. UniformBuffer._tempBuffer[0] = x;
  36258. UniformBuffer._tempBuffer[1] = y;
  36259. UniformBuffer._tempBuffer[2] = z;
  36260. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36261. };
  36262. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36263. if (suffix === void 0) { suffix = ""; }
  36264. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36265. };
  36266. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36267. if (suffix === void 0) { suffix = ""; }
  36268. UniformBuffer._tempBuffer[0] = x;
  36269. UniformBuffer._tempBuffer[1] = y;
  36270. UniformBuffer._tempBuffer[2] = z;
  36271. UniformBuffer._tempBuffer[3] = w;
  36272. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36273. };
  36274. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36275. this._currentEffect.setMatrix(name, mat);
  36276. };
  36277. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36278. this.updateUniform(name, mat.toArray(), 16);
  36279. };
  36280. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36281. this._currentEffect.setVector3(name, vector);
  36282. };
  36283. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36284. vector.toArray(UniformBuffer._tempBuffer);
  36285. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36286. };
  36287. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36288. this._currentEffect.setVector4(name, vector);
  36289. };
  36290. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36291. vector.toArray(UniformBuffer._tempBuffer);
  36292. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36293. };
  36294. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36295. if (suffix === void 0) { suffix = ""; }
  36296. this._currentEffect.setColor3(name + suffix, color);
  36297. };
  36298. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36299. if (suffix === void 0) { suffix = ""; }
  36300. color.toArray(UniformBuffer._tempBuffer);
  36301. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36302. };
  36303. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36304. if (suffix === void 0) { suffix = ""; }
  36305. this._currentEffect.setColor4(name + suffix, color, alpha);
  36306. };
  36307. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36308. if (suffix === void 0) { suffix = ""; }
  36309. color.toArray(UniformBuffer._tempBuffer);
  36310. UniformBuffer._tempBuffer[3] = alpha;
  36311. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36312. };
  36313. /**
  36314. * Sets a sampler uniform on the effect.
  36315. * @param {string} name Name of the sampler.
  36316. * @param {Texture} texture
  36317. */
  36318. UniformBuffer.prototype.setTexture = function (name, texture) {
  36319. this._currentEffect.setTexture(name, texture);
  36320. };
  36321. /**
  36322. * Directly updates the value of the uniform in the cache AND on the GPU.
  36323. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36324. * @param {number[]|Float32Array} data Flattened data
  36325. */
  36326. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36327. this.updateUniform(uniformName, data, data.length);
  36328. this.update();
  36329. };
  36330. /**
  36331. * Binds this uniform buffer to an effect.
  36332. * @param {Effect} effect
  36333. * @param {string} name Name of the uniform block in the shader.
  36334. */
  36335. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36336. this._currentEffect = effect;
  36337. if (this._noUBO || !this._buffer) {
  36338. return;
  36339. }
  36340. effect.bindUniformBuffer(this._buffer, name);
  36341. };
  36342. /**
  36343. * Disposes the uniform buffer.
  36344. */
  36345. UniformBuffer.prototype.dispose = function () {
  36346. if (this._noUBO) {
  36347. return;
  36348. }
  36349. var index = this._engine._uniformBuffers.indexOf(this);
  36350. if (index !== -1) {
  36351. this._engine._uniformBuffers.splice(index, 1);
  36352. }
  36353. if (!this._buffer) {
  36354. return;
  36355. }
  36356. if (this._engine._releaseBuffer(this._buffer)) {
  36357. this._buffer = null;
  36358. }
  36359. };
  36360. // Pool for avoiding memory leaks
  36361. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36362. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36363. return UniformBuffer;
  36364. }());
  36365. BABYLON.UniformBuffer = UniformBuffer;
  36366. })(BABYLON || (BABYLON = {}));
  36367. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36368. var BABYLON;
  36369. (function (BABYLON) {
  36370. /**
  36371. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36372. */
  36373. var VertexData = /** @class */ (function () {
  36374. function VertexData() {
  36375. }
  36376. /**
  36377. * Uses the passed data array to set the set the values for the specified kind of data
  36378. * @param data a linear array of floating numbers
  36379. * @param kind the type of data that is being set, eg positions, colors etc
  36380. */
  36381. VertexData.prototype.set = function (data, kind) {
  36382. switch (kind) {
  36383. case BABYLON.VertexBuffer.PositionKind:
  36384. this.positions = data;
  36385. break;
  36386. case BABYLON.VertexBuffer.NormalKind:
  36387. this.normals = data;
  36388. break;
  36389. case BABYLON.VertexBuffer.TangentKind:
  36390. this.tangents = data;
  36391. break;
  36392. case BABYLON.VertexBuffer.UVKind:
  36393. this.uvs = data;
  36394. break;
  36395. case BABYLON.VertexBuffer.UV2Kind:
  36396. this.uvs2 = data;
  36397. break;
  36398. case BABYLON.VertexBuffer.UV3Kind:
  36399. this.uvs3 = data;
  36400. break;
  36401. case BABYLON.VertexBuffer.UV4Kind:
  36402. this.uvs4 = data;
  36403. break;
  36404. case BABYLON.VertexBuffer.UV5Kind:
  36405. this.uvs5 = data;
  36406. break;
  36407. case BABYLON.VertexBuffer.UV6Kind:
  36408. this.uvs6 = data;
  36409. break;
  36410. case BABYLON.VertexBuffer.ColorKind:
  36411. this.colors = data;
  36412. break;
  36413. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36414. this.matricesIndices = data;
  36415. break;
  36416. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36417. this.matricesWeights = data;
  36418. break;
  36419. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36420. this.matricesIndicesExtra = data;
  36421. break;
  36422. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36423. this.matricesWeightsExtra = data;
  36424. break;
  36425. }
  36426. };
  36427. /**
  36428. * Associates the vertexData to the passed Mesh.
  36429. * Sets it as updatable or not (default `false`)
  36430. * @param mesh the mesh the vertexData is applied to
  36431. * @param updatable when used and having the value true allows new data to update the vertexData
  36432. * @returns the VertexData
  36433. */
  36434. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36435. this._applyTo(mesh, updatable);
  36436. return this;
  36437. };
  36438. /**
  36439. * Associates the vertexData to the passed Geometry.
  36440. * Sets it as updatable or not (default `false`)
  36441. * @param geometry the geometry the vertexData is applied to
  36442. * @param updatable when used and having the value true allows new data to update the vertexData
  36443. * @returns VertexData
  36444. */
  36445. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36446. this._applyTo(geometry, updatable);
  36447. return this;
  36448. };
  36449. /**
  36450. * Updates the associated mesh
  36451. * @param mesh the mesh to be updated
  36452. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36453. * @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
  36454. * @returns VertexData
  36455. */
  36456. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36457. this._update(mesh);
  36458. return this;
  36459. };
  36460. /**
  36461. * Updates the associated geometry
  36462. * @param geometry the geometry to be updated
  36463. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36464. * @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
  36465. * @returns VertexData.
  36466. */
  36467. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36468. this._update(geometry);
  36469. return this;
  36470. };
  36471. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36472. if (updatable === void 0) { updatable = false; }
  36473. if (this.positions) {
  36474. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36475. }
  36476. if (this.normals) {
  36477. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36478. }
  36479. if (this.tangents) {
  36480. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36481. }
  36482. if (this.uvs) {
  36483. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36484. }
  36485. if (this.uvs2) {
  36486. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36487. }
  36488. if (this.uvs3) {
  36489. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36490. }
  36491. if (this.uvs4) {
  36492. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36493. }
  36494. if (this.uvs5) {
  36495. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36496. }
  36497. if (this.uvs6) {
  36498. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36499. }
  36500. if (this.colors) {
  36501. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36502. }
  36503. if (this.matricesIndices) {
  36504. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36505. }
  36506. if (this.matricesWeights) {
  36507. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36508. }
  36509. if (this.matricesIndicesExtra) {
  36510. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36511. }
  36512. if (this.matricesWeightsExtra) {
  36513. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36514. }
  36515. if (this.indices) {
  36516. meshOrGeometry.setIndices(this.indices, null, updatable);
  36517. }
  36518. else {
  36519. meshOrGeometry.setIndices([], null);
  36520. }
  36521. return this;
  36522. };
  36523. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36524. if (this.positions) {
  36525. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36526. }
  36527. if (this.normals) {
  36528. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36529. }
  36530. if (this.tangents) {
  36531. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36532. }
  36533. if (this.uvs) {
  36534. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36535. }
  36536. if (this.uvs2) {
  36537. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36538. }
  36539. if (this.uvs3) {
  36540. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36541. }
  36542. if (this.uvs4) {
  36543. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36544. }
  36545. if (this.uvs5) {
  36546. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36547. }
  36548. if (this.uvs6) {
  36549. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36550. }
  36551. if (this.colors) {
  36552. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36553. }
  36554. if (this.matricesIndices) {
  36555. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36556. }
  36557. if (this.matricesWeights) {
  36558. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36559. }
  36560. if (this.matricesIndicesExtra) {
  36561. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36562. }
  36563. if (this.matricesWeightsExtra) {
  36564. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36565. }
  36566. if (this.indices) {
  36567. meshOrGeometry.setIndices(this.indices, null);
  36568. }
  36569. return this;
  36570. };
  36571. /**
  36572. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36573. * @param matrix the transforming matrix
  36574. * @returns the VertexData
  36575. */
  36576. VertexData.prototype.transform = function (matrix) {
  36577. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36578. var transformed = BABYLON.Vector3.Zero();
  36579. var index;
  36580. if (this.positions) {
  36581. var position = BABYLON.Vector3.Zero();
  36582. for (index = 0; index < this.positions.length; index += 3) {
  36583. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36584. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36585. this.positions[index] = transformed.x;
  36586. this.positions[index + 1] = transformed.y;
  36587. this.positions[index + 2] = transformed.z;
  36588. }
  36589. }
  36590. if (this.normals) {
  36591. var normal = BABYLON.Vector3.Zero();
  36592. for (index = 0; index < this.normals.length; index += 3) {
  36593. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36594. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36595. this.normals[index] = transformed.x;
  36596. this.normals[index + 1] = transformed.y;
  36597. this.normals[index + 2] = transformed.z;
  36598. }
  36599. }
  36600. if (this.tangents) {
  36601. var tangent = BABYLON.Vector4.Zero();
  36602. var tangentTransformed = BABYLON.Vector4.Zero();
  36603. for (index = 0; index < this.tangents.length; index += 4) {
  36604. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36605. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36606. this.tangents[index] = tangentTransformed.x;
  36607. this.tangents[index + 1] = tangentTransformed.y;
  36608. this.tangents[index + 2] = tangentTransformed.z;
  36609. this.tangents[index + 3] = tangentTransformed.w;
  36610. }
  36611. }
  36612. if (flip && this.indices) {
  36613. for (index = 0; index < this.indices.length; index += 3) {
  36614. var tmp = this.indices[index + 1];
  36615. this.indices[index + 1] = this.indices[index + 2];
  36616. this.indices[index + 2] = tmp;
  36617. }
  36618. }
  36619. return this;
  36620. };
  36621. /**
  36622. * Merges the passed VertexData into the current one
  36623. * @param other the VertexData to be merged into the current one
  36624. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36625. * @returns the modified VertexData
  36626. */
  36627. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36628. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36629. this._validate();
  36630. other._validate();
  36631. if (!this.normals !== !other.normals ||
  36632. !this.tangents !== !other.tangents ||
  36633. !this.uvs !== !other.uvs ||
  36634. !this.uvs2 !== !other.uvs2 ||
  36635. !this.uvs3 !== !other.uvs3 ||
  36636. !this.uvs4 !== !other.uvs4 ||
  36637. !this.uvs5 !== !other.uvs5 ||
  36638. !this.uvs6 !== !other.uvs6 ||
  36639. !this.colors !== !other.colors ||
  36640. !this.matricesIndices !== !other.matricesIndices ||
  36641. !this.matricesWeights !== !other.matricesWeights ||
  36642. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36643. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36644. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36645. }
  36646. if (other.indices) {
  36647. if (!this.indices) {
  36648. this.indices = [];
  36649. }
  36650. var offset = this.positions ? this.positions.length / 3 : 0;
  36651. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36652. if (isSrcTypedArray) {
  36653. var len = this.indices.length + other.indices.length;
  36654. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36655. temp.set(this.indices);
  36656. var decal = this.indices.length;
  36657. for (var index = 0; index < other.indices.length; index++) {
  36658. temp[decal + index] = other.indices[index] + offset;
  36659. }
  36660. this.indices = temp;
  36661. }
  36662. else {
  36663. for (var index = 0; index < other.indices.length; index++) {
  36664. this.indices.push(other.indices[index] + offset);
  36665. }
  36666. }
  36667. }
  36668. this.positions = this._mergeElement(this.positions, other.positions);
  36669. this.normals = this._mergeElement(this.normals, other.normals);
  36670. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36671. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36672. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36673. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36674. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36675. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36676. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36677. this.colors = this._mergeElement(this.colors, other.colors);
  36678. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36679. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36680. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36681. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36682. return this;
  36683. };
  36684. VertexData.prototype._mergeElement = function (source, other) {
  36685. if (!source) {
  36686. return other;
  36687. }
  36688. if (!other) {
  36689. return source;
  36690. }
  36691. var len = other.length + source.length;
  36692. var isSrcTypedArray = source instanceof Float32Array;
  36693. var isOthTypedArray = other instanceof Float32Array;
  36694. // use non-loop method when the source is Float32Array
  36695. if (isSrcTypedArray) {
  36696. var ret32 = new Float32Array(len);
  36697. ret32.set(source);
  36698. ret32.set(other, source.length);
  36699. return ret32;
  36700. // source is number[], when other is also use concat
  36701. }
  36702. else if (!isOthTypedArray) {
  36703. return source.concat(other);
  36704. // source is a number[], but other is a Float32Array, loop required
  36705. }
  36706. else {
  36707. var ret = source.slice(0); // copy source to a separate array
  36708. for (var i = 0, len = other.length; i < len; i++) {
  36709. ret.push(other[i]);
  36710. }
  36711. return ret;
  36712. }
  36713. };
  36714. VertexData.prototype._validate = function () {
  36715. if (!this.positions) {
  36716. throw new Error("Positions are required");
  36717. }
  36718. var getElementCount = function (kind, values) {
  36719. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36720. if ((values.length % stride) !== 0) {
  36721. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36722. }
  36723. return values.length / stride;
  36724. };
  36725. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36726. var validateElementCount = function (kind, values) {
  36727. var elementCount = getElementCount(kind, values);
  36728. if (elementCount !== positionsElementCount) {
  36729. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36730. }
  36731. };
  36732. if (this.normals)
  36733. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36734. if (this.tangents)
  36735. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36736. if (this.uvs)
  36737. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36738. if (this.uvs2)
  36739. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36740. if (this.uvs3)
  36741. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36742. if (this.uvs4)
  36743. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36744. if (this.uvs5)
  36745. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36746. if (this.uvs6)
  36747. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36748. if (this.colors)
  36749. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36750. if (this.matricesIndices)
  36751. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36752. if (this.matricesWeights)
  36753. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36754. if (this.matricesIndicesExtra)
  36755. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36756. if (this.matricesWeightsExtra)
  36757. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36758. };
  36759. /**
  36760. * Serializes the VertexData
  36761. * @returns a serialized object
  36762. */
  36763. VertexData.prototype.serialize = function () {
  36764. var serializationObject = this.serialize();
  36765. if (this.positions) {
  36766. serializationObject.positions = this.positions;
  36767. }
  36768. if (this.normals) {
  36769. serializationObject.normals = this.normals;
  36770. }
  36771. if (this.tangents) {
  36772. serializationObject.tangents = this.tangents;
  36773. }
  36774. if (this.uvs) {
  36775. serializationObject.uvs = this.uvs;
  36776. }
  36777. if (this.uvs2) {
  36778. serializationObject.uvs2 = this.uvs2;
  36779. }
  36780. if (this.uvs3) {
  36781. serializationObject.uvs3 = this.uvs3;
  36782. }
  36783. if (this.uvs4) {
  36784. serializationObject.uvs4 = this.uvs4;
  36785. }
  36786. if (this.uvs5) {
  36787. serializationObject.uvs5 = this.uvs5;
  36788. }
  36789. if (this.uvs6) {
  36790. serializationObject.uvs6 = this.uvs6;
  36791. }
  36792. if (this.colors) {
  36793. serializationObject.colors = this.colors;
  36794. }
  36795. if (this.matricesIndices) {
  36796. serializationObject.matricesIndices = this.matricesIndices;
  36797. serializationObject.matricesIndices._isExpanded = true;
  36798. }
  36799. if (this.matricesWeights) {
  36800. serializationObject.matricesWeights = this.matricesWeights;
  36801. }
  36802. if (this.matricesIndicesExtra) {
  36803. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36804. serializationObject.matricesIndicesExtra._isExpanded = true;
  36805. }
  36806. if (this.matricesWeightsExtra) {
  36807. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36808. }
  36809. serializationObject.indices = this.indices;
  36810. return serializationObject;
  36811. };
  36812. // Statics
  36813. /**
  36814. * Extracts the vertexData from a mesh
  36815. * @param mesh the mesh from which to extract the VertexData
  36816. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36817. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36818. * @returns the object VertexData associated to the passed mesh
  36819. */
  36820. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36821. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36822. };
  36823. /**
  36824. * Extracts the vertexData from the geometry
  36825. * @param geometry the geometry from which to extract the VertexData
  36826. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36827. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36828. * @returns the object VertexData associated to the passed mesh
  36829. */
  36830. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36831. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36832. };
  36833. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36834. var result = new VertexData();
  36835. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36836. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36837. }
  36838. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36839. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36840. }
  36841. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36842. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36843. }
  36844. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36845. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36846. }
  36847. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36848. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36849. }
  36850. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36851. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36852. }
  36853. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36854. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36855. }
  36856. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36857. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36858. }
  36859. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36860. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36861. }
  36862. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36863. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36864. }
  36865. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36866. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36867. }
  36868. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36869. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36870. }
  36871. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36872. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36873. }
  36874. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36875. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36876. }
  36877. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36878. return result;
  36879. };
  36880. /**
  36881. * Creates the VertexData for a Ribbon
  36882. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36883. * * pathArray array of paths, each of which an array of successive Vector3
  36884. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36885. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36886. * * 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
  36887. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36888. * * 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)
  36889. * * 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)
  36890. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36891. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36892. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36893. * @returns the VertexData of the ribbon
  36894. */
  36895. VertexData.CreateRibbon = function (options) {
  36896. var pathArray = options.pathArray;
  36897. var closeArray = options.closeArray || false;
  36898. var closePath = options.closePath || false;
  36899. var invertUV = options.invertUV || false;
  36900. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36901. var offset = options.offset || defaultOffset;
  36902. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36903. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36904. var customUV = options.uvs;
  36905. var customColors = options.colors;
  36906. var positions = [];
  36907. var indices = [];
  36908. var normals = [];
  36909. var uvs = [];
  36910. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36911. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36912. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36913. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36914. var minlg; // minimal length among all paths from pathArray
  36915. var lg = []; // array of path lengths : nb of vertex per path
  36916. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36917. var p; // path iterator
  36918. var i; // point iterator
  36919. var j; // point iterator
  36920. // if single path in pathArray
  36921. if (pathArray.length < 2) {
  36922. var ar1 = [];
  36923. var ar2 = [];
  36924. for (i = 0; i < pathArray[0].length - offset; i++) {
  36925. ar1.push(pathArray[0][i]);
  36926. ar2.push(pathArray[0][i + offset]);
  36927. }
  36928. pathArray = [ar1, ar2];
  36929. }
  36930. // positions and horizontal distances (u)
  36931. var idc = 0;
  36932. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36933. var path;
  36934. var l;
  36935. minlg = pathArray[0].length;
  36936. var vectlg;
  36937. var dist;
  36938. for (p = 0; p < pathArray.length; p++) {
  36939. uTotalDistance[p] = 0;
  36940. us[p] = [0];
  36941. path = pathArray[p];
  36942. l = path.length;
  36943. minlg = (minlg < l) ? minlg : l;
  36944. j = 0;
  36945. while (j < l) {
  36946. positions.push(path[j].x, path[j].y, path[j].z);
  36947. if (j > 0) {
  36948. vectlg = path[j].subtract(path[j - 1]).length();
  36949. dist = vectlg + uTotalDistance[p];
  36950. us[p].push(dist);
  36951. uTotalDistance[p] = dist;
  36952. }
  36953. j++;
  36954. }
  36955. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36956. j--;
  36957. positions.push(path[0].x, path[0].y, path[0].z);
  36958. vectlg = path[j].subtract(path[0]).length();
  36959. dist = vectlg + uTotalDistance[p];
  36960. us[p].push(dist);
  36961. uTotalDistance[p] = dist;
  36962. }
  36963. lg[p] = l + closePathCorr;
  36964. idx[p] = idc;
  36965. idc += (l + closePathCorr);
  36966. }
  36967. // vertical distances (v)
  36968. var path1;
  36969. var path2;
  36970. var vertex1 = null;
  36971. var vertex2 = null;
  36972. for (i = 0; i < minlg + closePathCorr; i++) {
  36973. vTotalDistance[i] = 0;
  36974. vs[i] = [0];
  36975. for (p = 0; p < pathArray.length - 1; p++) {
  36976. path1 = pathArray[p];
  36977. path2 = pathArray[p + 1];
  36978. if (i === minlg) { // closePath
  36979. vertex1 = path1[0];
  36980. vertex2 = path2[0];
  36981. }
  36982. else {
  36983. vertex1 = path1[i];
  36984. vertex2 = path2[i];
  36985. }
  36986. vectlg = vertex2.subtract(vertex1).length();
  36987. dist = vectlg + vTotalDistance[i];
  36988. vs[i].push(dist);
  36989. vTotalDistance[i] = dist;
  36990. }
  36991. if (closeArray && vertex2 && vertex1) {
  36992. path1 = pathArray[p];
  36993. path2 = pathArray[0];
  36994. if (i === minlg) { // closePath
  36995. vertex2 = path2[0];
  36996. }
  36997. vectlg = vertex2.subtract(vertex1).length();
  36998. dist = vectlg + vTotalDistance[i];
  36999. vTotalDistance[i] = dist;
  37000. }
  37001. }
  37002. // uvs
  37003. var u;
  37004. var v;
  37005. if (customUV) {
  37006. for (p = 0; p < customUV.length; p++) {
  37007. uvs.push(customUV[p].x, customUV[p].y);
  37008. }
  37009. }
  37010. else {
  37011. for (p = 0; p < pathArray.length; p++) {
  37012. for (i = 0; i < minlg + closePathCorr; i++) {
  37013. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37014. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37015. if (invertUV) {
  37016. uvs.push(v, u);
  37017. }
  37018. else {
  37019. uvs.push(u, v);
  37020. }
  37021. }
  37022. }
  37023. }
  37024. // indices
  37025. p = 0; // path index
  37026. var pi = 0; // positions array index
  37027. var l1 = lg[p] - 1; // path1 length
  37028. var l2 = lg[p + 1] - 1; // path2 length
  37029. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37030. var shft = idx[1] - idx[0]; // shift
  37031. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37032. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37033. // 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
  37034. indices.push(pi, pi + shft, pi + 1);
  37035. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37036. pi += 1;
  37037. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37038. p++;
  37039. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37040. shft = idx[0] - idx[p];
  37041. l1 = lg[p] - 1;
  37042. l2 = lg[0] - 1;
  37043. }
  37044. else {
  37045. shft = idx[p + 1] - idx[p];
  37046. l1 = lg[p] - 1;
  37047. l2 = lg[p + 1] - 1;
  37048. }
  37049. pi = idx[p];
  37050. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37051. }
  37052. }
  37053. // normals
  37054. VertexData.ComputeNormals(positions, indices, normals);
  37055. if (closePath) { // update both the first and last vertex normals to their average value
  37056. var indexFirst = 0;
  37057. var indexLast = 0;
  37058. for (p = 0; p < pathArray.length; p++) {
  37059. indexFirst = idx[p] * 3;
  37060. if (p + 1 < pathArray.length) {
  37061. indexLast = (idx[p + 1] - 1) * 3;
  37062. }
  37063. else {
  37064. indexLast = normals.length - 3;
  37065. }
  37066. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37067. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37068. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37069. normals[indexLast] = normals[indexFirst];
  37070. normals[indexLast + 1] = normals[indexFirst + 1];
  37071. normals[indexLast + 2] = normals[indexFirst + 2];
  37072. }
  37073. }
  37074. // sides
  37075. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37076. // Colors
  37077. var colors = null;
  37078. if (customColors) {
  37079. colors = new Float32Array(customColors.length * 4);
  37080. for (var c = 0; c < customColors.length; c++) {
  37081. colors[c * 4] = customColors[c].r;
  37082. colors[c * 4 + 1] = customColors[c].g;
  37083. colors[c * 4 + 2] = customColors[c].b;
  37084. colors[c * 4 + 3] = customColors[c].a;
  37085. }
  37086. }
  37087. // Result
  37088. var vertexData = new VertexData();
  37089. var positions32 = new Float32Array(positions);
  37090. var normals32 = new Float32Array(normals);
  37091. var uvs32 = new Float32Array(uvs);
  37092. vertexData.indices = indices;
  37093. vertexData.positions = positions32;
  37094. vertexData.normals = normals32;
  37095. vertexData.uvs = uvs32;
  37096. if (colors) {
  37097. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37098. }
  37099. if (closePath) {
  37100. vertexData._idx = idx;
  37101. }
  37102. return vertexData;
  37103. };
  37104. /**
  37105. * Creates the VertexData for a box
  37106. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37107. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37108. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37109. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37110. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37111. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37112. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37113. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37114. * * 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)
  37115. * * 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)
  37116. * @returns the VertexData of the box
  37117. */
  37118. VertexData.CreateBox = function (options) {
  37119. var normalsSource = [
  37120. new BABYLON.Vector3(0, 0, 1),
  37121. new BABYLON.Vector3(0, 0, -1),
  37122. new BABYLON.Vector3(1, 0, 0),
  37123. new BABYLON.Vector3(-1, 0, 0),
  37124. new BABYLON.Vector3(0, 1, 0),
  37125. new BABYLON.Vector3(0, -1, 0)
  37126. ];
  37127. var indices = [];
  37128. var positions = [];
  37129. var normals = [];
  37130. var uvs = [];
  37131. var width = options.width || options.size || 1;
  37132. var height = options.height || options.size || 1;
  37133. var depth = options.depth || options.size || 1;
  37134. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37135. var faceUV = options.faceUV || new Array(6);
  37136. var faceColors = options.faceColors;
  37137. var colors = [];
  37138. // default face colors and UV if undefined
  37139. for (var f = 0; f < 6; f++) {
  37140. if (faceUV[f] === undefined) {
  37141. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37142. }
  37143. if (faceColors && faceColors[f] === undefined) {
  37144. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37145. }
  37146. }
  37147. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37148. // Create each face in turn.
  37149. for (var index = 0; index < normalsSource.length; index++) {
  37150. var normal = normalsSource[index];
  37151. // Get two vectors perpendicular to the face normal and to each other.
  37152. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37153. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37154. // Six indices (two triangles) per face.
  37155. var verticesLength = positions.length / 3;
  37156. indices.push(verticesLength);
  37157. indices.push(verticesLength + 1);
  37158. indices.push(verticesLength + 2);
  37159. indices.push(verticesLength);
  37160. indices.push(verticesLength + 2);
  37161. indices.push(verticesLength + 3);
  37162. // Four vertices per face.
  37163. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37164. positions.push(vertex.x, vertex.y, vertex.z);
  37165. normals.push(normal.x, normal.y, normal.z);
  37166. uvs.push(faceUV[index].z, faceUV[index].w);
  37167. if (faceColors) {
  37168. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37169. }
  37170. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37171. positions.push(vertex.x, vertex.y, vertex.z);
  37172. normals.push(normal.x, normal.y, normal.z);
  37173. uvs.push(faceUV[index].x, faceUV[index].w);
  37174. if (faceColors) {
  37175. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37176. }
  37177. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37178. positions.push(vertex.x, vertex.y, vertex.z);
  37179. normals.push(normal.x, normal.y, normal.z);
  37180. uvs.push(faceUV[index].x, faceUV[index].y);
  37181. if (faceColors) {
  37182. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37183. }
  37184. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37185. positions.push(vertex.x, vertex.y, vertex.z);
  37186. normals.push(normal.x, normal.y, normal.z);
  37187. uvs.push(faceUV[index].z, faceUV[index].y);
  37188. if (faceColors) {
  37189. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37190. }
  37191. }
  37192. // sides
  37193. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37194. // Result
  37195. var vertexData = new VertexData();
  37196. vertexData.indices = indices;
  37197. vertexData.positions = positions;
  37198. vertexData.normals = normals;
  37199. vertexData.uvs = uvs;
  37200. if (faceColors) {
  37201. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37202. vertexData.colors = totalColors;
  37203. }
  37204. return vertexData;
  37205. };
  37206. /**
  37207. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37208. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37209. * * segments sets the number of horizontal strips optional, default 32
  37210. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37211. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37212. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37213. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37214. * * 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
  37215. * * 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
  37216. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37217. * * 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)
  37218. * * 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)
  37219. * @returns the VertexData of the ellipsoid
  37220. */
  37221. VertexData.CreateSphere = function (options) {
  37222. var segments = options.segments || 32;
  37223. var diameterX = options.diameterX || options.diameter || 1;
  37224. var diameterY = options.diameterY || options.diameter || 1;
  37225. var diameterZ = options.diameterZ || options.diameter || 1;
  37226. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37227. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37228. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37229. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37230. var totalZRotationSteps = 2 + segments;
  37231. var totalYRotationSteps = 2 * totalZRotationSteps;
  37232. var indices = [];
  37233. var positions = [];
  37234. var normals = [];
  37235. var uvs = [];
  37236. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37237. var normalizedZ = zRotationStep / totalZRotationSteps;
  37238. var angleZ = normalizedZ * Math.PI * slice;
  37239. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37240. var normalizedY = yRotationStep / totalYRotationSteps;
  37241. var angleY = normalizedY * Math.PI * 2 * arc;
  37242. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37243. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37244. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37245. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37246. var vertex = complete.multiply(radius);
  37247. var normal = complete.divide(radius).normalize();
  37248. positions.push(vertex.x, vertex.y, vertex.z);
  37249. normals.push(normal.x, normal.y, normal.z);
  37250. uvs.push(normalizedY, normalizedZ);
  37251. }
  37252. if (zRotationStep > 0) {
  37253. var verticesCount = positions.length / 3;
  37254. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37255. indices.push((firstIndex));
  37256. indices.push((firstIndex + 1));
  37257. indices.push(firstIndex + totalYRotationSteps + 1);
  37258. indices.push((firstIndex + totalYRotationSteps + 1));
  37259. indices.push((firstIndex + 1));
  37260. indices.push((firstIndex + totalYRotationSteps + 2));
  37261. }
  37262. }
  37263. }
  37264. // Sides
  37265. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37266. // Result
  37267. var vertexData = new VertexData();
  37268. vertexData.indices = indices;
  37269. vertexData.positions = positions;
  37270. vertexData.normals = normals;
  37271. vertexData.uvs = uvs;
  37272. return vertexData;
  37273. };
  37274. /**
  37275. * Creates the VertexData for a cylinder, cone or prism
  37276. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37277. * * height sets the height (y direction) of the cylinder, optional, default 2
  37278. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37279. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37280. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37281. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37282. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37283. * * 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
  37284. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37285. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37286. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37287. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37288. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37289. * * 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)
  37290. * * 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)
  37291. * @returns the VertexData of the cylinder, cone or prism
  37292. */
  37293. VertexData.CreateCylinder = function (options) {
  37294. var height = options.height || 2;
  37295. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37296. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37297. var tessellation = options.tessellation || 24;
  37298. var subdivisions = options.subdivisions || 1;
  37299. var hasRings = options.hasRings ? true : false;
  37300. var enclose = options.enclose ? true : false;
  37301. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37302. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37303. var faceUV = options.faceUV || new Array(3);
  37304. var faceColors = options.faceColors;
  37305. // default face colors and UV if undefined
  37306. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37307. var ringNb = (hasRings) ? subdivisions : 1;
  37308. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37309. var f;
  37310. for (f = 0; f < surfaceNb; f++) {
  37311. if (faceColors && faceColors[f] === undefined) {
  37312. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37313. }
  37314. }
  37315. for (f = 0; f < surfaceNb; f++) {
  37316. if (faceUV && faceUV[f] === undefined) {
  37317. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37318. }
  37319. }
  37320. var indices = new Array();
  37321. var positions = new Array();
  37322. var normals = new Array();
  37323. var uvs = new Array();
  37324. var colors = new Array();
  37325. var angle_step = Math.PI * 2 * arc / tessellation;
  37326. var angle;
  37327. var h;
  37328. var radius;
  37329. var tan = (diameterBottom - diameterTop) / 2 / height;
  37330. var ringVertex = BABYLON.Vector3.Zero();
  37331. var ringNormal = BABYLON.Vector3.Zero();
  37332. var ringFirstVertex = BABYLON.Vector3.Zero();
  37333. var ringFirstNormal = BABYLON.Vector3.Zero();
  37334. var quadNormal = BABYLON.Vector3.Zero();
  37335. var Y = BABYLON.Axis.Y;
  37336. // positions, normals, uvs
  37337. var i;
  37338. var j;
  37339. var r;
  37340. var ringIdx = 1;
  37341. var s = 1; // surface index
  37342. var cs = 0;
  37343. var v = 0;
  37344. for (i = 0; i <= subdivisions; i++) {
  37345. h = i / subdivisions;
  37346. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37347. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37348. for (r = 0; r < ringIdx; r++) {
  37349. if (hasRings) {
  37350. s += r;
  37351. }
  37352. if (enclose) {
  37353. s += 2 * r;
  37354. }
  37355. for (j = 0; j <= tessellation; j++) {
  37356. angle = j * angle_step;
  37357. // position
  37358. ringVertex.x = Math.cos(-angle) * radius;
  37359. ringVertex.y = -height / 2 + h * height;
  37360. ringVertex.z = Math.sin(-angle) * radius;
  37361. // normal
  37362. if (diameterTop === 0 && i === subdivisions) {
  37363. // if no top cap, reuse former normals
  37364. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37365. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37366. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37367. }
  37368. else {
  37369. ringNormal.x = ringVertex.x;
  37370. ringNormal.z = ringVertex.z;
  37371. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37372. ringNormal.normalize();
  37373. }
  37374. // keep first ring vertex values for enclose
  37375. if (j === 0) {
  37376. ringFirstVertex.copyFrom(ringVertex);
  37377. ringFirstNormal.copyFrom(ringNormal);
  37378. }
  37379. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37380. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37381. if (hasRings) {
  37382. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37383. }
  37384. else {
  37385. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37386. }
  37387. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37388. if (faceColors) {
  37389. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37390. }
  37391. }
  37392. // if enclose, add four vertices and their dedicated normals
  37393. if (arc !== 1 && enclose) {
  37394. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37395. positions.push(0, ringVertex.y, 0);
  37396. positions.push(0, ringVertex.y, 0);
  37397. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37398. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37399. quadNormal.normalize();
  37400. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37401. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37402. quadNormal.normalize();
  37403. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37404. if (hasRings) {
  37405. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37406. }
  37407. else {
  37408. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37409. }
  37410. uvs.push(faceUV[s + 1].x, v);
  37411. uvs.push(faceUV[s + 1].z, v);
  37412. if (hasRings) {
  37413. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37414. }
  37415. else {
  37416. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37417. }
  37418. uvs.push(faceUV[s + 2].x, v);
  37419. uvs.push(faceUV[s + 2].z, v);
  37420. if (faceColors) {
  37421. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37422. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37423. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37424. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37425. }
  37426. }
  37427. if (cs !== s) {
  37428. cs = s;
  37429. }
  37430. }
  37431. }
  37432. // indices
  37433. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37434. var s;
  37435. i = 0;
  37436. for (s = 0; s < subdivisions; s++) {
  37437. var i0 = 0;
  37438. var i1 = 0;
  37439. var i2 = 0;
  37440. var i3 = 0;
  37441. for (j = 0; j < tessellation; j++) {
  37442. i0 = i * (e + 1) + j;
  37443. i1 = (i + 1) * (e + 1) + j;
  37444. i2 = i * (e + 1) + (j + 1);
  37445. i3 = (i + 1) * (e + 1) + (j + 1);
  37446. indices.push(i0, i1, i2);
  37447. indices.push(i3, i2, i1);
  37448. }
  37449. if (arc !== 1 && enclose) { // if enclose, add two quads
  37450. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37451. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37452. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37453. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37454. }
  37455. i = (hasRings) ? (i + 2) : (i + 1);
  37456. }
  37457. // Caps
  37458. var createCylinderCap = function (isTop) {
  37459. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37460. if (radius === 0) {
  37461. return;
  37462. }
  37463. // Cap positions, normals & uvs
  37464. var angle;
  37465. var circleVector;
  37466. var i;
  37467. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37468. var c = null;
  37469. if (faceColors) {
  37470. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37471. }
  37472. // cap center
  37473. var vbase = positions.length / 3;
  37474. var offset = isTop ? height / 2 : -height / 2;
  37475. var center = new BABYLON.Vector3(0, offset, 0);
  37476. positions.push(center.x, center.y, center.z);
  37477. normals.push(0, isTop ? 1 : -1, 0);
  37478. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37479. if (c) {
  37480. colors.push(c.r, c.g, c.b, c.a);
  37481. }
  37482. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37483. for (i = 0; i <= tessellation; i++) {
  37484. angle = Math.PI * 2 * i * arc / tessellation;
  37485. var cos = Math.cos(-angle);
  37486. var sin = Math.sin(-angle);
  37487. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37488. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37489. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37490. normals.push(0, isTop ? 1 : -1, 0);
  37491. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37492. if (c) {
  37493. colors.push(c.r, c.g, c.b, c.a);
  37494. }
  37495. }
  37496. // Cap indices
  37497. for (i = 0; i < tessellation; i++) {
  37498. if (!isTop) {
  37499. indices.push(vbase);
  37500. indices.push(vbase + (i + 1));
  37501. indices.push(vbase + (i + 2));
  37502. }
  37503. else {
  37504. indices.push(vbase);
  37505. indices.push(vbase + (i + 2));
  37506. indices.push(vbase + (i + 1));
  37507. }
  37508. }
  37509. };
  37510. // add caps to geometry
  37511. createCylinderCap(false);
  37512. createCylinderCap(true);
  37513. // Sides
  37514. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37515. var vertexData = new VertexData();
  37516. vertexData.indices = indices;
  37517. vertexData.positions = positions;
  37518. vertexData.normals = normals;
  37519. vertexData.uvs = uvs;
  37520. if (faceColors) {
  37521. vertexData.colors = colors;
  37522. }
  37523. return vertexData;
  37524. };
  37525. /**
  37526. * Creates the VertexData for a torus
  37527. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37528. * * diameter the diameter of the torus, optional default 1
  37529. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37530. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37531. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37532. * * 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)
  37533. * * 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)
  37534. * @returns the VertexData of the torus
  37535. */
  37536. VertexData.CreateTorus = function (options) {
  37537. var indices = [];
  37538. var positions = [];
  37539. var normals = [];
  37540. var uvs = [];
  37541. var diameter = options.diameter || 1;
  37542. var thickness = options.thickness || 0.5;
  37543. var tessellation = options.tessellation || 16;
  37544. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37545. var stride = tessellation + 1;
  37546. for (var i = 0; i <= tessellation; i++) {
  37547. var u = i / tessellation;
  37548. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37549. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37550. for (var j = 0; j <= tessellation; j++) {
  37551. var v = 1 - j / tessellation;
  37552. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37553. var dx = Math.cos(innerAngle);
  37554. var dy = Math.sin(innerAngle);
  37555. // Create a vertex.
  37556. var normal = new BABYLON.Vector3(dx, dy, 0);
  37557. var position = normal.scale(thickness / 2);
  37558. var textureCoordinate = new BABYLON.Vector2(u, v);
  37559. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37560. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37561. positions.push(position.x, position.y, position.z);
  37562. normals.push(normal.x, normal.y, normal.z);
  37563. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37564. // And create indices for two triangles.
  37565. var nextI = (i + 1) % stride;
  37566. var nextJ = (j + 1) % stride;
  37567. indices.push(i * stride + j);
  37568. indices.push(i * stride + nextJ);
  37569. indices.push(nextI * stride + j);
  37570. indices.push(i * stride + nextJ);
  37571. indices.push(nextI * stride + nextJ);
  37572. indices.push(nextI * stride + j);
  37573. }
  37574. }
  37575. // Sides
  37576. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37577. // Result
  37578. var vertexData = new VertexData();
  37579. vertexData.indices = indices;
  37580. vertexData.positions = positions;
  37581. vertexData.normals = normals;
  37582. vertexData.uvs = uvs;
  37583. return vertexData;
  37584. };
  37585. /**
  37586. * Creates the VertexData of the LineSystem
  37587. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37588. * - lines an array of lines, each line being an array of successive Vector3
  37589. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37590. * @returns the VertexData of the LineSystem
  37591. */
  37592. VertexData.CreateLineSystem = function (options) {
  37593. var indices = [];
  37594. var positions = [];
  37595. var lines = options.lines;
  37596. var colors = options.colors;
  37597. var vertexColors = [];
  37598. var idx = 0;
  37599. for (var l = 0; l < lines.length; l++) {
  37600. var points = lines[l];
  37601. for (var index = 0; index < points.length; index++) {
  37602. positions.push(points[index].x, points[index].y, points[index].z);
  37603. if (colors) {
  37604. var color = colors[l];
  37605. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37606. }
  37607. if (index > 0) {
  37608. indices.push(idx - 1);
  37609. indices.push(idx);
  37610. }
  37611. idx++;
  37612. }
  37613. }
  37614. var vertexData = new VertexData();
  37615. vertexData.indices = indices;
  37616. vertexData.positions = positions;
  37617. if (colors) {
  37618. vertexData.colors = vertexColors;
  37619. }
  37620. return vertexData;
  37621. };
  37622. /**
  37623. * Create the VertexData for a DashedLines
  37624. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37625. * - points an array successive Vector3
  37626. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37627. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37628. * - dashNb the intended total number of dashes, optional, default 200
  37629. * @returns the VertexData for the DashedLines
  37630. */
  37631. VertexData.CreateDashedLines = function (options) {
  37632. var dashSize = options.dashSize || 3;
  37633. var gapSize = options.gapSize || 1;
  37634. var dashNb = options.dashNb || 200;
  37635. var points = options.points;
  37636. var positions = new Array();
  37637. var indices = new Array();
  37638. var curvect = BABYLON.Vector3.Zero();
  37639. var lg = 0;
  37640. var nb = 0;
  37641. var shft = 0;
  37642. var dashshft = 0;
  37643. var curshft = 0;
  37644. var idx = 0;
  37645. var i = 0;
  37646. for (i = 0; i < points.length - 1; i++) {
  37647. points[i + 1].subtractToRef(points[i], curvect);
  37648. lg += curvect.length();
  37649. }
  37650. shft = lg / dashNb;
  37651. dashshft = dashSize * shft / (dashSize + gapSize);
  37652. for (i = 0; i < points.length - 1; i++) {
  37653. points[i + 1].subtractToRef(points[i], curvect);
  37654. nb = Math.floor(curvect.length() / shft);
  37655. curvect.normalize();
  37656. for (var j = 0; j < nb; j++) {
  37657. curshft = shft * j;
  37658. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37659. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37660. indices.push(idx, idx + 1);
  37661. idx += 2;
  37662. }
  37663. }
  37664. // Result
  37665. var vertexData = new VertexData();
  37666. vertexData.positions = positions;
  37667. vertexData.indices = indices;
  37668. return vertexData;
  37669. };
  37670. /**
  37671. * Creates the VertexData for a Ground
  37672. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37673. * - width the width (x direction) of the ground, optional, default 1
  37674. * - height the height (z direction) of the ground, optional, default 1
  37675. * - subdivisions the number of subdivisions per side, optional, default 1
  37676. * @returns the VertexData of the Ground
  37677. */
  37678. VertexData.CreateGround = function (options) {
  37679. var indices = [];
  37680. var positions = [];
  37681. var normals = [];
  37682. var uvs = [];
  37683. var row, col;
  37684. var width = options.width || 1;
  37685. var height = options.height || 1;
  37686. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37687. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37688. for (row = 0; row <= subdivisionsY; row++) {
  37689. for (col = 0; col <= subdivisionsX; col++) {
  37690. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37691. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37692. positions.push(position.x, position.y, position.z);
  37693. normals.push(normal.x, normal.y, normal.z);
  37694. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37695. }
  37696. }
  37697. for (row = 0; row < subdivisionsY; row++) {
  37698. for (col = 0; col < subdivisionsX; col++) {
  37699. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37700. indices.push(col + 1 + row * (subdivisionsX + 1));
  37701. indices.push(col + row * (subdivisionsX + 1));
  37702. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37703. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37704. indices.push(col + row * (subdivisionsX + 1));
  37705. }
  37706. }
  37707. // Result
  37708. var vertexData = new VertexData();
  37709. vertexData.indices = indices;
  37710. vertexData.positions = positions;
  37711. vertexData.normals = normals;
  37712. vertexData.uvs = uvs;
  37713. return vertexData;
  37714. };
  37715. /**
  37716. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37717. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37718. * * xmin the ground minimum X coordinate, optional, default -1
  37719. * * zmin the ground minimum Z coordinate, optional, default -1
  37720. * * xmax the ground maximum X coordinate, optional, default 1
  37721. * * zmax the ground maximum Z coordinate, optional, default 1
  37722. * * 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}
  37723. * * 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}
  37724. * @returns the VertexData of the TiledGround
  37725. */
  37726. VertexData.CreateTiledGround = function (options) {
  37727. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37728. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37729. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37730. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37731. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37732. var precision = options.precision || { w: 1, h: 1 };
  37733. var indices = new Array();
  37734. var positions = new Array();
  37735. var normals = new Array();
  37736. var uvs = new Array();
  37737. var row, col, tileRow, tileCol;
  37738. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37739. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37740. precision.w = (precision.w < 1) ? 1 : precision.w;
  37741. precision.h = (precision.h < 1) ? 1 : precision.h;
  37742. var tileSize = {
  37743. 'w': (xmax - xmin) / subdivisions.w,
  37744. 'h': (zmax - zmin) / subdivisions.h
  37745. };
  37746. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37747. // Indices
  37748. var base = positions.length / 3;
  37749. var rowLength = precision.w + 1;
  37750. for (row = 0; row < precision.h; row++) {
  37751. for (col = 0; col < precision.w; col++) {
  37752. var square = [
  37753. base + col + row * rowLength,
  37754. base + (col + 1) + row * rowLength,
  37755. base + (col + 1) + (row + 1) * rowLength,
  37756. base + col + (row + 1) * rowLength
  37757. ];
  37758. indices.push(square[1]);
  37759. indices.push(square[2]);
  37760. indices.push(square[3]);
  37761. indices.push(square[0]);
  37762. indices.push(square[1]);
  37763. indices.push(square[3]);
  37764. }
  37765. }
  37766. // Position, normals and uvs
  37767. var position = BABYLON.Vector3.Zero();
  37768. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37769. for (row = 0; row <= precision.h; row++) {
  37770. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37771. for (col = 0; col <= precision.w; col++) {
  37772. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37773. position.y = 0;
  37774. positions.push(position.x, position.y, position.z);
  37775. normals.push(normal.x, normal.y, normal.z);
  37776. uvs.push(col / precision.w, row / precision.h);
  37777. }
  37778. }
  37779. }
  37780. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37781. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37782. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37783. }
  37784. }
  37785. // Result
  37786. var vertexData = new VertexData();
  37787. vertexData.indices = indices;
  37788. vertexData.positions = positions;
  37789. vertexData.normals = normals;
  37790. vertexData.uvs = uvs;
  37791. return vertexData;
  37792. };
  37793. /**
  37794. * Creates the VertexData of the Ground designed from a heightmap
  37795. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37796. * * width the width (x direction) of the ground
  37797. * * height the height (z direction) of the ground
  37798. * * subdivisions the number of subdivisions per side
  37799. * * minHeight the minimum altitude on the ground, optional, default 0
  37800. * * maxHeight the maximum altitude on the ground, optional default 1
  37801. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37802. * * buffer the array holding the image color data
  37803. * * bufferWidth the width of image
  37804. * * bufferHeight the height of image
  37805. * @returns the VertexData of the Ground designed from a heightmap
  37806. */
  37807. VertexData.CreateGroundFromHeightMap = function (options) {
  37808. var indices = [];
  37809. var positions = [];
  37810. var normals = [];
  37811. var uvs = [];
  37812. var row, col;
  37813. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37814. // Vertices
  37815. for (row = 0; row <= options.subdivisions; row++) {
  37816. for (col = 0; col <= options.subdivisions; col++) {
  37817. 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));
  37818. // Compute height
  37819. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37820. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37821. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37822. var r = options.buffer[pos] / 255.0;
  37823. var g = options.buffer[pos + 1] / 255.0;
  37824. var b = options.buffer[pos + 2] / 255.0;
  37825. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37826. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37827. // Add vertex
  37828. positions.push(position.x, position.y, position.z);
  37829. normals.push(0, 0, 0);
  37830. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37831. }
  37832. }
  37833. // Indices
  37834. for (row = 0; row < options.subdivisions; row++) {
  37835. for (col = 0; col < options.subdivisions; col++) {
  37836. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37837. indices.push(col + 1 + row * (options.subdivisions + 1));
  37838. indices.push(col + row * (options.subdivisions + 1));
  37839. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37840. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37841. indices.push(col + row * (options.subdivisions + 1));
  37842. }
  37843. }
  37844. // Normals
  37845. VertexData.ComputeNormals(positions, indices, normals);
  37846. // Result
  37847. var vertexData = new VertexData();
  37848. vertexData.indices = indices;
  37849. vertexData.positions = positions;
  37850. vertexData.normals = normals;
  37851. vertexData.uvs = uvs;
  37852. return vertexData;
  37853. };
  37854. /**
  37855. * Creates the VertexData for a Plane
  37856. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37857. * * size sets the width and height of the plane to the value of size, optional default 1
  37858. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37859. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37860. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37861. * * 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)
  37862. * * 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)
  37863. * @returns the VertexData of the box
  37864. */
  37865. VertexData.CreatePlane = function (options) {
  37866. var indices = [];
  37867. var positions = [];
  37868. var normals = [];
  37869. var uvs = [];
  37870. var width = options.width || options.size || 1;
  37871. var height = options.height || options.size || 1;
  37872. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37873. // Vertices
  37874. var halfWidth = width / 2.0;
  37875. var halfHeight = height / 2.0;
  37876. positions.push(-halfWidth, -halfHeight, 0);
  37877. normals.push(0, 0, -1.0);
  37878. uvs.push(0.0, 0.0);
  37879. positions.push(halfWidth, -halfHeight, 0);
  37880. normals.push(0, 0, -1.0);
  37881. uvs.push(1.0, 0.0);
  37882. positions.push(halfWidth, halfHeight, 0);
  37883. normals.push(0, 0, -1.0);
  37884. uvs.push(1.0, 1.0);
  37885. positions.push(-halfWidth, halfHeight, 0);
  37886. normals.push(0, 0, -1.0);
  37887. uvs.push(0.0, 1.0);
  37888. // Indices
  37889. indices.push(0);
  37890. indices.push(1);
  37891. indices.push(2);
  37892. indices.push(0);
  37893. indices.push(2);
  37894. indices.push(3);
  37895. // Sides
  37896. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37897. // Result
  37898. var vertexData = new VertexData();
  37899. vertexData.indices = indices;
  37900. vertexData.positions = positions;
  37901. vertexData.normals = normals;
  37902. vertexData.uvs = uvs;
  37903. return vertexData;
  37904. };
  37905. /**
  37906. * Creates the VertexData of the Disc or regular Polygon
  37907. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37908. * * radius the radius of the disc, optional default 0.5
  37909. * * tessellation the number of polygon sides, optional, default 64
  37910. * * 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
  37911. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37912. * * 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)
  37913. * * 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)
  37914. * @returns the VertexData of the box
  37915. */
  37916. VertexData.CreateDisc = function (options) {
  37917. var positions = new Array();
  37918. var indices = new Array();
  37919. var normals = new Array();
  37920. var uvs = new Array();
  37921. var radius = options.radius || 0.5;
  37922. var tessellation = options.tessellation || 64;
  37923. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37924. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37925. // positions and uvs
  37926. positions.push(0, 0, 0); // disc center first
  37927. uvs.push(0.5, 0.5);
  37928. var theta = Math.PI * 2 * arc;
  37929. var step = theta / tessellation;
  37930. for (var a = 0; a < theta; a += step) {
  37931. var x = Math.cos(a);
  37932. var y = Math.sin(a);
  37933. var u = (x + 1) / 2;
  37934. var v = (1 - y) / 2;
  37935. positions.push(radius * x, radius * y, 0);
  37936. uvs.push(u, v);
  37937. }
  37938. if (arc === 1) {
  37939. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37940. uvs.push(uvs[2], uvs[3]);
  37941. }
  37942. //indices
  37943. var vertexNb = positions.length / 3;
  37944. for (var i = 1; i < vertexNb - 1; i++) {
  37945. indices.push(i + 1, 0, i);
  37946. }
  37947. // result
  37948. VertexData.ComputeNormals(positions, indices, normals);
  37949. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37950. var vertexData = new VertexData();
  37951. vertexData.indices = indices;
  37952. vertexData.positions = positions;
  37953. vertexData.normals = normals;
  37954. vertexData.uvs = uvs;
  37955. return vertexData;
  37956. };
  37957. /**
  37958. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37959. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37960. * @param polygon a mesh built from polygonTriangulation.build()
  37961. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37962. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37963. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37964. * @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)
  37965. * @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)
  37966. * @returns the VertexData of the Polygon
  37967. */
  37968. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37969. var faceUV = fUV || new Array(3);
  37970. var faceColors = fColors;
  37971. var colors = [];
  37972. // default face colors and UV if undefined
  37973. for (var f = 0; f < 3; f++) {
  37974. if (faceUV[f] === undefined) {
  37975. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37976. }
  37977. if (faceColors && faceColors[f] === undefined) {
  37978. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37979. }
  37980. }
  37981. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37982. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37983. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37984. var indices = polygon.getIndices();
  37985. // set face colours and textures
  37986. var idx = 0;
  37987. var face = 0;
  37988. for (var index = 0; index < normals.length; index += 3) {
  37989. //Edge Face no. 1
  37990. if (Math.abs(normals[index + 1]) < 0.001) {
  37991. face = 1;
  37992. }
  37993. //Top Face no. 0
  37994. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37995. face = 0;
  37996. }
  37997. //Bottom Face no. 2
  37998. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37999. face = 2;
  38000. }
  38001. idx = index / 3;
  38002. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38003. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38004. if (faceColors) {
  38005. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38006. }
  38007. }
  38008. // sides
  38009. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38010. // Result
  38011. var vertexData = new VertexData();
  38012. vertexData.indices = indices;
  38013. vertexData.positions = positions;
  38014. vertexData.normals = normals;
  38015. vertexData.uvs = uvs;
  38016. if (faceColors) {
  38017. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38018. vertexData.colors = totalColors;
  38019. }
  38020. return vertexData;
  38021. };
  38022. /**
  38023. * Creates the VertexData of the IcoSphere
  38024. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38025. * * radius the radius of the IcoSphere, optional default 1
  38026. * * radiusX allows stretching in the x direction, optional, default radius
  38027. * * radiusY allows stretching in the y direction, optional, default radius
  38028. * * radiusZ allows stretching in the z direction, optional, default radius
  38029. * * flat when true creates a flat shaded mesh, optional, default true
  38030. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38031. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38032. * * 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)
  38033. * * 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)
  38034. * @returns the VertexData of the IcoSphere
  38035. */
  38036. VertexData.CreateIcoSphere = function (options) {
  38037. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38038. var radius = options.radius || 1;
  38039. var flat = (options.flat === undefined) ? true : options.flat;
  38040. var subdivisions = options.subdivisions || 4;
  38041. var radiusX = options.radiusX || radius;
  38042. var radiusY = options.radiusY || radius;
  38043. var radiusZ = options.radiusZ || radius;
  38044. var t = (1 + Math.sqrt(5)) / 2;
  38045. // 12 vertex x,y,z
  38046. var ico_vertices = [
  38047. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38048. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38049. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38050. ];
  38051. // index of 3 vertex makes a face of icopshere
  38052. var ico_indices = [
  38053. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38054. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38055. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38056. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38057. ];
  38058. // vertex for uv have aliased position, not for UV
  38059. var vertices_unalias_id = [
  38060. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38061. // vertex alias
  38062. 0,
  38063. 2,
  38064. 3,
  38065. 3,
  38066. 3,
  38067. 4,
  38068. 7,
  38069. 8,
  38070. 9,
  38071. 9,
  38072. 10,
  38073. 11 // 23: B + 12
  38074. ];
  38075. // uv as integer step (not pixels !)
  38076. var ico_vertexuv = [
  38077. 5, 1, 3, 1, 6, 4, 0, 0,
  38078. 5, 3, 4, 2, 2, 2, 4, 0,
  38079. 2, 0, 1, 1, 6, 0, 6, 2,
  38080. // vertex alias (for same vertex on different faces)
  38081. 0, 4,
  38082. 3, 3,
  38083. 4, 4,
  38084. 3, 1,
  38085. 4, 2,
  38086. 4, 4,
  38087. 0, 2,
  38088. 1, 1,
  38089. 2, 2,
  38090. 3, 3,
  38091. 1, 3,
  38092. 2, 4 // 23: B + 12
  38093. ];
  38094. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38095. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38096. // First island of uv mapping
  38097. // v = 4h 3+ 2
  38098. // v = 3h 9+ 4
  38099. // v = 2h 9+ 5 B
  38100. // v = 1h 9 1 0
  38101. // v = 0h 3 8 7 A
  38102. // u = 0 1 2 3 4 5 6 *a
  38103. // Second island of uv mapping
  38104. // v = 4h 0+ B+ 4+
  38105. // v = 3h A+ 2+
  38106. // v = 2h 7+ 6 3+
  38107. // v = 1h 8+ 3+
  38108. // v = 0h
  38109. // u = 0 1 2 3 4 5 6 *a
  38110. // Face layout on texture UV mapping
  38111. // ============
  38112. // \ 4 /\ 16 / ======
  38113. // \ / \ / /\ 11 /
  38114. // \/ 7 \/ / \ /
  38115. // ======= / 10 \/
  38116. // /\ 17 /\ =======
  38117. // / \ / \ \ 15 /\
  38118. // / 8 \/ 12 \ \ / \
  38119. // ============ \/ 6 \
  38120. // \ 18 /\ ============
  38121. // \ / \ \ 5 /\ 0 /
  38122. // \/ 13 \ \ / \ /
  38123. // ======= \/ 1 \/
  38124. // =============
  38125. // /\ 19 /\ 2 /\
  38126. // / \ / \ / \
  38127. // / 14 \/ 9 \/ 3 \
  38128. // ===================
  38129. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38130. var ustep = 138 / 1024;
  38131. var vstep = 239 / 1024;
  38132. var uoffset = 60 / 1024;
  38133. var voffset = 26 / 1024;
  38134. // Second island should have margin, not to touch the first island
  38135. // avoid any borderline artefact in pixel rounding
  38136. var island_u_offset = -40 / 1024;
  38137. var island_v_offset = +20 / 1024;
  38138. // face is either island 0 or 1 :
  38139. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38140. var island = [
  38141. 0, 0, 0, 0, 1,
  38142. 0, 0, 1, 1, 0,
  38143. 0, 0, 1, 1, 0,
  38144. 0, 1, 1, 1, 0 // 15 - 19
  38145. ];
  38146. var indices = new Array();
  38147. var positions = new Array();
  38148. var normals = new Array();
  38149. var uvs = new Array();
  38150. var current_indice = 0;
  38151. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38152. var face_vertex_pos = new Array(3);
  38153. var face_vertex_uv = new Array(3);
  38154. var v012;
  38155. for (v012 = 0; v012 < 3; v012++) {
  38156. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38157. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38158. }
  38159. // create all with normals
  38160. for (var face = 0; face < 20; face++) {
  38161. // 3 vertex per face
  38162. for (v012 = 0; v012 < 3; v012++) {
  38163. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38164. var v_id = ico_indices[3 * face + v012];
  38165. // vertex have 3D position (x,y,z)
  38166. 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]);
  38167. // Normalize to get normal, then scale to radius
  38168. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38169. // uv Coordinates from vertex ID
  38170. 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);
  38171. }
  38172. // Subdivide the face (interpolate pos, norm, uv)
  38173. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38174. // - norm is linear interpolation of vertex corner normal
  38175. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38176. // - uv is linear interpolation
  38177. //
  38178. // Topology is as below for sub-divide by 2
  38179. // vertex shown as v0,v1,v2
  38180. // interp index is i1 to progress in range [v0,v1[
  38181. // interp index is i2 to progress in range [v0,v2[
  38182. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38183. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38184. //
  38185. //
  38186. // i2 v2
  38187. // ^ ^
  38188. // / / \
  38189. // / / \
  38190. // / / \
  38191. // / / (0,1) \
  38192. // / #---------\
  38193. // / / \ (0,0)'/ \
  38194. // / / \ / \
  38195. // / / \ / \
  38196. // / / (0,0) \ / (1,0) \
  38197. // / #---------#---------\
  38198. // v0 v1
  38199. //
  38200. // --------------------> i1
  38201. //
  38202. // interp of (i1,i2):
  38203. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38204. // along i1 : lerp(x0,x1, i1/(S-i2))
  38205. //
  38206. // centroid of triangle is needed to get help normal computation
  38207. // (c1,c2) are used for centroid location
  38208. var interp_vertex = function (i1, i2, c1, c2) {
  38209. // vertex is interpolated from
  38210. // - face_vertex_pos[0..2]
  38211. // - face_vertex_uv[0..2]
  38212. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38213. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38214. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38215. pos_interp.normalize();
  38216. var vertex_normal;
  38217. if (flat) {
  38218. // in flat mode, recalculate normal as face centroid normal
  38219. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38220. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38221. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38222. }
  38223. else {
  38224. // in smooth mode, recalculate normal from each single vertex position
  38225. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38226. }
  38227. // Vertex normal need correction due to X,Y,Z radius scaling
  38228. vertex_normal.x /= radiusX;
  38229. vertex_normal.y /= radiusY;
  38230. vertex_normal.z /= radiusZ;
  38231. vertex_normal.normalize();
  38232. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38233. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38234. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38235. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38236. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38237. uvs.push(uv_interp.x, uv_interp.y);
  38238. // push each vertex has member of a face
  38239. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38240. indices.push(current_indice);
  38241. current_indice++;
  38242. };
  38243. for (var i2 = 0; i2 < subdivisions; i2++) {
  38244. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38245. // face : (i1,i2) for /\ :
  38246. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38247. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38248. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38249. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38250. if (i1 + i2 + 1 < subdivisions) {
  38251. // face : (i1,i2)' for \/ :
  38252. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38253. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38254. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38255. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38256. }
  38257. }
  38258. }
  38259. }
  38260. // Sides
  38261. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38262. // Result
  38263. var vertexData = new VertexData();
  38264. vertexData.indices = indices;
  38265. vertexData.positions = positions;
  38266. vertexData.normals = normals;
  38267. vertexData.uvs = uvs;
  38268. return vertexData;
  38269. };
  38270. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38271. /**
  38272. * Creates the VertexData for a Polyhedron
  38273. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38274. * * type provided types are:
  38275. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38276. * * 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)
  38277. * * size the size of the IcoSphere, optional default 1
  38278. * * sizeX allows stretching in the x direction, optional, default size
  38279. * * sizeY allows stretching in the y direction, optional, default size
  38280. * * sizeZ allows stretching in the z direction, optional, default size
  38281. * * 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
  38282. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38283. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38284. * * flat when true creates a flat shaded mesh, optional, default true
  38285. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38286. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38287. * * 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)
  38288. * * 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)
  38289. * @returns the VertexData of the Polyhedron
  38290. */
  38291. VertexData.CreatePolyhedron = function (options) {
  38292. // provided polyhedron types :
  38293. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38294. // 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)
  38295. var polyhedra = [];
  38296. 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]] };
  38297. 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]] };
  38298. polyhedra[2] = {
  38299. 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]],
  38300. 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]]
  38301. };
  38302. polyhedra[3] = {
  38303. 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]],
  38304. 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]]
  38305. };
  38306. polyhedra[4] = {
  38307. 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]],
  38308. 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]]
  38309. };
  38310. 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]] };
  38311. 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]] };
  38312. 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]] };
  38313. 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]] };
  38314. 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]] };
  38315. 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]] };
  38316. 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]] };
  38317. 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]] };
  38318. 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]] };
  38319. polyhedra[14] = {
  38320. 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]],
  38321. 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]]
  38322. };
  38323. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38324. var size = options.size;
  38325. var sizeX = options.sizeX || size || 1;
  38326. var sizeY = options.sizeY || size || 1;
  38327. var sizeZ = options.sizeZ || size || 1;
  38328. var data = options.custom || polyhedra[type];
  38329. var nbfaces = data.face.length;
  38330. var faceUV = options.faceUV || new Array(nbfaces);
  38331. var faceColors = options.faceColors;
  38332. var flat = (options.flat === undefined) ? true : options.flat;
  38333. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38334. var positions = new Array();
  38335. var indices = new Array();
  38336. var normals = new Array();
  38337. var uvs = new Array();
  38338. var colors = new Array();
  38339. var index = 0;
  38340. var faceIdx = 0; // face cursor in the array "indexes"
  38341. var indexes = new Array();
  38342. var i = 0;
  38343. var f = 0;
  38344. var u, v, ang, x, y, tmp;
  38345. // default face colors and UV if undefined
  38346. if (flat) {
  38347. for (f = 0; f < nbfaces; f++) {
  38348. if (faceColors && faceColors[f] === undefined) {
  38349. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38350. }
  38351. if (faceUV && faceUV[f] === undefined) {
  38352. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38353. }
  38354. }
  38355. }
  38356. if (!flat) {
  38357. for (i = 0; i < data.vertex.length; i++) {
  38358. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38359. uvs.push(0, 0);
  38360. }
  38361. for (f = 0; f < nbfaces; f++) {
  38362. for (i = 0; i < data.face[f].length - 2; i++) {
  38363. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38364. }
  38365. }
  38366. }
  38367. else {
  38368. for (f = 0; f < nbfaces; f++) {
  38369. var fl = data.face[f].length; // number of vertices of the current face
  38370. ang = 2 * Math.PI / fl;
  38371. x = 0.5 * Math.tan(ang / 2);
  38372. y = 0.5;
  38373. // positions, uvs, colors
  38374. for (i = 0; i < fl; i++) {
  38375. // positions
  38376. 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);
  38377. indexes.push(index);
  38378. index++;
  38379. // uvs
  38380. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38381. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38382. uvs.push(u, v);
  38383. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38384. y = x * Math.sin(ang) + y * Math.cos(ang);
  38385. x = tmp;
  38386. // colors
  38387. if (faceColors) {
  38388. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38389. }
  38390. }
  38391. // indices from indexes
  38392. for (i = 0; i < fl - 2; i++) {
  38393. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38394. }
  38395. faceIdx += fl;
  38396. }
  38397. }
  38398. VertexData.ComputeNormals(positions, indices, normals);
  38399. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38400. var vertexData = new VertexData();
  38401. vertexData.positions = positions;
  38402. vertexData.indices = indices;
  38403. vertexData.normals = normals;
  38404. vertexData.uvs = uvs;
  38405. if (faceColors && flat) {
  38406. vertexData.colors = colors;
  38407. }
  38408. return vertexData;
  38409. };
  38410. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38411. /**
  38412. * Creates the VertexData for a TorusKnot
  38413. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38414. * * radius the radius of the torus knot, optional, default 2
  38415. * * tube the thickness of the tube, optional, default 0.5
  38416. * * radialSegments the number of sides on each tube segments, optional, default 32
  38417. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38418. * * p the number of windings around the z axis, optional, default 2
  38419. * * q the number of windings around the x axis, optional, default 3
  38420. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38421. * * 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)
  38422. * * 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)
  38423. * @returns the VertexData of the Torus Knot
  38424. */
  38425. VertexData.CreateTorusKnot = function (options) {
  38426. var indices = new Array();
  38427. var positions = new Array();
  38428. var normals = new Array();
  38429. var uvs = new Array();
  38430. var radius = options.radius || 2;
  38431. var tube = options.tube || 0.5;
  38432. var radialSegments = options.radialSegments || 32;
  38433. var tubularSegments = options.tubularSegments || 32;
  38434. var p = options.p || 2;
  38435. var q = options.q || 3;
  38436. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38437. // Helper
  38438. var getPos = function (angle) {
  38439. var cu = Math.cos(angle);
  38440. var su = Math.sin(angle);
  38441. var quOverP = q / p * angle;
  38442. var cs = Math.cos(quOverP);
  38443. var tx = radius * (2 + cs) * 0.5 * cu;
  38444. var ty = radius * (2 + cs) * su * 0.5;
  38445. var tz = radius * Math.sin(quOverP) * 0.5;
  38446. return new BABYLON.Vector3(tx, ty, tz);
  38447. };
  38448. // Vertices
  38449. var i;
  38450. var j;
  38451. for (i = 0; i <= radialSegments; i++) {
  38452. var modI = i % radialSegments;
  38453. var u = modI / radialSegments * 2 * p * Math.PI;
  38454. var p1 = getPos(u);
  38455. var p2 = getPos(u + 0.01);
  38456. var tang = p2.subtract(p1);
  38457. var n = p2.add(p1);
  38458. var bitan = BABYLON.Vector3.Cross(tang, n);
  38459. n = BABYLON.Vector3.Cross(bitan, tang);
  38460. bitan.normalize();
  38461. n.normalize();
  38462. for (j = 0; j < tubularSegments; j++) {
  38463. var modJ = j % tubularSegments;
  38464. var v = modJ / tubularSegments * 2 * Math.PI;
  38465. var cx = -tube * Math.cos(v);
  38466. var cy = tube * Math.sin(v);
  38467. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38468. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38469. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38470. uvs.push(i / radialSegments);
  38471. uvs.push(j / tubularSegments);
  38472. }
  38473. }
  38474. for (i = 0; i < radialSegments; i++) {
  38475. for (j = 0; j < tubularSegments; j++) {
  38476. var jNext = (j + 1) % tubularSegments;
  38477. var a = i * tubularSegments + j;
  38478. var b = (i + 1) * tubularSegments + j;
  38479. var c = (i + 1) * tubularSegments + jNext;
  38480. var d = i * tubularSegments + jNext;
  38481. indices.push(d);
  38482. indices.push(b);
  38483. indices.push(a);
  38484. indices.push(d);
  38485. indices.push(c);
  38486. indices.push(b);
  38487. }
  38488. }
  38489. // Normals
  38490. VertexData.ComputeNormals(positions, indices, normals);
  38491. // Sides
  38492. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38493. // Result
  38494. var vertexData = new VertexData();
  38495. vertexData.indices = indices;
  38496. vertexData.positions = positions;
  38497. vertexData.normals = normals;
  38498. vertexData.uvs = uvs;
  38499. return vertexData;
  38500. };
  38501. // Tools
  38502. /**
  38503. * Compute normals for given positions and indices
  38504. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38505. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38506. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38507. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38508. * * facetNormals : optional array of facet normals (vector3)
  38509. * * facetPositions : optional array of facet positions (vector3)
  38510. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38511. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38512. * * bInfo : optional bounding info, required for facetPartitioning computation
  38513. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38514. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38515. * * useRightHandedSystem: optional boolean to for right handed system computation
  38516. * * depthSort : optional boolean to enable the facet depth sort computation
  38517. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38518. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38519. */
  38520. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38521. // temporary scalar variables
  38522. var index = 0; // facet index
  38523. var p1p2x = 0.0; // p1p2 vector x coordinate
  38524. var p1p2y = 0.0; // p1p2 vector y coordinate
  38525. var p1p2z = 0.0; // p1p2 vector z coordinate
  38526. var p3p2x = 0.0; // p3p2 vector x coordinate
  38527. var p3p2y = 0.0; // p3p2 vector y coordinate
  38528. var p3p2z = 0.0; // p3p2 vector z coordinate
  38529. var faceNormalx = 0.0; // facet normal x coordinate
  38530. var faceNormaly = 0.0; // facet normal y coordinate
  38531. var faceNormalz = 0.0; // facet normal z coordinate
  38532. var length = 0.0; // facet normal length before normalization
  38533. var v1x = 0; // vector1 x index in the positions array
  38534. var v1y = 0; // vector1 y index in the positions array
  38535. var v1z = 0; // vector1 z index in the positions array
  38536. var v2x = 0; // vector2 x index in the positions array
  38537. var v2y = 0; // vector2 y index in the positions array
  38538. var v2z = 0; // vector2 z index in the positions array
  38539. var v3x = 0; // vector3 x index in the positions array
  38540. var v3y = 0; // vector3 y index in the positions array
  38541. var v3z = 0; // vector3 z index in the positions array
  38542. var computeFacetNormals = false;
  38543. var computeFacetPositions = false;
  38544. var computeFacetPartitioning = false;
  38545. var computeDepthSort = false;
  38546. var faceNormalSign = 1;
  38547. var ratio = 0;
  38548. var distanceTo = null;
  38549. if (options) {
  38550. computeFacetNormals = (options.facetNormals) ? true : false;
  38551. computeFacetPositions = (options.facetPositions) ? true : false;
  38552. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38553. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38554. ratio = options.ratio || 0;
  38555. computeDepthSort = (options.depthSort) ? true : false;
  38556. distanceTo = (options.distanceTo);
  38557. if (computeDepthSort) {
  38558. if (distanceTo === undefined) {
  38559. distanceTo = BABYLON.Vector3.Zero();
  38560. }
  38561. var depthSortedFacets = options.depthSortedFacets;
  38562. }
  38563. }
  38564. // facetPartitioning reinit if needed
  38565. var xSubRatio = 0;
  38566. var ySubRatio = 0;
  38567. var zSubRatio = 0;
  38568. var subSq = 0;
  38569. if (computeFacetPartitioning && options && options.bbSize) {
  38570. var ox = 0; // X partitioning index for facet position
  38571. var oy = 0; // Y partinioning index for facet position
  38572. var oz = 0; // Z partinioning index for facet position
  38573. var b1x = 0; // X partitioning index for facet v1 vertex
  38574. var b1y = 0; // Y partitioning index for facet v1 vertex
  38575. var b1z = 0; // z partitioning index for facet v1 vertex
  38576. var b2x = 0; // X partitioning index for facet v2 vertex
  38577. var b2y = 0; // Y partitioning index for facet v2 vertex
  38578. var b2z = 0; // Z partitioning index for facet v2 vertex
  38579. var b3x = 0; // X partitioning index for facet v3 vertex
  38580. var b3y = 0; // Y partitioning index for facet v3 vertex
  38581. var b3z = 0; // Z partitioning index for facet v3 vertex
  38582. var block_idx_o = 0; // facet barycenter block index
  38583. var block_idx_v1 = 0; // v1 vertex block index
  38584. var block_idx_v2 = 0; // v2 vertex block index
  38585. var block_idx_v3 = 0; // v3 vertex block index
  38586. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38587. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38588. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38589. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38590. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38591. subSq = options.subDiv.max * options.subDiv.max;
  38592. options.facetPartitioning.length = 0;
  38593. }
  38594. // reset the normals
  38595. for (index = 0; index < positions.length; index++) {
  38596. normals[index] = 0.0;
  38597. }
  38598. // Loop : 1 indice triplet = 1 facet
  38599. var nbFaces = (indices.length / 3) | 0;
  38600. for (index = 0; index < nbFaces; index++) {
  38601. // get the indexes of the coordinates of each vertex of the facet
  38602. v1x = indices[index * 3] * 3;
  38603. v1y = v1x + 1;
  38604. v1z = v1x + 2;
  38605. v2x = indices[index * 3 + 1] * 3;
  38606. v2y = v2x + 1;
  38607. v2z = v2x + 2;
  38608. v3x = indices[index * 3 + 2] * 3;
  38609. v3y = v3x + 1;
  38610. v3z = v3x + 2;
  38611. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38612. p1p2y = positions[v1y] - positions[v2y];
  38613. p1p2z = positions[v1z] - positions[v2z];
  38614. p3p2x = positions[v3x] - positions[v2x];
  38615. p3p2y = positions[v3y] - positions[v2y];
  38616. p3p2z = positions[v3z] - positions[v2z];
  38617. // compute the face normal with the cross product
  38618. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38619. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38620. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38621. // normalize this normal and store it in the array facetData
  38622. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38623. length = (length === 0) ? 1.0 : length;
  38624. faceNormalx /= length;
  38625. faceNormaly /= length;
  38626. faceNormalz /= length;
  38627. if (computeFacetNormals && options) {
  38628. options.facetNormals[index].x = faceNormalx;
  38629. options.facetNormals[index].y = faceNormaly;
  38630. options.facetNormals[index].z = faceNormalz;
  38631. }
  38632. if (computeFacetPositions && options) {
  38633. // compute and the facet barycenter coordinates in the array facetPositions
  38634. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38635. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38636. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38637. }
  38638. if (computeFacetPartitioning && options) {
  38639. // store the facet indexes in arrays in the main facetPartitioning array :
  38640. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38641. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38642. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38643. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38644. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38645. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38646. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38647. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38648. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38649. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38650. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38651. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38652. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38653. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38654. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38655. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38656. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38657. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38658. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38659. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38660. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38661. // push each facet index in each block containing the vertex
  38662. options.facetPartitioning[block_idx_v1].push(index);
  38663. if (block_idx_v2 != block_idx_v1) {
  38664. options.facetPartitioning[block_idx_v2].push(index);
  38665. }
  38666. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38667. options.facetPartitioning[block_idx_v3].push(index);
  38668. }
  38669. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38670. options.facetPartitioning[block_idx_o].push(index);
  38671. }
  38672. }
  38673. if (computeDepthSort && options && options.facetPositions) {
  38674. var dsf = depthSortedFacets[index];
  38675. dsf.ind = index * 3;
  38676. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38677. }
  38678. // compute the normals anyway
  38679. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38680. normals[v1y] += faceNormaly;
  38681. normals[v1z] += faceNormalz;
  38682. normals[v2x] += faceNormalx;
  38683. normals[v2y] += faceNormaly;
  38684. normals[v2z] += faceNormalz;
  38685. normals[v3x] += faceNormalx;
  38686. normals[v3y] += faceNormaly;
  38687. normals[v3z] += faceNormalz;
  38688. }
  38689. // last normalization of each normal
  38690. for (index = 0; index < normals.length / 3; index++) {
  38691. faceNormalx = normals[index * 3];
  38692. faceNormaly = normals[index * 3 + 1];
  38693. faceNormalz = normals[index * 3 + 2];
  38694. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38695. length = (length === 0) ? 1.0 : length;
  38696. faceNormalx /= length;
  38697. faceNormaly /= length;
  38698. faceNormalz /= length;
  38699. normals[index * 3] = faceNormalx;
  38700. normals[index * 3 + 1] = faceNormaly;
  38701. normals[index * 3 + 2] = faceNormalz;
  38702. }
  38703. };
  38704. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38705. var li = indices.length;
  38706. var ln = normals.length;
  38707. var i;
  38708. var n;
  38709. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38710. switch (sideOrientation) {
  38711. case BABYLON.Mesh.FRONTSIDE:
  38712. // nothing changed
  38713. break;
  38714. case BABYLON.Mesh.BACKSIDE:
  38715. var tmp;
  38716. // indices
  38717. for (i = 0; i < li; i += 3) {
  38718. tmp = indices[i];
  38719. indices[i] = indices[i + 2];
  38720. indices[i + 2] = tmp;
  38721. }
  38722. // normals
  38723. for (n = 0; n < ln; n++) {
  38724. normals[n] = -normals[n];
  38725. }
  38726. break;
  38727. case BABYLON.Mesh.DOUBLESIDE:
  38728. // positions
  38729. var lp = positions.length;
  38730. var l = lp / 3;
  38731. for (var p = 0; p < lp; p++) {
  38732. positions[lp + p] = positions[p];
  38733. }
  38734. // indices
  38735. for (i = 0; i < li; i += 3) {
  38736. indices[i + li] = indices[i + 2] + l;
  38737. indices[i + 1 + li] = indices[i + 1] + l;
  38738. indices[i + 2 + li] = indices[i] + l;
  38739. }
  38740. // normals
  38741. for (n = 0; n < ln; n++) {
  38742. normals[ln + n] = -normals[n];
  38743. }
  38744. // uvs
  38745. var lu = uvs.length;
  38746. var u = 0;
  38747. for (u = 0; u < lu; u++) {
  38748. uvs[u + lu] = uvs[u];
  38749. }
  38750. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38751. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38752. u = 0;
  38753. for (i = 0; i < lu / 2; i++) {
  38754. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38755. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38756. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38757. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38758. u += 2;
  38759. }
  38760. break;
  38761. }
  38762. };
  38763. /**
  38764. * Applies VertexData created from the imported parameters to the geometry
  38765. * @param parsedVertexData the parsed data from an imported file
  38766. * @param geometry the geometry to apply the VertexData to
  38767. */
  38768. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38769. var vertexData = new VertexData();
  38770. // positions
  38771. var positions = parsedVertexData.positions;
  38772. if (positions) {
  38773. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38774. }
  38775. // normals
  38776. var normals = parsedVertexData.normals;
  38777. if (normals) {
  38778. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38779. }
  38780. // tangents
  38781. var tangents = parsedVertexData.tangents;
  38782. if (tangents) {
  38783. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38784. }
  38785. // uvs
  38786. var uvs = parsedVertexData.uvs;
  38787. if (uvs) {
  38788. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38789. }
  38790. // uv2s
  38791. var uv2s = parsedVertexData.uv2s;
  38792. if (uv2s) {
  38793. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38794. }
  38795. // uv3s
  38796. var uv3s = parsedVertexData.uv3s;
  38797. if (uv3s) {
  38798. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38799. }
  38800. // uv4s
  38801. var uv4s = parsedVertexData.uv4s;
  38802. if (uv4s) {
  38803. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38804. }
  38805. // uv5s
  38806. var uv5s = parsedVertexData.uv5s;
  38807. if (uv5s) {
  38808. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38809. }
  38810. // uv6s
  38811. var uv6s = parsedVertexData.uv6s;
  38812. if (uv6s) {
  38813. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38814. }
  38815. // colors
  38816. var colors = parsedVertexData.colors;
  38817. if (colors) {
  38818. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38819. }
  38820. // matricesIndices
  38821. var matricesIndices = parsedVertexData.matricesIndices;
  38822. if (matricesIndices) {
  38823. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38824. }
  38825. // matricesWeights
  38826. var matricesWeights = parsedVertexData.matricesWeights;
  38827. if (matricesWeights) {
  38828. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38829. }
  38830. // indices
  38831. var indices = parsedVertexData.indices;
  38832. if (indices) {
  38833. vertexData.indices = indices;
  38834. }
  38835. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38836. };
  38837. return VertexData;
  38838. }());
  38839. BABYLON.VertexData = VertexData;
  38840. })(BABYLON || (BABYLON = {}));
  38841. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38842. var BABYLON;
  38843. (function (BABYLON) {
  38844. /**
  38845. * Class used to store geometry data (vertex buffers + index buffer)
  38846. */
  38847. var Geometry = /** @class */ (function () {
  38848. /**
  38849. * Creates a new geometry
  38850. * @param id defines the unique ID
  38851. * @param scene defines the hosting scene
  38852. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38853. * @param updatable defines if geometry must be updatable (false by default)
  38854. * @param mesh defines the mesh that will be associated with the geometry
  38855. */
  38856. function Geometry(id, scene, vertexData, updatable, mesh) {
  38857. if (updatable === void 0) { updatable = false; }
  38858. if (mesh === void 0) { mesh = null; }
  38859. /**
  38860. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38861. */
  38862. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38863. this._totalVertices = 0;
  38864. this._isDisposed = false;
  38865. this._indexBufferIsUpdatable = false;
  38866. this.id = id;
  38867. this._engine = scene.getEngine();
  38868. this._meshes = [];
  38869. this._scene = scene;
  38870. //Init vertex buffer cache
  38871. this._vertexBuffers = {};
  38872. this._indices = [];
  38873. this._updatable = updatable;
  38874. // vertexData
  38875. if (vertexData) {
  38876. this.setAllVerticesData(vertexData, updatable);
  38877. }
  38878. else {
  38879. this._totalVertices = 0;
  38880. this._indices = [];
  38881. }
  38882. if (this._engine.getCaps().vertexArrayObject) {
  38883. this._vertexArrayObjects = {};
  38884. }
  38885. // applyToMesh
  38886. if (mesh) {
  38887. if (mesh.getClassName() === "LinesMesh") {
  38888. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38889. this._updateExtend();
  38890. }
  38891. this.applyToMesh(mesh);
  38892. mesh.computeWorldMatrix(true);
  38893. }
  38894. }
  38895. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38896. /**
  38897. * 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
  38898. */
  38899. get: function () {
  38900. return this._boundingBias;
  38901. },
  38902. /**
  38903. * 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
  38904. */
  38905. set: function (value) {
  38906. if (this._boundingBias && this._boundingBias.equals(value)) {
  38907. return;
  38908. }
  38909. this._boundingBias = value.clone();
  38910. this._updateBoundingInfo(true, null);
  38911. },
  38912. enumerable: true,
  38913. configurable: true
  38914. });
  38915. /**
  38916. * Static function used to attach a new empty geometry to a mesh
  38917. * @param mesh defines the mesh to attach the geometry to
  38918. * @returns the new {BABYLON.Geometry}
  38919. */
  38920. Geometry.CreateGeometryForMesh = function (mesh) {
  38921. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38922. geometry.applyToMesh(mesh);
  38923. return geometry;
  38924. };
  38925. Object.defineProperty(Geometry.prototype, "extend", {
  38926. /**
  38927. * Gets the current extend of the geometry
  38928. */
  38929. get: function () {
  38930. return this._extend;
  38931. },
  38932. enumerable: true,
  38933. configurable: true
  38934. });
  38935. /**
  38936. * Gets the hosting scene
  38937. * @returns the hosting {BABYLON.Scene}
  38938. */
  38939. Geometry.prototype.getScene = function () {
  38940. return this._scene;
  38941. };
  38942. /**
  38943. * Gets the hosting engine
  38944. * @returns the hosting {BABYLON.Engine}
  38945. */
  38946. Geometry.prototype.getEngine = function () {
  38947. return this._engine;
  38948. };
  38949. /**
  38950. * Defines if the geometry is ready to use
  38951. * @returns true if the geometry is ready to be used
  38952. */
  38953. Geometry.prototype.isReady = function () {
  38954. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38955. };
  38956. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38957. /**
  38958. * Gets a value indicating that the geometry should not be serialized
  38959. */
  38960. get: function () {
  38961. for (var index = 0; index < this._meshes.length; index++) {
  38962. if (!this._meshes[index].doNotSerialize) {
  38963. return false;
  38964. }
  38965. }
  38966. return true;
  38967. },
  38968. enumerable: true,
  38969. configurable: true
  38970. });
  38971. /** @hidden */
  38972. Geometry.prototype._rebuild = function () {
  38973. if (this._vertexArrayObjects) {
  38974. this._vertexArrayObjects = {};
  38975. }
  38976. // Index buffer
  38977. if (this._meshes.length !== 0 && this._indices) {
  38978. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38979. }
  38980. // Vertex buffers
  38981. for (var key in this._vertexBuffers) {
  38982. var vertexBuffer = this._vertexBuffers[key];
  38983. vertexBuffer._rebuild();
  38984. }
  38985. };
  38986. /**
  38987. * Affects all geometry data in one call
  38988. * @param vertexData defines the geometry data
  38989. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38990. */
  38991. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38992. vertexData.applyToGeometry(this, updatable);
  38993. this.notifyUpdate();
  38994. };
  38995. /**
  38996. * Set specific vertex data
  38997. * @param kind defines the data kind (Position, normal, etc...)
  38998. * @param data defines the vertex data to use
  38999. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39000. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39001. */
  39002. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39003. if (updatable === void 0) { updatable = false; }
  39004. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39005. this.setVerticesBuffer(buffer);
  39006. };
  39007. /**
  39008. * Removes a specific vertex data
  39009. * @param kind defines the data kind (Position, normal, etc...)
  39010. */
  39011. Geometry.prototype.removeVerticesData = function (kind) {
  39012. if (this._vertexBuffers[kind]) {
  39013. this._vertexBuffers[kind].dispose();
  39014. delete this._vertexBuffers[kind];
  39015. }
  39016. };
  39017. /**
  39018. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39019. * @param buffer defines the vertex buffer to use
  39020. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39021. */
  39022. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39023. if (totalVertices === void 0) { totalVertices = null; }
  39024. var kind = buffer.getKind();
  39025. if (this._vertexBuffers[kind]) {
  39026. this._vertexBuffers[kind].dispose();
  39027. }
  39028. this._vertexBuffers[kind] = buffer;
  39029. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39030. var data = buffer.getData();
  39031. if (totalVertices != null) {
  39032. this._totalVertices = totalVertices;
  39033. }
  39034. else {
  39035. if (data != null) {
  39036. this._totalVertices = data.length / (buffer.byteStride / 4);
  39037. }
  39038. }
  39039. this._updateExtend(data);
  39040. this._resetPointsArrayCache();
  39041. var meshes = this._meshes;
  39042. var numOfMeshes = meshes.length;
  39043. for (var index = 0; index < numOfMeshes; index++) {
  39044. var mesh = meshes[index];
  39045. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39046. mesh._createGlobalSubMesh(false);
  39047. mesh.computeWorldMatrix(true);
  39048. }
  39049. }
  39050. this.notifyUpdate(kind);
  39051. if (this._vertexArrayObjects) {
  39052. this._disposeVertexArrayObjects();
  39053. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39054. }
  39055. };
  39056. /**
  39057. * Update a specific vertex buffer
  39058. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39059. * It will do nothing if the buffer is not updatable
  39060. * @param kind defines the data kind (Position, normal, etc...)
  39061. * @param data defines the data to use
  39062. * @param offset defines the offset in the target buffer where to store the data
  39063. * @param useBytes set to true if the offset is in bytes
  39064. */
  39065. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39066. if (useBytes === void 0) { useBytes = false; }
  39067. var vertexBuffer = this.getVertexBuffer(kind);
  39068. if (!vertexBuffer) {
  39069. return;
  39070. }
  39071. vertexBuffer.updateDirectly(data, offset, useBytes);
  39072. this.notifyUpdate(kind);
  39073. };
  39074. /**
  39075. * Update a specific vertex buffer
  39076. * This function will create a new buffer if the current one is not updatable
  39077. * @param kind defines the data kind (Position, normal, etc...)
  39078. * @param data defines the data to use
  39079. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39080. */
  39081. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39082. if (updateExtends === void 0) { updateExtends = false; }
  39083. var vertexBuffer = this.getVertexBuffer(kind);
  39084. if (!vertexBuffer) {
  39085. return;
  39086. }
  39087. vertexBuffer.update(data);
  39088. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39089. this._updateBoundingInfo(updateExtends, data);
  39090. }
  39091. this.notifyUpdate(kind);
  39092. };
  39093. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39094. if (updateExtends) {
  39095. this._updateExtend(data);
  39096. }
  39097. var meshes = this._meshes;
  39098. var numOfMeshes = meshes.length;
  39099. this._resetPointsArrayCache();
  39100. for (var index = 0; index < numOfMeshes; index++) {
  39101. var mesh = meshes[index];
  39102. if (updateExtends) {
  39103. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39104. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39105. var subMesh = mesh.subMeshes[subIndex];
  39106. subMesh.refreshBoundingInfo();
  39107. }
  39108. }
  39109. }
  39110. };
  39111. /** @hidden */
  39112. Geometry.prototype._bind = function (effect, indexToBind) {
  39113. if (!effect) {
  39114. return;
  39115. }
  39116. if (indexToBind === undefined) {
  39117. indexToBind = this._indexBuffer;
  39118. }
  39119. var vbs = this.getVertexBuffers();
  39120. if (!vbs) {
  39121. return;
  39122. }
  39123. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39124. this._engine.bindBuffers(vbs, indexToBind, effect);
  39125. return;
  39126. }
  39127. // Using VAO
  39128. if (!this._vertexArrayObjects[effect.key]) {
  39129. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39130. }
  39131. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39132. };
  39133. /**
  39134. * Gets total number of vertices
  39135. * @returns the total number of vertices
  39136. */
  39137. Geometry.prototype.getTotalVertices = function () {
  39138. if (!this.isReady()) {
  39139. return 0;
  39140. }
  39141. return this._totalVertices;
  39142. };
  39143. /**
  39144. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39145. * @param kind defines the data kind (Position, normal, etc...)
  39146. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39147. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39148. * @returns a float array containing vertex data
  39149. */
  39150. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39151. var vertexBuffer = this.getVertexBuffer(kind);
  39152. if (!vertexBuffer) {
  39153. return null;
  39154. }
  39155. var data = vertexBuffer.getData();
  39156. if (!data) {
  39157. return null;
  39158. }
  39159. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39160. var count = this._totalVertices * vertexBuffer.getSize();
  39161. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39162. var copy_1 = new Array(count);
  39163. vertexBuffer.forEach(count, function (value, index) {
  39164. copy_1[index] = value;
  39165. });
  39166. return copy_1;
  39167. }
  39168. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39169. if (data instanceof Array) {
  39170. var offset = vertexBuffer.byteOffset / 4;
  39171. return BABYLON.Tools.Slice(data, offset, offset + count);
  39172. }
  39173. else if (data instanceof ArrayBuffer) {
  39174. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39175. }
  39176. else {
  39177. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39178. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39179. var result = new Float32Array(count);
  39180. var source = new Float32Array(data.buffer, offset, count);
  39181. result.set(source);
  39182. return result;
  39183. }
  39184. return new Float32Array(data.buffer, offset, count);
  39185. }
  39186. }
  39187. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39188. return BABYLON.Tools.Slice(data);
  39189. }
  39190. return data;
  39191. };
  39192. /**
  39193. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39194. * @param kind defines the data kind (Position, normal, etc...)
  39195. * @returns true if the vertex buffer with the specified kind is updatable
  39196. */
  39197. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39198. var vb = this._vertexBuffers[kind];
  39199. if (!vb) {
  39200. return false;
  39201. }
  39202. return vb.isUpdatable();
  39203. };
  39204. /**
  39205. * Gets a specific vertex buffer
  39206. * @param kind defines the data kind (Position, normal, etc...)
  39207. * @returns a {BABYLON.VertexBuffer}
  39208. */
  39209. Geometry.prototype.getVertexBuffer = function (kind) {
  39210. if (!this.isReady()) {
  39211. return null;
  39212. }
  39213. return this._vertexBuffers[kind];
  39214. };
  39215. /**
  39216. * Returns all vertex buffers
  39217. * @return an object holding all vertex buffers indexed by kind
  39218. */
  39219. Geometry.prototype.getVertexBuffers = function () {
  39220. if (!this.isReady()) {
  39221. return null;
  39222. }
  39223. return this._vertexBuffers;
  39224. };
  39225. /**
  39226. * Gets a boolean indicating if specific vertex buffer is present
  39227. * @param kind defines the data kind (Position, normal, etc...)
  39228. * @returns true if data is present
  39229. */
  39230. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39231. if (!this._vertexBuffers) {
  39232. if (this._delayInfo) {
  39233. return this._delayInfo.indexOf(kind) !== -1;
  39234. }
  39235. return false;
  39236. }
  39237. return this._vertexBuffers[kind] !== undefined;
  39238. };
  39239. /**
  39240. * Gets a list of all attached data kinds (Position, normal, etc...)
  39241. * @returns a list of string containing all kinds
  39242. */
  39243. Geometry.prototype.getVerticesDataKinds = function () {
  39244. var result = [];
  39245. var kind;
  39246. if (!this._vertexBuffers && this._delayInfo) {
  39247. for (kind in this._delayInfo) {
  39248. result.push(kind);
  39249. }
  39250. }
  39251. else {
  39252. for (kind in this._vertexBuffers) {
  39253. result.push(kind);
  39254. }
  39255. }
  39256. return result;
  39257. };
  39258. /**
  39259. * Update index buffer
  39260. * @param indices defines the indices to store in the index buffer
  39261. * @param offset defines the offset in the target buffer where to store the data
  39262. */
  39263. Geometry.prototype.updateIndices = function (indices, offset) {
  39264. if (!this._indexBuffer) {
  39265. return;
  39266. }
  39267. if (!this._indexBufferIsUpdatable) {
  39268. this.setIndices(indices, null, true);
  39269. }
  39270. else {
  39271. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39272. }
  39273. };
  39274. /**
  39275. * Creates a new index buffer
  39276. * @param indices defines the indices to store in the index buffer
  39277. * @param totalVertices defines the total number of vertices (could be null)
  39278. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39279. */
  39280. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39281. if (totalVertices === void 0) { totalVertices = null; }
  39282. if (updatable === void 0) { updatable = false; }
  39283. if (this._indexBuffer) {
  39284. this._engine._releaseBuffer(this._indexBuffer);
  39285. }
  39286. this._disposeVertexArrayObjects();
  39287. this._indices = indices;
  39288. this._indexBufferIsUpdatable = updatable;
  39289. if (this._meshes.length !== 0 && this._indices) {
  39290. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39291. }
  39292. if (totalVertices != undefined) { // including null and undefined
  39293. this._totalVertices = totalVertices;
  39294. }
  39295. var meshes = this._meshes;
  39296. var numOfMeshes = meshes.length;
  39297. for (var index = 0; index < numOfMeshes; index++) {
  39298. meshes[index]._createGlobalSubMesh(true);
  39299. }
  39300. this.notifyUpdate();
  39301. };
  39302. /**
  39303. * Return the total number of indices
  39304. * @returns the total number of indices
  39305. */
  39306. Geometry.prototype.getTotalIndices = function () {
  39307. if (!this.isReady()) {
  39308. return 0;
  39309. }
  39310. return this._indices.length;
  39311. };
  39312. /**
  39313. * Gets the index buffer array
  39314. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39315. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39316. * @returns the index buffer array
  39317. */
  39318. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39319. if (!this.isReady()) {
  39320. return null;
  39321. }
  39322. var orig = this._indices;
  39323. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39324. return orig;
  39325. }
  39326. else {
  39327. var len = orig.length;
  39328. var copy = [];
  39329. for (var i = 0; i < len; i++) {
  39330. copy.push(orig[i]);
  39331. }
  39332. return copy;
  39333. }
  39334. };
  39335. /**
  39336. * Gets the index buffer
  39337. * @return the index buffer
  39338. */
  39339. Geometry.prototype.getIndexBuffer = function () {
  39340. if (!this.isReady()) {
  39341. return null;
  39342. }
  39343. return this._indexBuffer;
  39344. };
  39345. /** @hidden */
  39346. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39347. if (effect === void 0) { effect = null; }
  39348. if (!effect || !this._vertexArrayObjects) {
  39349. return;
  39350. }
  39351. if (this._vertexArrayObjects[effect.key]) {
  39352. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39353. delete this._vertexArrayObjects[effect.key];
  39354. }
  39355. };
  39356. /**
  39357. * Release the associated resources for a specific mesh
  39358. * @param mesh defines the source mesh
  39359. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39360. */
  39361. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39362. var meshes = this._meshes;
  39363. var index = meshes.indexOf(mesh);
  39364. if (index === -1) {
  39365. return;
  39366. }
  39367. meshes.splice(index, 1);
  39368. mesh._geometry = null;
  39369. if (meshes.length === 0 && shouldDispose) {
  39370. this.dispose();
  39371. }
  39372. };
  39373. /**
  39374. * Apply current geometry to a given mesh
  39375. * @param mesh defines the mesh to apply geometry to
  39376. */
  39377. Geometry.prototype.applyToMesh = function (mesh) {
  39378. if (mesh._geometry === this) {
  39379. return;
  39380. }
  39381. var previousGeometry = mesh._geometry;
  39382. if (previousGeometry) {
  39383. previousGeometry.releaseForMesh(mesh);
  39384. }
  39385. var meshes = this._meshes;
  39386. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39387. mesh._geometry = this;
  39388. this._scene.pushGeometry(this);
  39389. meshes.push(mesh);
  39390. if (this.isReady()) {
  39391. this._applyToMesh(mesh);
  39392. }
  39393. else {
  39394. mesh._boundingInfo = this._boundingInfo;
  39395. }
  39396. };
  39397. Geometry.prototype._updateExtend = function (data) {
  39398. if (data === void 0) { data = null; }
  39399. if (!data) {
  39400. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39401. }
  39402. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39403. };
  39404. Geometry.prototype._applyToMesh = function (mesh) {
  39405. var numOfMeshes = this._meshes.length;
  39406. // vertexBuffers
  39407. for (var kind in this._vertexBuffers) {
  39408. if (numOfMeshes === 1) {
  39409. this._vertexBuffers[kind].create();
  39410. }
  39411. var buffer = this._vertexBuffers[kind].getBuffer();
  39412. if (buffer)
  39413. buffer.references = numOfMeshes;
  39414. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39415. if (!this._extend) {
  39416. this._updateExtend();
  39417. }
  39418. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39419. mesh._createGlobalSubMesh(false);
  39420. //bounding info was just created again, world matrix should be applied again.
  39421. mesh._updateBoundingInfo();
  39422. }
  39423. }
  39424. // indexBuffer
  39425. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39426. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39427. }
  39428. if (this._indexBuffer) {
  39429. this._indexBuffer.references = numOfMeshes;
  39430. }
  39431. };
  39432. Geometry.prototype.notifyUpdate = function (kind) {
  39433. if (this.onGeometryUpdated) {
  39434. this.onGeometryUpdated(this, kind);
  39435. }
  39436. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39437. var mesh = _a[_i];
  39438. mesh._markSubMeshesAsAttributesDirty();
  39439. }
  39440. };
  39441. /**
  39442. * Load the geometry if it was flagged as delay loaded
  39443. * @param scene defines the hosting scene
  39444. * @param onLoaded defines a callback called when the geometry is loaded
  39445. */
  39446. Geometry.prototype.load = function (scene, onLoaded) {
  39447. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39448. return;
  39449. }
  39450. if (this.isReady()) {
  39451. if (onLoaded) {
  39452. onLoaded();
  39453. }
  39454. return;
  39455. }
  39456. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39457. this._queueLoad(scene, onLoaded);
  39458. };
  39459. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39460. var _this = this;
  39461. if (!this.delayLoadingFile) {
  39462. return;
  39463. }
  39464. scene._addPendingData(this);
  39465. scene._loadFile(this.delayLoadingFile, function (data) {
  39466. if (!_this._delayLoadingFunction) {
  39467. return;
  39468. }
  39469. _this._delayLoadingFunction(JSON.parse(data), _this);
  39470. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39471. _this._delayInfo = [];
  39472. scene._removePendingData(_this);
  39473. var meshes = _this._meshes;
  39474. var numOfMeshes = meshes.length;
  39475. for (var index = 0; index < numOfMeshes; index++) {
  39476. _this._applyToMesh(meshes[index]);
  39477. }
  39478. if (onLoaded) {
  39479. onLoaded();
  39480. }
  39481. }, undefined, true);
  39482. };
  39483. /**
  39484. * Invert the geometry to move from a right handed system to a left handed one.
  39485. */
  39486. Geometry.prototype.toLeftHanded = function () {
  39487. // Flip faces
  39488. var tIndices = this.getIndices(false);
  39489. if (tIndices != null && tIndices.length > 0) {
  39490. for (var i = 0; i < tIndices.length; i += 3) {
  39491. var tTemp = tIndices[i + 0];
  39492. tIndices[i + 0] = tIndices[i + 2];
  39493. tIndices[i + 2] = tTemp;
  39494. }
  39495. this.setIndices(tIndices);
  39496. }
  39497. // Negate position.z
  39498. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39499. if (tPositions != null && tPositions.length > 0) {
  39500. for (var i = 0; i < tPositions.length; i += 3) {
  39501. tPositions[i + 2] = -tPositions[i + 2];
  39502. }
  39503. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39504. }
  39505. // Negate normal.z
  39506. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39507. if (tNormals != null && tNormals.length > 0) {
  39508. for (var i = 0; i < tNormals.length; i += 3) {
  39509. tNormals[i + 2] = -tNormals[i + 2];
  39510. }
  39511. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39512. }
  39513. };
  39514. // Cache
  39515. /** @hidden */
  39516. Geometry.prototype._resetPointsArrayCache = function () {
  39517. this._positions = null;
  39518. };
  39519. /** @hidden */
  39520. Geometry.prototype._generatePointsArray = function () {
  39521. if (this._positions)
  39522. return true;
  39523. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39524. if (!data || data.length === 0) {
  39525. return false;
  39526. }
  39527. this._positions = [];
  39528. for (var index = 0; index < data.length; index += 3) {
  39529. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39530. }
  39531. return true;
  39532. };
  39533. /**
  39534. * Gets a value indicating if the geometry is disposed
  39535. * @returns true if the geometry was disposed
  39536. */
  39537. Geometry.prototype.isDisposed = function () {
  39538. return this._isDisposed;
  39539. };
  39540. Geometry.prototype._disposeVertexArrayObjects = function () {
  39541. if (this._vertexArrayObjects) {
  39542. for (var kind in this._vertexArrayObjects) {
  39543. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39544. }
  39545. this._vertexArrayObjects = {};
  39546. }
  39547. };
  39548. /**
  39549. * Free all associated resources
  39550. */
  39551. Geometry.prototype.dispose = function () {
  39552. var meshes = this._meshes;
  39553. var numOfMeshes = meshes.length;
  39554. var index;
  39555. for (index = 0; index < numOfMeshes; index++) {
  39556. this.releaseForMesh(meshes[index]);
  39557. }
  39558. this._meshes = [];
  39559. this._disposeVertexArrayObjects();
  39560. for (var kind in this._vertexBuffers) {
  39561. this._vertexBuffers[kind].dispose();
  39562. }
  39563. this._vertexBuffers = {};
  39564. this._totalVertices = 0;
  39565. if (this._indexBuffer) {
  39566. this._engine._releaseBuffer(this._indexBuffer);
  39567. }
  39568. this._indexBuffer = null;
  39569. this._indices = [];
  39570. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39571. this.delayLoadingFile = null;
  39572. this._delayLoadingFunction = null;
  39573. this._delayInfo = [];
  39574. this._boundingInfo = null;
  39575. this._scene.removeGeometry(this);
  39576. this._isDisposed = true;
  39577. };
  39578. /**
  39579. * Clone the current geometry into a new geometry
  39580. * @param id defines the unique ID of the new geometry
  39581. * @returns a new geometry object
  39582. */
  39583. Geometry.prototype.copy = function (id) {
  39584. var vertexData = new BABYLON.VertexData();
  39585. vertexData.indices = [];
  39586. var indices = this.getIndices();
  39587. if (indices) {
  39588. for (var index = 0; index < indices.length; index++) {
  39589. vertexData.indices.push(indices[index]);
  39590. }
  39591. }
  39592. var updatable = false;
  39593. var stopChecking = false;
  39594. var kind;
  39595. for (kind in this._vertexBuffers) {
  39596. // using slice() to make a copy of the array and not just reference it
  39597. var data = this.getVerticesData(kind);
  39598. if (data instanceof Float32Array) {
  39599. vertexData.set(new Float32Array(data), kind);
  39600. }
  39601. else {
  39602. vertexData.set(data.slice(0), kind);
  39603. }
  39604. if (!stopChecking) {
  39605. var vb = this.getVertexBuffer(kind);
  39606. if (vb) {
  39607. updatable = vb.isUpdatable();
  39608. stopChecking = !updatable;
  39609. }
  39610. }
  39611. }
  39612. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39613. geometry.delayLoadState = this.delayLoadState;
  39614. geometry.delayLoadingFile = this.delayLoadingFile;
  39615. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39616. for (kind in this._delayInfo) {
  39617. geometry._delayInfo = geometry._delayInfo || [];
  39618. geometry._delayInfo.push(kind);
  39619. }
  39620. // Bounding info
  39621. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39622. return geometry;
  39623. };
  39624. /**
  39625. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39626. * @return a JSON representation of the current geometry data (without the vertices data)
  39627. */
  39628. Geometry.prototype.serialize = function () {
  39629. var serializationObject = {};
  39630. serializationObject.id = this.id;
  39631. serializationObject.updatable = this._updatable;
  39632. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39633. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39634. }
  39635. return serializationObject;
  39636. };
  39637. Geometry.prototype.toNumberArray = function (origin) {
  39638. if (Array.isArray(origin)) {
  39639. return origin;
  39640. }
  39641. else {
  39642. return Array.prototype.slice.call(origin);
  39643. }
  39644. };
  39645. /**
  39646. * Serialize all vertices data into a JSON oject
  39647. * @returns a JSON representation of the current geometry data
  39648. */
  39649. Geometry.prototype.serializeVerticeData = function () {
  39650. var serializationObject = this.serialize();
  39651. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39652. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39653. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39654. serializationObject.positions._updatable = true;
  39655. }
  39656. }
  39657. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39658. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39659. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39660. serializationObject.normals._updatable = true;
  39661. }
  39662. }
  39663. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39664. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39665. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39666. serializationObject.tangets._updatable = true;
  39667. }
  39668. }
  39669. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39670. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39671. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39672. serializationObject.uvs._updatable = true;
  39673. }
  39674. }
  39675. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39676. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39677. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39678. serializationObject.uv2s._updatable = true;
  39679. }
  39680. }
  39681. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39682. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39683. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39684. serializationObject.uv3s._updatable = true;
  39685. }
  39686. }
  39687. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39688. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39689. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39690. serializationObject.uv4s._updatable = true;
  39691. }
  39692. }
  39693. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39694. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39695. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39696. serializationObject.uv5s._updatable = true;
  39697. }
  39698. }
  39699. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39700. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39701. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39702. serializationObject.uv6s._updatable = true;
  39703. }
  39704. }
  39705. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39706. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39707. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39708. serializationObject.colors._updatable = true;
  39709. }
  39710. }
  39711. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39712. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39713. serializationObject.matricesIndices._isExpanded = true;
  39714. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39715. serializationObject.matricesIndices._updatable = true;
  39716. }
  39717. }
  39718. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39719. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39720. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39721. serializationObject.matricesWeights._updatable = true;
  39722. }
  39723. }
  39724. serializationObject.indices = this.toNumberArray(this.getIndices());
  39725. return serializationObject;
  39726. };
  39727. // Statics
  39728. /**
  39729. * Extracts a clone of a mesh geometry
  39730. * @param mesh defines the source mesh
  39731. * @param id defines the unique ID of the new geometry object
  39732. * @returns the new geometry object
  39733. */
  39734. Geometry.ExtractFromMesh = function (mesh, id) {
  39735. var geometry = mesh._geometry;
  39736. if (!geometry) {
  39737. return null;
  39738. }
  39739. return geometry.copy(id);
  39740. };
  39741. /**
  39742. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39743. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39744. * Be aware Math.random() could cause collisions, but:
  39745. * "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"
  39746. * @returns a string containing a new GUID
  39747. */
  39748. Geometry.RandomId = function () {
  39749. return BABYLON.Tools.RandomId();
  39750. };
  39751. /** @hidden */
  39752. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39753. var scene = mesh.getScene();
  39754. // Geometry
  39755. var geometryId = parsedGeometry.geometryId;
  39756. if (geometryId) {
  39757. var geometry = scene.getGeometryByID(geometryId);
  39758. if (geometry) {
  39759. geometry.applyToMesh(mesh);
  39760. }
  39761. }
  39762. else if (parsedGeometry instanceof ArrayBuffer) {
  39763. var binaryInfo = mesh._binaryInfo;
  39764. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39765. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39766. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39767. }
  39768. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39769. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39770. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39771. }
  39772. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39773. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39774. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39775. }
  39776. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39777. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39778. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39779. }
  39780. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39781. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39782. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39783. }
  39784. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39785. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39786. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39787. }
  39788. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39789. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39790. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39791. }
  39792. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39793. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39794. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39795. }
  39796. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39797. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39798. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39799. }
  39800. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39801. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39802. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39803. }
  39804. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39805. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39806. var floatIndices = [];
  39807. for (var i = 0; i < matricesIndicesData.length; i++) {
  39808. var index = matricesIndicesData[i];
  39809. floatIndices.push(index & 0x000000FF);
  39810. floatIndices.push((index & 0x0000FF00) >> 8);
  39811. floatIndices.push((index & 0x00FF0000) >> 16);
  39812. floatIndices.push(index >> 24);
  39813. }
  39814. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39815. }
  39816. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39817. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39818. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39819. }
  39820. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39821. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39822. mesh.setIndices(indicesData, null);
  39823. }
  39824. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39825. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39826. mesh.subMeshes = [];
  39827. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39828. var materialIndex = subMeshesData[(i * 5) + 0];
  39829. var verticesStart = subMeshesData[(i * 5) + 1];
  39830. var verticesCount = subMeshesData[(i * 5) + 2];
  39831. var indexStart = subMeshesData[(i * 5) + 3];
  39832. var indexCount = subMeshesData[(i * 5) + 4];
  39833. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39834. }
  39835. }
  39836. }
  39837. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39838. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39839. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39840. if (parsedGeometry.tangents) {
  39841. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39842. }
  39843. if (parsedGeometry.uvs) {
  39844. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39845. }
  39846. if (parsedGeometry.uvs2) {
  39847. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39848. }
  39849. if (parsedGeometry.uvs3) {
  39850. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39851. }
  39852. if (parsedGeometry.uvs4) {
  39853. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39854. }
  39855. if (parsedGeometry.uvs5) {
  39856. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39857. }
  39858. if (parsedGeometry.uvs6) {
  39859. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39860. }
  39861. if (parsedGeometry.colors) {
  39862. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39863. }
  39864. if (parsedGeometry.matricesIndices) {
  39865. if (!parsedGeometry.matricesIndices._isExpanded) {
  39866. var floatIndices = [];
  39867. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39868. var matricesIndex = parsedGeometry.matricesIndices[i];
  39869. floatIndices.push(matricesIndex & 0x000000FF);
  39870. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39871. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39872. floatIndices.push(matricesIndex >> 24);
  39873. }
  39874. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39875. }
  39876. else {
  39877. delete parsedGeometry.matricesIndices._isExpanded;
  39878. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39879. }
  39880. }
  39881. if (parsedGeometry.matricesIndicesExtra) {
  39882. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39883. var floatIndices = [];
  39884. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39885. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39886. floatIndices.push(matricesIndex & 0x000000FF);
  39887. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39888. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39889. floatIndices.push(matricesIndex >> 24);
  39890. }
  39891. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39892. }
  39893. else {
  39894. delete parsedGeometry.matricesIndices._isExpanded;
  39895. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39896. }
  39897. }
  39898. if (parsedGeometry.matricesWeights) {
  39899. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39900. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39901. }
  39902. if (parsedGeometry.matricesWeightsExtra) {
  39903. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39904. }
  39905. mesh.setIndices(parsedGeometry.indices, null);
  39906. }
  39907. // SubMeshes
  39908. if (parsedGeometry.subMeshes) {
  39909. mesh.subMeshes = [];
  39910. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39911. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39912. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39913. }
  39914. }
  39915. // Flat shading
  39916. if (mesh._shouldGenerateFlatShading) {
  39917. mesh.convertToFlatShadedMesh();
  39918. delete mesh._shouldGenerateFlatShading;
  39919. }
  39920. // Update
  39921. mesh.computeWorldMatrix(true);
  39922. // Octree
  39923. var sceneOctree = scene.selectionOctree;
  39924. if (sceneOctree !== undefined && sceneOctree !== null) {
  39925. sceneOctree.addMesh(mesh);
  39926. }
  39927. };
  39928. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39929. var epsilon = 1e-3;
  39930. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39931. return;
  39932. }
  39933. var noInfluenceBoneIndex = 0.0;
  39934. if (parsedGeometry.skeletonId > -1) {
  39935. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39936. if (!skeleton) {
  39937. return;
  39938. }
  39939. noInfluenceBoneIndex = skeleton.bones.length;
  39940. }
  39941. else {
  39942. return;
  39943. }
  39944. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39945. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39946. var matricesWeights = parsedGeometry.matricesWeights;
  39947. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39948. var influencers = parsedGeometry.numBoneInfluencer;
  39949. var size = matricesWeights.length;
  39950. for (var i = 0; i < size; i += 4) {
  39951. var weight = 0.0;
  39952. var firstZeroWeight = -1;
  39953. for (var j = 0; j < 4; j++) {
  39954. var w = matricesWeights[i + j];
  39955. weight += w;
  39956. if (w < epsilon && firstZeroWeight < 0) {
  39957. firstZeroWeight = j;
  39958. }
  39959. }
  39960. if (matricesWeightsExtra) {
  39961. for (var j = 0; j < 4; j++) {
  39962. var w = matricesWeightsExtra[i + j];
  39963. weight += w;
  39964. if (w < epsilon && firstZeroWeight < 0) {
  39965. firstZeroWeight = j + 4;
  39966. }
  39967. }
  39968. }
  39969. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39970. firstZeroWeight = influencers - 1;
  39971. }
  39972. if (weight > epsilon) {
  39973. var mweight = 1.0 / weight;
  39974. for (var j = 0; j < 4; j++) {
  39975. matricesWeights[i + j] *= mweight;
  39976. }
  39977. if (matricesWeightsExtra) {
  39978. for (var j = 0; j < 4; j++) {
  39979. matricesWeightsExtra[i + j] *= mweight;
  39980. }
  39981. }
  39982. }
  39983. else {
  39984. if (firstZeroWeight >= 4) {
  39985. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39986. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39987. }
  39988. else {
  39989. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39990. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39991. }
  39992. }
  39993. }
  39994. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39995. if (parsedGeometry.matricesWeightsExtra) {
  39996. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39997. }
  39998. };
  39999. /**
  40000. * Create a new geometry from persisted data (Using .babylon file format)
  40001. * @param parsedVertexData defines the persisted data
  40002. * @param scene defines the hosting scene
  40003. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40004. * @returns the new geometry object
  40005. */
  40006. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40007. if (scene.getGeometryByID(parsedVertexData.id)) {
  40008. return null; // null since geometry could be something else than a box...
  40009. }
  40010. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40011. if (BABYLON.Tags) {
  40012. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40013. }
  40014. if (parsedVertexData.delayLoadingFile) {
  40015. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40016. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40017. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40018. geometry._delayInfo = [];
  40019. if (parsedVertexData.hasUVs) {
  40020. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40021. }
  40022. if (parsedVertexData.hasUVs2) {
  40023. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40024. }
  40025. if (parsedVertexData.hasUVs3) {
  40026. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40027. }
  40028. if (parsedVertexData.hasUVs4) {
  40029. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40030. }
  40031. if (parsedVertexData.hasUVs5) {
  40032. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40033. }
  40034. if (parsedVertexData.hasUVs6) {
  40035. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40036. }
  40037. if (parsedVertexData.hasColors) {
  40038. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40039. }
  40040. if (parsedVertexData.hasMatricesIndices) {
  40041. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40042. }
  40043. if (parsedVertexData.hasMatricesWeights) {
  40044. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40045. }
  40046. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40047. }
  40048. else {
  40049. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40050. }
  40051. scene.pushGeometry(geometry, true);
  40052. return geometry;
  40053. };
  40054. return Geometry;
  40055. }());
  40056. BABYLON.Geometry = Geometry;
  40057. // Primitives
  40058. /// Abstract class
  40059. /**
  40060. * Abstract class used to provide common services for all typed geometries
  40061. * @hidden
  40062. */
  40063. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40064. __extends(_PrimitiveGeometry, _super);
  40065. /**
  40066. * Creates a new typed geometry
  40067. * @param id defines the unique ID of the geometry
  40068. * @param scene defines the hosting scene
  40069. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40070. * @param mesh defines the hosting mesh (can be null)
  40071. */
  40072. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40073. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40074. if (mesh === void 0) { mesh = null; }
  40075. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40076. _this._canBeRegenerated = _canBeRegenerated;
  40077. _this._beingRegenerated = true;
  40078. _this.regenerate();
  40079. _this._beingRegenerated = false;
  40080. return _this;
  40081. }
  40082. /**
  40083. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40084. * @returns true if the geometry can be regenerated
  40085. */
  40086. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40087. return this._canBeRegenerated;
  40088. };
  40089. /**
  40090. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40091. */
  40092. _PrimitiveGeometry.prototype.regenerate = function () {
  40093. if (!this._canBeRegenerated) {
  40094. return;
  40095. }
  40096. this._beingRegenerated = true;
  40097. this.setAllVerticesData(this._regenerateVertexData(), false);
  40098. this._beingRegenerated = false;
  40099. };
  40100. /**
  40101. * Clone the geometry
  40102. * @param id defines the unique ID of the new geometry
  40103. * @returns the new geometry
  40104. */
  40105. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40106. return _super.prototype.copy.call(this, id);
  40107. };
  40108. // overrides
  40109. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40110. if (!this._beingRegenerated) {
  40111. return;
  40112. }
  40113. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40114. };
  40115. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40116. if (!this._beingRegenerated) {
  40117. return;
  40118. }
  40119. _super.prototype.setVerticesData.call(this, kind, data, false);
  40120. };
  40121. // to override
  40122. /** @hidden */
  40123. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40124. throw new Error("Abstract method");
  40125. };
  40126. _PrimitiveGeometry.prototype.copy = function (id) {
  40127. throw new Error("Must be overriden in sub-classes.");
  40128. };
  40129. _PrimitiveGeometry.prototype.serialize = function () {
  40130. var serializationObject = _super.prototype.serialize.call(this);
  40131. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40132. return serializationObject;
  40133. };
  40134. return _PrimitiveGeometry;
  40135. }(Geometry));
  40136. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40137. /**
  40138. * Creates a ribbon geometry
  40139. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40140. */
  40141. var RibbonGeometry = /** @class */ (function (_super) {
  40142. __extends(RibbonGeometry, _super);
  40143. /**
  40144. * Creates a ribbon geometry
  40145. * @param id defines the unique ID of the geometry
  40146. * @param scene defines the hosting scene
  40147. * @param pathArray defines the array of paths to use
  40148. * @param closeArray defines if the last path and the first path must be joined
  40149. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40150. * @param offset defines the offset between points
  40151. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40152. * @param mesh defines the hosting mesh (can be null)
  40153. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40154. */
  40155. function RibbonGeometry(id, scene,
  40156. /**
  40157. * Defines the array of paths to use
  40158. */
  40159. pathArray,
  40160. /**
  40161. * Defines if the last and first points of each path in your pathArray must be joined
  40162. */
  40163. closeArray,
  40164. /**
  40165. * Defines if the last and first points of each path in your pathArray must be joined
  40166. */
  40167. closePath,
  40168. /**
  40169. * Defines the offset between points
  40170. */
  40171. offset, canBeRegenerated, mesh,
  40172. /**
  40173. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40174. */
  40175. side) {
  40176. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40177. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40178. _this.pathArray = pathArray;
  40179. _this.closeArray = closeArray;
  40180. _this.closePath = closePath;
  40181. _this.offset = offset;
  40182. _this.side = side;
  40183. return _this;
  40184. }
  40185. /** @hidden */
  40186. RibbonGeometry.prototype._regenerateVertexData = function () {
  40187. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40188. };
  40189. RibbonGeometry.prototype.copy = function (id) {
  40190. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40191. };
  40192. return RibbonGeometry;
  40193. }(_PrimitiveGeometry));
  40194. BABYLON.RibbonGeometry = RibbonGeometry;
  40195. /**
  40196. * Creates a box geometry
  40197. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40198. */
  40199. var BoxGeometry = /** @class */ (function (_super) {
  40200. __extends(BoxGeometry, _super);
  40201. /**
  40202. * Creates a box geometry
  40203. * @param id defines the unique ID of the geometry
  40204. * @param scene defines the hosting scene
  40205. * @param size defines the zise of the box (width, height and depth are the same)
  40206. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40207. * @param mesh defines the hosting mesh (can be null)
  40208. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40209. */
  40210. function BoxGeometry(id, scene,
  40211. /**
  40212. * Defines the zise of the box (width, height and depth are the same)
  40213. */
  40214. size, canBeRegenerated, mesh,
  40215. /**
  40216. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40217. */
  40218. side) {
  40219. if (mesh === void 0) { mesh = null; }
  40220. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40221. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40222. _this.size = size;
  40223. _this.side = side;
  40224. return _this;
  40225. }
  40226. /** @hidden */
  40227. BoxGeometry.prototype._regenerateVertexData = function () {
  40228. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40229. };
  40230. BoxGeometry.prototype.copy = function (id) {
  40231. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40232. };
  40233. BoxGeometry.prototype.serialize = function () {
  40234. var serializationObject = _super.prototype.serialize.call(this);
  40235. serializationObject.size = this.size;
  40236. return serializationObject;
  40237. };
  40238. BoxGeometry.Parse = function (parsedBox, scene) {
  40239. if (scene.getGeometryByID(parsedBox.id)) {
  40240. return null; // null since geometry could be something else than a box...
  40241. }
  40242. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40243. if (BABYLON.Tags) {
  40244. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40245. }
  40246. scene.pushGeometry(box, true);
  40247. return box;
  40248. };
  40249. return BoxGeometry;
  40250. }(_PrimitiveGeometry));
  40251. BABYLON.BoxGeometry = BoxGeometry;
  40252. /**
  40253. * Creates a sphere geometry
  40254. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40255. */
  40256. var SphereGeometry = /** @class */ (function (_super) {
  40257. __extends(SphereGeometry, _super);
  40258. /**
  40259. * Create a new sphere geometry
  40260. * @param id defines the unique ID of the geometry
  40261. * @param scene defines the hosting scene
  40262. * @param segments defines the number of segments to use to create the sphere
  40263. * @param diameter defines the diameter of the sphere
  40264. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40265. * @param mesh defines the hosting mesh (can be null)
  40266. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40267. */
  40268. function SphereGeometry(id, scene,
  40269. /**
  40270. * Defines the number of segments to use to create the sphere
  40271. */
  40272. segments,
  40273. /**
  40274. * Defines the diameter of the sphere
  40275. */
  40276. diameter, canBeRegenerated, mesh,
  40277. /**
  40278. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40279. */
  40280. side) {
  40281. if (mesh === void 0) { mesh = null; }
  40282. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40283. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40284. _this.segments = segments;
  40285. _this.diameter = diameter;
  40286. _this.side = side;
  40287. return _this;
  40288. }
  40289. /** @hidden */
  40290. SphereGeometry.prototype._regenerateVertexData = function () {
  40291. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40292. };
  40293. SphereGeometry.prototype.copy = function (id) {
  40294. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40295. };
  40296. SphereGeometry.prototype.serialize = function () {
  40297. var serializationObject = _super.prototype.serialize.call(this);
  40298. serializationObject.segments = this.segments;
  40299. serializationObject.diameter = this.diameter;
  40300. return serializationObject;
  40301. };
  40302. SphereGeometry.Parse = function (parsedSphere, scene) {
  40303. if (scene.getGeometryByID(parsedSphere.id)) {
  40304. return null; // null since geometry could be something else than a sphere...
  40305. }
  40306. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40307. if (BABYLON.Tags) {
  40308. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40309. }
  40310. scene.pushGeometry(sphere, true);
  40311. return sphere;
  40312. };
  40313. return SphereGeometry;
  40314. }(_PrimitiveGeometry));
  40315. BABYLON.SphereGeometry = SphereGeometry;
  40316. /**
  40317. * Creates a disc geometry
  40318. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40319. */
  40320. var DiscGeometry = /** @class */ (function (_super) {
  40321. __extends(DiscGeometry, _super);
  40322. /**
  40323. * Creates a new disc geometry
  40324. * @param id defines the unique ID of the geometry
  40325. * @param scene defines the hosting scene
  40326. * @param radius defines the radius of the disc
  40327. * @param tessellation defines the tesselation factor to apply to the disc
  40328. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40329. * @param mesh defines the hosting mesh (can be null)
  40330. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40331. */
  40332. function DiscGeometry(id, scene,
  40333. /**
  40334. * Defines the radius of the disc
  40335. */
  40336. radius,
  40337. /**
  40338. * Defines the tesselation factor to apply to the disc
  40339. */
  40340. tessellation, canBeRegenerated, mesh,
  40341. /**
  40342. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40343. */
  40344. side) {
  40345. if (mesh === void 0) { mesh = null; }
  40346. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40347. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40348. _this.radius = radius;
  40349. _this.tessellation = tessellation;
  40350. _this.side = side;
  40351. return _this;
  40352. }
  40353. /** @hidden */
  40354. DiscGeometry.prototype._regenerateVertexData = function () {
  40355. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40356. };
  40357. DiscGeometry.prototype.copy = function (id) {
  40358. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40359. };
  40360. return DiscGeometry;
  40361. }(_PrimitiveGeometry));
  40362. BABYLON.DiscGeometry = DiscGeometry;
  40363. /**
  40364. * Creates a new cylinder geometry
  40365. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40366. */
  40367. var CylinderGeometry = /** @class */ (function (_super) {
  40368. __extends(CylinderGeometry, _super);
  40369. /**
  40370. * Creates a new cylinder geometry
  40371. * @param id defines the unique ID of the geometry
  40372. * @param scene defines the hosting scene
  40373. * @param height defines the height of the cylinder
  40374. * @param diameterTop defines the diameter of the cylinder's top cap
  40375. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40376. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40377. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  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 CylinderGeometry(id, scene,
  40383. /**
  40384. * Defines the height of the cylinder
  40385. */
  40386. height,
  40387. /**
  40388. * Defines the diameter of the cylinder's top cap
  40389. */
  40390. diameterTop,
  40391. /**
  40392. * Defines the diameter of the cylinder's bottom cap
  40393. */
  40394. diameterBottom,
  40395. /**
  40396. * Defines the tessellation factor to apply to the cylinder
  40397. */
  40398. tessellation,
  40399. /**
  40400. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40401. */
  40402. subdivisions, canBeRegenerated, mesh,
  40403. /**
  40404. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40405. */
  40406. side) {
  40407. if (subdivisions === void 0) { subdivisions = 1; }
  40408. if (mesh === void 0) { mesh = null; }
  40409. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40410. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40411. _this.height = height;
  40412. _this.diameterTop = diameterTop;
  40413. _this.diameterBottom = diameterBottom;
  40414. _this.tessellation = tessellation;
  40415. _this.subdivisions = subdivisions;
  40416. _this.side = side;
  40417. return _this;
  40418. }
  40419. /** @hidden */
  40420. CylinderGeometry.prototype._regenerateVertexData = function () {
  40421. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40422. };
  40423. CylinderGeometry.prototype.copy = function (id) {
  40424. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40425. };
  40426. CylinderGeometry.prototype.serialize = function () {
  40427. var serializationObject = _super.prototype.serialize.call(this);
  40428. serializationObject.height = this.height;
  40429. serializationObject.diameterTop = this.diameterTop;
  40430. serializationObject.diameterBottom = this.diameterBottom;
  40431. serializationObject.tessellation = this.tessellation;
  40432. return serializationObject;
  40433. };
  40434. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40435. if (scene.getGeometryByID(parsedCylinder.id)) {
  40436. return null; // null since geometry could be something else than a cylinder...
  40437. }
  40438. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40439. if (BABYLON.Tags) {
  40440. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40441. }
  40442. scene.pushGeometry(cylinder, true);
  40443. return cylinder;
  40444. };
  40445. return CylinderGeometry;
  40446. }(_PrimitiveGeometry));
  40447. BABYLON.CylinderGeometry = CylinderGeometry;
  40448. /**
  40449. * Creates a new torus geometry
  40450. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40451. */
  40452. var TorusGeometry = /** @class */ (function (_super) {
  40453. __extends(TorusGeometry, _super);
  40454. /**
  40455. * Creates a new torus geometry
  40456. * @param id defines the unique ID of the geometry
  40457. * @param scene defines the hosting scene
  40458. * @param diameter defines the diameter of the torus
  40459. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40460. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40461. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40462. * @param mesh defines the hosting mesh (can be null)
  40463. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40464. */
  40465. function TorusGeometry(id, scene,
  40466. /**
  40467. * Defines the diameter of the torus
  40468. */
  40469. diameter,
  40470. /**
  40471. * Defines the thickness of the torus (ie. internal diameter)
  40472. */
  40473. thickness,
  40474. /**
  40475. * Defines the tesselation factor to apply to the torus
  40476. */
  40477. tessellation, canBeRegenerated, mesh,
  40478. /**
  40479. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40480. */
  40481. side) {
  40482. if (mesh === void 0) { mesh = null; }
  40483. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40484. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40485. _this.diameter = diameter;
  40486. _this.thickness = thickness;
  40487. _this.tessellation = tessellation;
  40488. _this.side = side;
  40489. return _this;
  40490. }
  40491. /** @hidden */
  40492. TorusGeometry.prototype._regenerateVertexData = function () {
  40493. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40494. };
  40495. TorusGeometry.prototype.copy = function (id) {
  40496. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40497. };
  40498. TorusGeometry.prototype.serialize = function () {
  40499. var serializationObject = _super.prototype.serialize.call(this);
  40500. serializationObject.diameter = this.diameter;
  40501. serializationObject.thickness = this.thickness;
  40502. serializationObject.tessellation = this.tessellation;
  40503. return serializationObject;
  40504. };
  40505. TorusGeometry.Parse = function (parsedTorus, scene) {
  40506. if (scene.getGeometryByID(parsedTorus.id)) {
  40507. return null; // null since geometry could be something else than a torus...
  40508. }
  40509. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40510. if (BABYLON.Tags) {
  40511. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40512. }
  40513. scene.pushGeometry(torus, true);
  40514. return torus;
  40515. };
  40516. return TorusGeometry;
  40517. }(_PrimitiveGeometry));
  40518. BABYLON.TorusGeometry = TorusGeometry;
  40519. /**
  40520. * Creates a new ground geometry
  40521. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40522. */
  40523. var GroundGeometry = /** @class */ (function (_super) {
  40524. __extends(GroundGeometry, _super);
  40525. /**
  40526. * Creates a new ground geometry
  40527. * @param id defines the unique ID of the geometry
  40528. * @param scene defines the hosting scene
  40529. * @param width defines the width of the ground
  40530. * @param height defines the height of the ground
  40531. * @param subdivisions defines the subdivisions to apply to the ground
  40532. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40533. * @param mesh defines the hosting mesh (can be null)
  40534. */
  40535. function GroundGeometry(id, scene,
  40536. /**
  40537. * Defines the width of the ground
  40538. */
  40539. width,
  40540. /**
  40541. * Defines the height of the ground
  40542. */
  40543. height,
  40544. /**
  40545. * Defines the subdivisions to apply to the ground
  40546. */
  40547. subdivisions, canBeRegenerated, mesh) {
  40548. if (mesh === void 0) { mesh = null; }
  40549. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40550. _this.width = width;
  40551. _this.height = height;
  40552. _this.subdivisions = subdivisions;
  40553. return _this;
  40554. }
  40555. /** @hidden */
  40556. GroundGeometry.prototype._regenerateVertexData = function () {
  40557. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40558. };
  40559. GroundGeometry.prototype.copy = function (id) {
  40560. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40561. };
  40562. GroundGeometry.prototype.serialize = function () {
  40563. var serializationObject = _super.prototype.serialize.call(this);
  40564. serializationObject.width = this.width;
  40565. serializationObject.height = this.height;
  40566. serializationObject.subdivisions = this.subdivisions;
  40567. return serializationObject;
  40568. };
  40569. GroundGeometry.Parse = function (parsedGround, scene) {
  40570. if (scene.getGeometryByID(parsedGround.id)) {
  40571. return null; // null since geometry could be something else than a ground...
  40572. }
  40573. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40574. if (BABYLON.Tags) {
  40575. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40576. }
  40577. scene.pushGeometry(ground, true);
  40578. return ground;
  40579. };
  40580. return GroundGeometry;
  40581. }(_PrimitiveGeometry));
  40582. BABYLON.GroundGeometry = GroundGeometry;
  40583. /**
  40584. * Creates a tiled ground geometry
  40585. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40586. */
  40587. var TiledGroundGeometry = /** @class */ (function (_super) {
  40588. __extends(TiledGroundGeometry, _super);
  40589. /**
  40590. * Creates a tiled ground geometry
  40591. * @param id defines the unique ID of the geometry
  40592. * @param scene defines the hosting scene
  40593. * @param xmin defines the minimum value on X axis
  40594. * @param zmin defines the minimum value on Z axis
  40595. * @param xmax defines the maximum value on X axis
  40596. * @param zmax defines the maximum value on Z axis
  40597. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40598. * @param precision defines the precision to use when computing the tiles
  40599. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40600. * @param mesh defines the hosting mesh (can be null)
  40601. */
  40602. function TiledGroundGeometry(id, scene,
  40603. /**
  40604. * Defines the minimum value on X axis
  40605. */
  40606. xmin,
  40607. /**
  40608. * Defines the minimum value on Z axis
  40609. */
  40610. zmin,
  40611. /**
  40612. * Defines the maximum value on X axis
  40613. */
  40614. xmax,
  40615. /**
  40616. * Defines the maximum value on Z axis
  40617. */
  40618. zmax,
  40619. /**
  40620. * Defines the subdivisions to apply to the ground
  40621. */
  40622. subdivisions,
  40623. /**
  40624. * Defines the precision to use when computing the tiles
  40625. */
  40626. precision, canBeRegenerated, mesh) {
  40627. if (mesh === void 0) { mesh = null; }
  40628. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40629. _this.xmin = xmin;
  40630. _this.zmin = zmin;
  40631. _this.xmax = xmax;
  40632. _this.zmax = zmax;
  40633. _this.subdivisions = subdivisions;
  40634. _this.precision = precision;
  40635. return _this;
  40636. }
  40637. /** @hidden */
  40638. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40639. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40640. };
  40641. TiledGroundGeometry.prototype.copy = function (id) {
  40642. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40643. };
  40644. return TiledGroundGeometry;
  40645. }(_PrimitiveGeometry));
  40646. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40647. /**
  40648. * Creates a plane geometry
  40649. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40650. */
  40651. var PlaneGeometry = /** @class */ (function (_super) {
  40652. __extends(PlaneGeometry, _super);
  40653. /**
  40654. * Creates a plane geometry
  40655. * @param id defines the unique ID of the geometry
  40656. * @param scene defines the hosting scene
  40657. * @param size defines the size of the plane (width === height)
  40658. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40659. * @param mesh defines the hosting mesh (can be null)
  40660. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40661. */
  40662. function PlaneGeometry(id, scene,
  40663. /**
  40664. * Defines the size of the plane (width === height)
  40665. */
  40666. size, canBeRegenerated, mesh,
  40667. /**
  40668. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40669. */
  40670. side) {
  40671. if (mesh === void 0) { mesh = null; }
  40672. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40673. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40674. _this.size = size;
  40675. _this.side = side;
  40676. return _this;
  40677. }
  40678. /** @hidden */
  40679. PlaneGeometry.prototype._regenerateVertexData = function () {
  40680. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40681. };
  40682. PlaneGeometry.prototype.copy = function (id) {
  40683. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40684. };
  40685. PlaneGeometry.prototype.serialize = function () {
  40686. var serializationObject = _super.prototype.serialize.call(this);
  40687. serializationObject.size = this.size;
  40688. return serializationObject;
  40689. };
  40690. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40691. if (scene.getGeometryByID(parsedPlane.id)) {
  40692. return null; // null since geometry could be something else than a ground...
  40693. }
  40694. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40695. if (BABYLON.Tags) {
  40696. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40697. }
  40698. scene.pushGeometry(plane, true);
  40699. return plane;
  40700. };
  40701. return PlaneGeometry;
  40702. }(_PrimitiveGeometry));
  40703. BABYLON.PlaneGeometry = PlaneGeometry;
  40704. /**
  40705. * Creates a torus knot geometry
  40706. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40707. */
  40708. var TorusKnotGeometry = /** @class */ (function (_super) {
  40709. __extends(TorusKnotGeometry, _super);
  40710. /**
  40711. * Creates a torus knot geometry
  40712. * @param id defines the unique ID of the geometry
  40713. * @param scene defines the hosting scene
  40714. * @param radius defines the radius of the torus knot
  40715. * @param tube defines the thickness of the torus knot tube
  40716. * @param radialSegments defines the number of radial segments
  40717. * @param tubularSegments defines the number of tubular segments
  40718. * @param p defines the first number of windings
  40719. * @param q defines the second number of windings
  40720. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40721. * @param mesh defines the hosting mesh (can be null)
  40722. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40723. */
  40724. function TorusKnotGeometry(id, scene,
  40725. /**
  40726. * Defines the radius of the torus knot
  40727. */
  40728. radius,
  40729. /**
  40730. * Defines the thickness of the torus knot tube
  40731. */
  40732. tube,
  40733. /**
  40734. * Defines the number of radial segments
  40735. */
  40736. radialSegments,
  40737. /**
  40738. * Defines the number of tubular segments
  40739. */
  40740. tubularSegments,
  40741. /**
  40742. * Defines the first number of windings
  40743. */
  40744. p,
  40745. /**
  40746. * Defines the second number of windings
  40747. */
  40748. q, canBeRegenerated, mesh,
  40749. /**
  40750. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40751. */
  40752. side) {
  40753. if (mesh === void 0) { mesh = null; }
  40754. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40755. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40756. _this.radius = radius;
  40757. _this.tube = tube;
  40758. _this.radialSegments = radialSegments;
  40759. _this.tubularSegments = tubularSegments;
  40760. _this.p = p;
  40761. _this.q = q;
  40762. _this.side = side;
  40763. return _this;
  40764. }
  40765. /** @hidden */
  40766. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40767. 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 });
  40768. };
  40769. TorusKnotGeometry.prototype.copy = function (id) {
  40770. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40771. };
  40772. TorusKnotGeometry.prototype.serialize = function () {
  40773. var serializationObject = _super.prototype.serialize.call(this);
  40774. serializationObject.radius = this.radius;
  40775. serializationObject.tube = this.tube;
  40776. serializationObject.radialSegments = this.radialSegments;
  40777. serializationObject.tubularSegments = this.tubularSegments;
  40778. serializationObject.p = this.p;
  40779. serializationObject.q = this.q;
  40780. return serializationObject;
  40781. };
  40782. ;
  40783. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40784. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40785. return null; // null since geometry could be something else than a ground...
  40786. }
  40787. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40788. if (BABYLON.Tags) {
  40789. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40790. }
  40791. scene.pushGeometry(torusKnot, true);
  40792. return torusKnot;
  40793. };
  40794. return TorusKnotGeometry;
  40795. }(_PrimitiveGeometry));
  40796. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40797. //}
  40798. })(BABYLON || (BABYLON = {}));
  40799. //# sourceMappingURL=babylon.geometry.js.map
  40800. var BABYLON;
  40801. (function (BABYLON) {
  40802. /**
  40803. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40804. */
  40805. var PerformanceMonitor = /** @class */ (function () {
  40806. /**
  40807. * constructor
  40808. * @param frameSampleSize The number of samples required to saturate the sliding window
  40809. */
  40810. function PerformanceMonitor(frameSampleSize) {
  40811. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40812. this._enabled = true;
  40813. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40814. }
  40815. /**
  40816. * Samples current frame
  40817. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40818. */
  40819. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40820. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40821. if (!this._enabled)
  40822. return;
  40823. if (this._lastFrameTimeMs != null) {
  40824. var dt = timeMs - this._lastFrameTimeMs;
  40825. this._rollingFrameTime.add(dt);
  40826. }
  40827. this._lastFrameTimeMs = timeMs;
  40828. };
  40829. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40830. /**
  40831. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40832. * @return Average frame time in milliseconds
  40833. */
  40834. get: function () {
  40835. return this._rollingFrameTime.average;
  40836. },
  40837. enumerable: true,
  40838. configurable: true
  40839. });
  40840. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40841. /**
  40842. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40843. * @return Frame time variance in milliseconds squared
  40844. */
  40845. get: function () {
  40846. return this._rollingFrameTime.variance;
  40847. },
  40848. enumerable: true,
  40849. configurable: true
  40850. });
  40851. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40852. /**
  40853. * Returns the frame time of the most recent frame
  40854. * @return Frame time in milliseconds
  40855. */
  40856. get: function () {
  40857. return this._rollingFrameTime.history(0);
  40858. },
  40859. enumerable: true,
  40860. configurable: true
  40861. });
  40862. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40863. /**
  40864. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40865. * @return Framerate in frames per second
  40866. */
  40867. get: function () {
  40868. return 1000.0 / this._rollingFrameTime.average;
  40869. },
  40870. enumerable: true,
  40871. configurable: true
  40872. });
  40873. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40874. /**
  40875. * Returns the average framerate in frames per second using the most recent frame time
  40876. * @return Framerate in frames per second
  40877. */
  40878. get: function () {
  40879. var history = this._rollingFrameTime.history(0);
  40880. if (history === 0) {
  40881. return 0;
  40882. }
  40883. return 1000.0 / history;
  40884. },
  40885. enumerable: true,
  40886. configurable: true
  40887. });
  40888. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40889. /**
  40890. * Returns true if enough samples have been taken to completely fill the sliding window
  40891. * @return true if saturated
  40892. */
  40893. get: function () {
  40894. return this._rollingFrameTime.isSaturated();
  40895. },
  40896. enumerable: true,
  40897. configurable: true
  40898. });
  40899. /**
  40900. * Enables contributions to the sliding window sample set
  40901. */
  40902. PerformanceMonitor.prototype.enable = function () {
  40903. this._enabled = true;
  40904. };
  40905. /**
  40906. * Disables contributions to the sliding window sample set
  40907. * Samples will not be interpolated over the disabled period
  40908. */
  40909. PerformanceMonitor.prototype.disable = function () {
  40910. this._enabled = false;
  40911. //clear last sample to avoid interpolating over the disabled period when next enabled
  40912. this._lastFrameTimeMs = null;
  40913. };
  40914. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40915. /**
  40916. * Returns true if sampling is enabled
  40917. * @return true if enabled
  40918. */
  40919. get: function () {
  40920. return this._enabled;
  40921. },
  40922. enumerable: true,
  40923. configurable: true
  40924. });
  40925. /**
  40926. * Resets performance monitor
  40927. */
  40928. PerformanceMonitor.prototype.reset = function () {
  40929. //clear last sample to avoid interpolating over the disabled period when next enabled
  40930. this._lastFrameTimeMs = null;
  40931. //wipe record
  40932. this._rollingFrameTime.reset();
  40933. };
  40934. return PerformanceMonitor;
  40935. }());
  40936. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40937. /**
  40938. * RollingAverage
  40939. *
  40940. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40941. */
  40942. var RollingAverage = /** @class */ (function () {
  40943. /**
  40944. * constructor
  40945. * @param length The number of samples required to saturate the sliding window
  40946. */
  40947. function RollingAverage(length) {
  40948. this._samples = new Array(length);
  40949. this.reset();
  40950. }
  40951. /**
  40952. * Adds a sample to the sample set
  40953. * @param v The sample value
  40954. */
  40955. RollingAverage.prototype.add = function (v) {
  40956. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40957. var delta;
  40958. //we need to check if we've already wrapped round
  40959. if (this.isSaturated()) {
  40960. //remove bottom of stack from mean
  40961. var bottomValue = this._samples[this._pos];
  40962. delta = bottomValue - this.average;
  40963. this.average -= delta / (this._sampleCount - 1);
  40964. this._m2 -= delta * (bottomValue - this.average);
  40965. }
  40966. else {
  40967. this._sampleCount++;
  40968. }
  40969. //add new value to mean
  40970. delta = v - this.average;
  40971. this.average += delta / (this._sampleCount);
  40972. this._m2 += delta * (v - this.average);
  40973. //set the new variance
  40974. this.variance = this._m2 / (this._sampleCount - 1);
  40975. this._samples[this._pos] = v;
  40976. this._pos++;
  40977. this._pos %= this._samples.length; //positive wrap around
  40978. };
  40979. /**
  40980. * Returns previously added values or null if outside of history or outside the sliding window domain
  40981. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40982. * @return Value previously recorded with add() or null if outside of range
  40983. */
  40984. RollingAverage.prototype.history = function (i) {
  40985. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40986. return 0;
  40987. }
  40988. var i0 = this._wrapPosition(this._pos - 1.0);
  40989. return this._samples[this._wrapPosition(i0 - i)];
  40990. };
  40991. /**
  40992. * Returns true if enough samples have been taken to completely fill the sliding window
  40993. * @return true if sample-set saturated
  40994. */
  40995. RollingAverage.prototype.isSaturated = function () {
  40996. return this._sampleCount >= this._samples.length;
  40997. };
  40998. /**
  40999. * Resets the rolling average (equivalent to 0 samples taken so far)
  41000. */
  41001. RollingAverage.prototype.reset = function () {
  41002. this.average = 0;
  41003. this.variance = 0;
  41004. this._sampleCount = 0;
  41005. this._pos = 0;
  41006. this._m2 = 0;
  41007. };
  41008. /**
  41009. * Wraps a value around the sample range boundaries
  41010. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41011. * @return Wrapped position in sample range
  41012. */
  41013. RollingAverage.prototype._wrapPosition = function (i) {
  41014. var max = this._samples.length;
  41015. return ((i % max) + max) % max;
  41016. };
  41017. return RollingAverage;
  41018. }());
  41019. BABYLON.RollingAverage = RollingAverage;
  41020. })(BABYLON || (BABYLON = {}));
  41021. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41022. var BABYLON;
  41023. (function (BABYLON) {
  41024. /**
  41025. * "Static Class" containing the most commonly used helper while dealing with material for
  41026. * rendering purpose.
  41027. *
  41028. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41029. *
  41030. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41031. */
  41032. var MaterialHelper = /** @class */ (function () {
  41033. function MaterialHelper() {
  41034. }
  41035. /**
  41036. * Bind the current view position to an effect.
  41037. * @param effect The effect to be bound
  41038. * @param scene The scene the eyes position is used from
  41039. */
  41040. MaterialHelper.BindEyePosition = function (effect, scene) {
  41041. if (scene._forcedViewPosition) {
  41042. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41043. return;
  41044. }
  41045. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41046. };
  41047. /**
  41048. * Helps preparing the defines values about the UVs in used in the effect.
  41049. * UVs are shared as much as we can accross chanels in the shaders.
  41050. * @param texture The texture we are preparing the UVs for
  41051. * @param defines The defines to update
  41052. * @param key The chanel key "diffuse", "specular"... used in the shader
  41053. */
  41054. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41055. defines._needUVs = true;
  41056. defines[key] = true;
  41057. if (texture.getTextureMatrix().isIdentity(true)) {
  41058. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41059. if (texture.coordinatesIndex === 0) {
  41060. defines["MAINUV1"] = true;
  41061. }
  41062. else {
  41063. defines["MAINUV2"] = true;
  41064. }
  41065. }
  41066. else {
  41067. defines[key + "DIRECTUV"] = 0;
  41068. }
  41069. };
  41070. /**
  41071. * Binds a texture matrix value to its corrsponding uniform
  41072. * @param texture The texture to bind the matrix for
  41073. * @param uniformBuffer The uniform buffer receivin the data
  41074. * @param key The chanel key "diffuse", "specular"... used in the shader
  41075. */
  41076. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41077. var matrix = texture.getTextureMatrix();
  41078. if (!matrix.isIdentity(true)) {
  41079. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41080. }
  41081. };
  41082. /**
  41083. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41084. * @param mesh defines the current mesh
  41085. * @param scene defines the current scene
  41086. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41087. * @param pointsCloud defines if point cloud rendering has to be turned on
  41088. * @param fogEnabled defines if fog has to be turned on
  41089. * @param alphaTest defines if alpha testing has to be turned on
  41090. * @param defines defines the current list of defines
  41091. */
  41092. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41093. if (defines._areMiscDirty) {
  41094. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41095. defines["POINTSIZE"] = pointsCloud;
  41096. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41097. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41098. defines["ALPHATEST"] = alphaTest;
  41099. }
  41100. };
  41101. /**
  41102. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41103. * @param scene defines the current scene
  41104. * @param engine defines the current engine
  41105. * @param defines specifies the list of active defines
  41106. * @param useInstances defines if instances have to be turned on
  41107. * @param useClipPlane defines if clip plane have to be turned on
  41108. */
  41109. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41110. if (useClipPlane === void 0) { useClipPlane = null; }
  41111. var changed = false;
  41112. var useClipPlane1 = false;
  41113. var useClipPlane2 = false;
  41114. var useClipPlane3 = false;
  41115. var useClipPlane4 = false;
  41116. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41117. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41118. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41119. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41120. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41121. defines["CLIPPLANE"] = useClipPlane1;
  41122. changed = true;
  41123. }
  41124. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41125. defines["CLIPPLANE2"] = useClipPlane2;
  41126. changed = true;
  41127. }
  41128. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41129. defines["CLIPPLANE3"] = useClipPlane3;
  41130. changed = true;
  41131. }
  41132. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41133. defines["CLIPPLANE4"] = useClipPlane4;
  41134. changed = true;
  41135. }
  41136. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41137. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41138. changed = true;
  41139. }
  41140. if (defines["INSTANCES"] !== useInstances) {
  41141. defines["INSTANCES"] = useInstances;
  41142. changed = true;
  41143. }
  41144. if (changed) {
  41145. defines.markAsUnprocessed();
  41146. }
  41147. };
  41148. /**
  41149. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41150. * @param mesh The mesh containing the geometry data we will draw
  41151. * @param defines The defines to update
  41152. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41153. * @param useBones Precise whether bones should be used or not (override mesh info)
  41154. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41155. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41156. * @returns false if defines are considered not dirty and have not been checked
  41157. */
  41158. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41159. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41160. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41161. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41162. return false;
  41163. }
  41164. defines._normals = defines._needNormals;
  41165. defines._uvs = defines._needUVs;
  41166. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41167. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41168. defines["TANGENT"] = true;
  41169. }
  41170. if (defines._needUVs) {
  41171. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41172. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41173. }
  41174. else {
  41175. defines["UV1"] = false;
  41176. defines["UV2"] = false;
  41177. }
  41178. if (useVertexColor) {
  41179. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41180. defines["VERTEXCOLOR"] = hasVertexColors;
  41181. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41182. }
  41183. if (useBones) {
  41184. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41185. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41186. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41187. }
  41188. else {
  41189. defines["NUM_BONE_INFLUENCERS"] = 0;
  41190. defines["BonesPerMesh"] = 0;
  41191. }
  41192. }
  41193. if (useMorphTargets) {
  41194. var manager = mesh.morphTargetManager;
  41195. if (manager) {
  41196. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41197. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41198. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41199. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41200. }
  41201. else {
  41202. defines["MORPHTARGETS_TANGENT"] = false;
  41203. defines["MORPHTARGETS_NORMAL"] = false;
  41204. defines["MORPHTARGETS"] = false;
  41205. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41206. }
  41207. }
  41208. return true;
  41209. };
  41210. /**
  41211. * Prepares the defines related to the light information passed in parameter
  41212. * @param scene The scene we are intending to draw
  41213. * @param mesh The mesh the effect is compiling for
  41214. * @param defines The defines to update
  41215. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41216. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41217. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41218. * @returns true if normals will be required for the rest of the effect
  41219. */
  41220. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41221. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41222. if (disableLighting === void 0) { disableLighting = false; }
  41223. if (!defines._areLightsDirty) {
  41224. return defines._needNormals;
  41225. }
  41226. var lightIndex = 0;
  41227. var needNormals = false;
  41228. var needRebuild = false;
  41229. var lightmapMode = false;
  41230. var shadowEnabled = false;
  41231. var specularEnabled = false;
  41232. if (scene.lightsEnabled && !disableLighting) {
  41233. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41234. var light = _a[_i];
  41235. needNormals = true;
  41236. if (defines["LIGHT" + lightIndex] === undefined) {
  41237. needRebuild = true;
  41238. }
  41239. defines["LIGHT" + lightIndex] = true;
  41240. defines["SPOTLIGHT" + lightIndex] = false;
  41241. defines["HEMILIGHT" + lightIndex] = false;
  41242. defines["POINTLIGHT" + lightIndex] = false;
  41243. defines["DIRLIGHT" + lightIndex] = false;
  41244. light.prepareLightSpecificDefines(defines, lightIndex);
  41245. // FallOff.
  41246. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41247. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41248. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41249. switch (light.falloffType) {
  41250. case BABYLON.Light.FALLOFF_GLTF:
  41251. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41252. break;
  41253. case BABYLON.Light.FALLOFF_PHYSICAL:
  41254. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41255. break;
  41256. case BABYLON.Light.FALLOFF_STANDARD:
  41257. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41258. break;
  41259. }
  41260. // Specular
  41261. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41262. specularEnabled = true;
  41263. }
  41264. // Shadows
  41265. defines["SHADOW" + lightIndex] = false;
  41266. defines["SHADOWPCF" + lightIndex] = false;
  41267. defines["SHADOWPCSS" + lightIndex] = false;
  41268. defines["SHADOWPOISSON" + lightIndex] = false;
  41269. defines["SHADOWESM" + lightIndex] = false;
  41270. defines["SHADOWCUBE" + lightIndex] = false;
  41271. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41272. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41273. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41274. var shadowGenerator = light.getShadowGenerator();
  41275. if (shadowGenerator) {
  41276. var shadowMap = shadowGenerator.getShadowMap();
  41277. if (shadowMap) {
  41278. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41279. shadowEnabled = true;
  41280. shadowGenerator.prepareDefines(defines, lightIndex);
  41281. }
  41282. }
  41283. }
  41284. }
  41285. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41286. lightmapMode = true;
  41287. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41288. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41289. }
  41290. else {
  41291. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41292. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41293. }
  41294. lightIndex++;
  41295. if (lightIndex === maxSimultaneousLights)
  41296. break;
  41297. }
  41298. }
  41299. defines["SPECULARTERM"] = specularEnabled;
  41300. defines["SHADOWS"] = shadowEnabled;
  41301. // Resetting all other lights if any
  41302. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41303. if (defines["LIGHT" + index] !== undefined) {
  41304. defines["LIGHT" + index] = false;
  41305. defines["HEMILIGHT" + lightIndex] = false;
  41306. defines["POINTLIGHT" + lightIndex] = false;
  41307. defines["DIRLIGHT" + lightIndex] = false;
  41308. defines["SPOTLIGHT" + lightIndex] = false;
  41309. defines["SHADOW" + lightIndex] = false;
  41310. }
  41311. }
  41312. var caps = scene.getEngine().getCaps();
  41313. if (defines["SHADOWFLOAT"] === undefined) {
  41314. needRebuild = true;
  41315. }
  41316. defines["SHADOWFLOAT"] = shadowEnabled &&
  41317. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41318. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41319. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41320. if (needRebuild) {
  41321. defines.rebuild();
  41322. }
  41323. return needNormals;
  41324. };
  41325. /**
  41326. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41327. * that won t be acctive due to defines being turned off.
  41328. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41329. * @param samplersList The samplers list
  41330. * @param defines The defines helping in the list generation
  41331. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41332. */
  41333. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41334. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41335. var uniformsList;
  41336. var uniformBuffersList = null;
  41337. if (uniformsListOrOptions.uniformsNames) {
  41338. var options = uniformsListOrOptions;
  41339. uniformsList = options.uniformsNames;
  41340. uniformBuffersList = options.uniformBuffersNames;
  41341. samplersList = options.samplers;
  41342. defines = options.defines;
  41343. maxSimultaneousLights = options.maxSimultaneousLights;
  41344. }
  41345. else {
  41346. uniformsList = uniformsListOrOptions;
  41347. if (!samplersList) {
  41348. samplersList = [];
  41349. }
  41350. }
  41351. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41352. if (!defines["LIGHT" + lightIndex]) {
  41353. break;
  41354. }
  41355. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41356. if (uniformBuffersList) {
  41357. uniformBuffersList.push("Light" + lightIndex);
  41358. }
  41359. samplersList.push("shadowSampler" + lightIndex);
  41360. samplersList.push("depthSampler" + lightIndex);
  41361. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41362. samplersList.push("projectionLightSampler" + lightIndex);
  41363. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41364. }
  41365. }
  41366. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41367. uniformsList.push("morphTargetInfluences");
  41368. }
  41369. };
  41370. /**
  41371. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41372. * @param defines The defines to update while falling back
  41373. * @param fallbacks The authorized effect fallbacks
  41374. * @param maxSimultaneousLights The maximum number of lights allowed
  41375. * @param rank the current rank of the Effect
  41376. * @returns The newly affected rank
  41377. */
  41378. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41379. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41380. if (rank === void 0) { rank = 0; }
  41381. var lightFallbackRank = 0;
  41382. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41383. if (!defines["LIGHT" + lightIndex]) {
  41384. break;
  41385. }
  41386. if (lightIndex > 0) {
  41387. lightFallbackRank = rank + lightIndex;
  41388. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41389. }
  41390. if (!defines["SHADOWS"]) {
  41391. if (defines["SHADOW" + lightIndex]) {
  41392. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41393. }
  41394. if (defines["SHADOWPCF" + lightIndex]) {
  41395. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41396. }
  41397. if (defines["SHADOWPCSS" + lightIndex]) {
  41398. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41399. }
  41400. if (defines["SHADOWPOISSON" + lightIndex]) {
  41401. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41402. }
  41403. if (defines["SHADOWESM" + lightIndex]) {
  41404. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41405. }
  41406. }
  41407. }
  41408. return lightFallbackRank++;
  41409. };
  41410. /**
  41411. * Prepares the list of attributes required for morph targets according to the effect defines.
  41412. * @param attribs The current list of supported attribs
  41413. * @param mesh The mesh to prepare the morph targets attributes for
  41414. * @param defines The current Defines of the effect
  41415. */
  41416. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41417. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41418. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41419. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41420. var manager = mesh.morphTargetManager;
  41421. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41422. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41423. for (var index = 0; index < influencers; index++) {
  41424. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41425. if (normal) {
  41426. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41427. }
  41428. if (tangent) {
  41429. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41430. }
  41431. if (attribs.length > maxAttributesCount) {
  41432. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41433. }
  41434. }
  41435. }
  41436. };
  41437. /**
  41438. * Prepares the list of attributes required for bones according to the effect defines.
  41439. * @param attribs The current list of supported attribs
  41440. * @param mesh The mesh to prepare the bones attributes for
  41441. * @param defines The current Defines of the effect
  41442. * @param fallbacks The current efffect fallback strategy
  41443. */
  41444. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41445. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41446. fallbacks.addCPUSkinningFallback(0, mesh);
  41447. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41448. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41449. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41450. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41451. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41452. }
  41453. }
  41454. };
  41455. /**
  41456. * Prepares the list of attributes required for instances according to the effect defines.
  41457. * @param attribs The current list of supported attribs
  41458. * @param defines The current Defines of the effect
  41459. */
  41460. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41461. if (defines["INSTANCES"]) {
  41462. attribs.push("world0");
  41463. attribs.push("world1");
  41464. attribs.push("world2");
  41465. attribs.push("world3");
  41466. }
  41467. };
  41468. /**
  41469. * Binds the light shadow information to the effect for the given mesh.
  41470. * @param light The light containing the generator
  41471. * @param scene The scene the lights belongs to
  41472. * @param mesh The mesh we are binding the information to render
  41473. * @param lightIndex The light index in the effect used to render the mesh
  41474. * @param effect The effect we are binding the data to
  41475. */
  41476. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41477. if (light.shadowEnabled && mesh.receiveShadows) {
  41478. var shadowGenerator = light.getShadowGenerator();
  41479. if (shadowGenerator) {
  41480. shadowGenerator.bindShadowLight(lightIndex, effect);
  41481. }
  41482. }
  41483. };
  41484. /**
  41485. * Binds the light information to the effect.
  41486. * @param light The light containing the generator
  41487. * @param effect The effect we are binding the data to
  41488. * @param lightIndex The light index in the effect used to render
  41489. */
  41490. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41491. light.transferToEffect(effect, lightIndex + "");
  41492. };
  41493. /**
  41494. * Binds the lights information from the scene to the effect for the given mesh.
  41495. * @param scene The scene the lights belongs to
  41496. * @param mesh The mesh we are binding the information to render
  41497. * @param effect The effect we are binding the data to
  41498. * @param defines The generated defines for the effect
  41499. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41500. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41501. */
  41502. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41503. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41504. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41505. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41506. for (var i = 0; i < len; i++) {
  41507. var light = mesh._lightSources[i];
  41508. var iAsString = i.toString();
  41509. var scaledIntensity = light.getScaledIntensity();
  41510. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41511. MaterialHelper.BindLightProperties(light, effect, i);
  41512. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41513. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41514. if (defines["SPECULARTERM"]) {
  41515. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41516. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41517. }
  41518. // Shadows
  41519. if (scene.shadowsEnabled) {
  41520. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41521. }
  41522. light._uniformBuffer.update();
  41523. }
  41524. };
  41525. /**
  41526. * Binds the fog information from the scene to the effect for the given mesh.
  41527. * @param scene The scene the lights belongs to
  41528. * @param mesh The mesh we are binding the information to render
  41529. * @param effect The effect we are binding the data to
  41530. */
  41531. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41532. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41533. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41534. effect.setColor3("vFogColor", scene.fogColor);
  41535. }
  41536. };
  41537. /**
  41538. * Binds the bones information from the mesh to the effect.
  41539. * @param mesh The mesh we are binding the information to render
  41540. * @param effect The effect we are binding the data to
  41541. */
  41542. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41543. if (!effect || !mesh) {
  41544. return;
  41545. }
  41546. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41547. mesh.computeBonesUsingShaders = false;
  41548. }
  41549. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41550. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41551. if (matrices) {
  41552. effect.setMatrices("mBones", matrices);
  41553. }
  41554. }
  41555. };
  41556. /**
  41557. * Binds the morph targets information from the mesh to the effect.
  41558. * @param abstractMesh The mesh we are binding the information to render
  41559. * @param effect The effect we are binding the data to
  41560. */
  41561. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41562. var manager = abstractMesh.morphTargetManager;
  41563. if (!abstractMesh || !manager) {
  41564. return;
  41565. }
  41566. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41567. };
  41568. /**
  41569. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41570. * @param defines The generated defines used in the effect
  41571. * @param effect The effect we are binding the data to
  41572. * @param scene The scene we are willing to render with logarithmic scale for
  41573. */
  41574. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41575. if (defines["LOGARITHMICDEPTH"]) {
  41576. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41577. }
  41578. };
  41579. /**
  41580. * Binds the clip plane information from the scene to the effect.
  41581. * @param scene The scene the clip plane information are extracted from
  41582. * @param effect The effect we are binding the data to
  41583. */
  41584. MaterialHelper.BindClipPlane = function (effect, scene) {
  41585. if (scene.clipPlane) {
  41586. var clipPlane = scene.clipPlane;
  41587. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41588. }
  41589. if (scene.clipPlane2) {
  41590. var clipPlane = scene.clipPlane2;
  41591. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41592. }
  41593. if (scene.clipPlane3) {
  41594. var clipPlane = scene.clipPlane3;
  41595. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41596. }
  41597. if (scene.clipPlane4) {
  41598. var clipPlane = scene.clipPlane4;
  41599. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41600. }
  41601. };
  41602. return MaterialHelper;
  41603. }());
  41604. BABYLON.MaterialHelper = MaterialHelper;
  41605. })(BABYLON || (BABYLON = {}));
  41606. //# sourceMappingURL=babylon.materialHelper.js.map
  41607. var BABYLON;
  41608. (function (BABYLON) {
  41609. var PushMaterial = /** @class */ (function (_super) {
  41610. __extends(PushMaterial, _super);
  41611. function PushMaterial(name, scene) {
  41612. var _this = _super.call(this, name, scene) || this;
  41613. _this._normalMatrix = new BABYLON.Matrix();
  41614. _this.storeEffectOnSubMeshes = true;
  41615. return _this;
  41616. }
  41617. PushMaterial.prototype.getEffect = function () {
  41618. return this._activeEffect;
  41619. };
  41620. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41621. if (!mesh) {
  41622. return false;
  41623. }
  41624. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41625. return true;
  41626. }
  41627. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41628. };
  41629. /**
  41630. * Binds the given world matrix to the active effect
  41631. *
  41632. * @param world the matrix to bind
  41633. */
  41634. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41635. this._activeEffect.setMatrix("world", world);
  41636. };
  41637. /**
  41638. * Binds the given normal matrix to the active effect
  41639. *
  41640. * @param normalMatrix the matrix to bind
  41641. */
  41642. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41643. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41644. };
  41645. PushMaterial.prototype.bind = function (world, mesh) {
  41646. if (!mesh) {
  41647. return;
  41648. }
  41649. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41650. };
  41651. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41652. if (effect === void 0) { effect = null; }
  41653. _super.prototype._afterBind.call(this, mesh);
  41654. this.getScene()._cachedEffect = effect;
  41655. };
  41656. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41657. if (visibility === void 0) { visibility = 1; }
  41658. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41659. };
  41660. return PushMaterial;
  41661. }(BABYLON.Material));
  41662. BABYLON.PushMaterial = PushMaterial;
  41663. })(BABYLON || (BABYLON = {}));
  41664. //# sourceMappingURL=babylon.pushMaterial.js.map
  41665. var BABYLON;
  41666. (function (BABYLON) {
  41667. /** @hidden */
  41668. var StandardMaterialDefines = /** @class */ (function (_super) {
  41669. __extends(StandardMaterialDefines, _super);
  41670. function StandardMaterialDefines() {
  41671. var _this = _super.call(this) || this;
  41672. _this.MAINUV1 = false;
  41673. _this.MAINUV2 = false;
  41674. _this.DIFFUSE = false;
  41675. _this.DIFFUSEDIRECTUV = 0;
  41676. _this.AMBIENT = false;
  41677. _this.AMBIENTDIRECTUV = 0;
  41678. _this.OPACITY = false;
  41679. _this.OPACITYDIRECTUV = 0;
  41680. _this.OPACITYRGB = false;
  41681. _this.REFLECTION = false;
  41682. _this.EMISSIVE = false;
  41683. _this.EMISSIVEDIRECTUV = 0;
  41684. _this.SPECULAR = false;
  41685. _this.SPECULARDIRECTUV = 0;
  41686. _this.BUMP = false;
  41687. _this.BUMPDIRECTUV = 0;
  41688. _this.PARALLAX = false;
  41689. _this.PARALLAXOCCLUSION = false;
  41690. _this.SPECULAROVERALPHA = false;
  41691. _this.CLIPPLANE = false;
  41692. _this.CLIPPLANE2 = false;
  41693. _this.CLIPPLANE3 = false;
  41694. _this.CLIPPLANE4 = false;
  41695. _this.ALPHATEST = false;
  41696. _this.DEPTHPREPASS = false;
  41697. _this.ALPHAFROMDIFFUSE = false;
  41698. _this.POINTSIZE = false;
  41699. _this.FOG = false;
  41700. _this.SPECULARTERM = false;
  41701. _this.DIFFUSEFRESNEL = false;
  41702. _this.OPACITYFRESNEL = false;
  41703. _this.REFLECTIONFRESNEL = false;
  41704. _this.REFRACTIONFRESNEL = false;
  41705. _this.EMISSIVEFRESNEL = false;
  41706. _this.FRESNEL = false;
  41707. _this.NORMAL = false;
  41708. _this.UV1 = false;
  41709. _this.UV2 = false;
  41710. _this.VERTEXCOLOR = false;
  41711. _this.VERTEXALPHA = false;
  41712. _this.NUM_BONE_INFLUENCERS = 0;
  41713. _this.BonesPerMesh = 0;
  41714. _this.INSTANCES = false;
  41715. _this.GLOSSINESS = false;
  41716. _this.ROUGHNESS = false;
  41717. _this.EMISSIVEASILLUMINATION = false;
  41718. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41719. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41720. _this.LIGHTMAP = false;
  41721. _this.LIGHTMAPDIRECTUV = 0;
  41722. _this.OBJECTSPACE_NORMALMAP = false;
  41723. _this.USELIGHTMAPASSHADOWMAP = false;
  41724. _this.REFLECTIONMAP_3D = false;
  41725. _this.REFLECTIONMAP_SPHERICAL = false;
  41726. _this.REFLECTIONMAP_PLANAR = false;
  41727. _this.REFLECTIONMAP_CUBIC = false;
  41728. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41729. _this.REFLECTIONMAP_PROJECTION = false;
  41730. _this.REFLECTIONMAP_SKYBOX = false;
  41731. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41732. _this.REFLECTIONMAP_EXPLICIT = false;
  41733. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41734. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41735. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41736. _this.INVERTCUBICMAP = false;
  41737. _this.LOGARITHMICDEPTH = false;
  41738. _this.REFRACTION = false;
  41739. _this.REFRACTIONMAP_3D = false;
  41740. _this.REFLECTIONOVERALPHA = false;
  41741. _this.TWOSIDEDLIGHTING = false;
  41742. _this.SHADOWFLOAT = false;
  41743. _this.MORPHTARGETS = false;
  41744. _this.MORPHTARGETS_NORMAL = false;
  41745. _this.MORPHTARGETS_TANGENT = false;
  41746. _this.NUM_MORPH_INFLUENCERS = 0;
  41747. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41748. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41749. _this.IMAGEPROCESSING = false;
  41750. _this.VIGNETTE = false;
  41751. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41752. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41753. _this.TONEMAPPING = false;
  41754. _this.TONEMAPPING_ACES = false;
  41755. _this.CONTRAST = false;
  41756. _this.COLORCURVES = false;
  41757. _this.COLORGRADING = false;
  41758. _this.COLORGRADING3D = false;
  41759. _this.SAMPLER3DGREENDEPTH = false;
  41760. _this.SAMPLER3DBGRMAP = false;
  41761. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41762. /**
  41763. * If the reflection texture on this material is in linear color space
  41764. * @hidden
  41765. */
  41766. _this.IS_REFLECTION_LINEAR = false;
  41767. /**
  41768. * If the refraction texture on this material is in linear color space
  41769. * @hidden
  41770. */
  41771. _this.IS_REFRACTION_LINEAR = false;
  41772. _this.EXPOSURE = false;
  41773. _this.rebuild();
  41774. return _this;
  41775. }
  41776. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41777. var modes = [
  41778. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41779. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41780. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41781. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41782. ];
  41783. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41784. var mode = modes_1[_i];
  41785. this[mode] = (mode === modeToEnable);
  41786. }
  41787. };
  41788. return StandardMaterialDefines;
  41789. }(BABYLON.MaterialDefines));
  41790. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41791. var StandardMaterial = /** @class */ (function (_super) {
  41792. __extends(StandardMaterial, _super);
  41793. function StandardMaterial(name, scene) {
  41794. var _this = _super.call(this, name, scene) || this;
  41795. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41796. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41797. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41798. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41799. _this.specularPower = 64;
  41800. _this._useAlphaFromDiffuseTexture = false;
  41801. _this._useEmissiveAsIllumination = false;
  41802. _this._linkEmissiveWithDiffuse = false;
  41803. _this._useSpecularOverAlpha = false;
  41804. _this._useReflectionOverAlpha = false;
  41805. _this._disableLighting = false;
  41806. _this._useObjectSpaceNormalMap = false;
  41807. _this._useParallax = false;
  41808. _this._useParallaxOcclusion = false;
  41809. _this.parallaxScaleBias = 0.05;
  41810. _this._roughness = 0;
  41811. _this.indexOfRefraction = 0.98;
  41812. _this.invertRefractionY = true;
  41813. /**
  41814. * Defines the alpha limits in alpha test mode
  41815. */
  41816. _this.alphaCutOff = 0.4;
  41817. _this._useLightmapAsShadowmap = false;
  41818. _this._useReflectionFresnelFromSpecular = false;
  41819. _this._useGlossinessFromSpecularMapAlpha = false;
  41820. _this._maxSimultaneousLights = 4;
  41821. /**
  41822. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41823. */
  41824. _this._invertNormalMapX = false;
  41825. /**
  41826. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41827. */
  41828. _this._invertNormalMapY = false;
  41829. /**
  41830. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41831. */
  41832. _this._twoSidedLighting = false;
  41833. _this._renderTargets = new BABYLON.SmartArray(16);
  41834. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41835. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41836. // Setup the default processing configuration to the scene.
  41837. _this._attachImageProcessingConfiguration(null);
  41838. _this.getRenderTargetTextures = function () {
  41839. _this._renderTargets.reset();
  41840. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41841. _this._renderTargets.push(_this._reflectionTexture);
  41842. }
  41843. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41844. _this._renderTargets.push(_this._refractionTexture);
  41845. }
  41846. return _this._renderTargets;
  41847. };
  41848. return _this;
  41849. }
  41850. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41851. /**
  41852. * Gets the image processing configuration used either in this material.
  41853. */
  41854. get: function () {
  41855. return this._imageProcessingConfiguration;
  41856. },
  41857. /**
  41858. * Sets the Default image processing configuration used either in the this material.
  41859. *
  41860. * If sets to null, the scene one is in use.
  41861. */
  41862. set: function (value) {
  41863. this._attachImageProcessingConfiguration(value);
  41864. // Ensure the effect will be rebuilt.
  41865. this._markAllSubMeshesAsTexturesDirty();
  41866. },
  41867. enumerable: true,
  41868. configurable: true
  41869. });
  41870. /**
  41871. * Attaches a new image processing configuration to the Standard Material.
  41872. * @param configuration
  41873. */
  41874. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41875. var _this = this;
  41876. if (configuration === this._imageProcessingConfiguration) {
  41877. return;
  41878. }
  41879. // Detaches observer.
  41880. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41881. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41882. }
  41883. // Pick the scene configuration if needed.
  41884. if (!configuration) {
  41885. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41886. }
  41887. else {
  41888. this._imageProcessingConfiguration = configuration;
  41889. }
  41890. // Attaches observer.
  41891. if (this._imageProcessingConfiguration) {
  41892. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41893. _this._markAllSubMeshesAsImageProcessingDirty();
  41894. });
  41895. }
  41896. };
  41897. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41898. /**
  41899. * Gets wether the color curves effect is enabled.
  41900. */
  41901. get: function () {
  41902. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41903. },
  41904. /**
  41905. * Sets wether the color curves effect is enabled.
  41906. */
  41907. set: function (value) {
  41908. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41909. },
  41910. enumerable: true,
  41911. configurable: true
  41912. });
  41913. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41914. /**
  41915. * Gets wether the color grading effect is enabled.
  41916. */
  41917. get: function () {
  41918. return this.imageProcessingConfiguration.colorGradingEnabled;
  41919. },
  41920. /**
  41921. * Gets wether the color grading effect is enabled.
  41922. */
  41923. set: function (value) {
  41924. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41925. },
  41926. enumerable: true,
  41927. configurable: true
  41928. });
  41929. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41930. /**
  41931. * Gets wether tonemapping is enabled or not.
  41932. */
  41933. get: function () {
  41934. return this._imageProcessingConfiguration.toneMappingEnabled;
  41935. },
  41936. /**
  41937. * Sets wether tonemapping is enabled or not
  41938. */
  41939. set: function (value) {
  41940. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41941. },
  41942. enumerable: true,
  41943. configurable: true
  41944. });
  41945. ;
  41946. ;
  41947. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41948. /**
  41949. * The camera exposure used on this material.
  41950. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41951. * This corresponds to a photographic exposure.
  41952. */
  41953. get: function () {
  41954. return this._imageProcessingConfiguration.exposure;
  41955. },
  41956. /**
  41957. * The camera exposure used on this material.
  41958. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41959. * This corresponds to a photographic exposure.
  41960. */
  41961. set: function (value) {
  41962. this._imageProcessingConfiguration.exposure = value;
  41963. },
  41964. enumerable: true,
  41965. configurable: true
  41966. });
  41967. ;
  41968. ;
  41969. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41970. /**
  41971. * Gets The camera contrast used on this material.
  41972. */
  41973. get: function () {
  41974. return this._imageProcessingConfiguration.contrast;
  41975. },
  41976. /**
  41977. * Sets The camera contrast used on this material.
  41978. */
  41979. set: function (value) {
  41980. this._imageProcessingConfiguration.contrast = value;
  41981. },
  41982. enumerable: true,
  41983. configurable: true
  41984. });
  41985. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41986. /**
  41987. * Gets the Color Grading 2D Lookup Texture.
  41988. */
  41989. get: function () {
  41990. return this._imageProcessingConfiguration.colorGradingTexture;
  41991. },
  41992. /**
  41993. * Sets the Color Grading 2D Lookup Texture.
  41994. */
  41995. set: function (value) {
  41996. this._imageProcessingConfiguration.colorGradingTexture = value;
  41997. },
  41998. enumerable: true,
  41999. configurable: true
  42000. });
  42001. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42002. /**
  42003. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42004. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42005. * 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;
  42006. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42007. */
  42008. get: function () {
  42009. return this._imageProcessingConfiguration.colorCurves;
  42010. },
  42011. /**
  42012. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42013. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42014. * 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;
  42015. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42016. */
  42017. set: function (value) {
  42018. this._imageProcessingConfiguration.colorCurves = value;
  42019. },
  42020. enumerable: true,
  42021. configurable: true
  42022. });
  42023. StandardMaterial.prototype.getClassName = function () {
  42024. return "StandardMaterial";
  42025. };
  42026. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42027. get: function () {
  42028. return this._useLogarithmicDepth;
  42029. },
  42030. set: function (value) {
  42031. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42032. this._markAllSubMeshesAsMiscDirty();
  42033. },
  42034. enumerable: true,
  42035. configurable: true
  42036. });
  42037. StandardMaterial.prototype.needAlphaBlending = function () {
  42038. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42039. };
  42040. StandardMaterial.prototype.needAlphaTesting = function () {
  42041. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42042. };
  42043. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42044. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42045. };
  42046. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42047. return this._diffuseTexture;
  42048. };
  42049. /**
  42050. * Child classes can use it to update shaders
  42051. */
  42052. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42053. if (useInstances === void 0) { useInstances = false; }
  42054. if (subMesh.effect && this.isFrozen) {
  42055. if (this._wasPreviouslyReady) {
  42056. return true;
  42057. }
  42058. }
  42059. if (!subMesh._materialDefines) {
  42060. subMesh._materialDefines = new StandardMaterialDefines();
  42061. }
  42062. var scene = this.getScene();
  42063. var defines = subMesh._materialDefines;
  42064. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42065. if (defines._renderId === scene.getRenderId()) {
  42066. return true;
  42067. }
  42068. }
  42069. var engine = scene.getEngine();
  42070. // Lights
  42071. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42072. // Textures
  42073. if (defines._areTexturesDirty) {
  42074. defines._needUVs = false;
  42075. defines.MAINUV1 = false;
  42076. defines.MAINUV2 = false;
  42077. if (scene.texturesEnabled) {
  42078. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42079. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42080. return false;
  42081. }
  42082. else {
  42083. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42084. }
  42085. }
  42086. else {
  42087. defines.DIFFUSE = false;
  42088. }
  42089. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42090. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42091. return false;
  42092. }
  42093. else {
  42094. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42095. }
  42096. }
  42097. else {
  42098. defines.AMBIENT = false;
  42099. }
  42100. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42101. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42102. return false;
  42103. }
  42104. else {
  42105. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42106. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42107. }
  42108. }
  42109. else {
  42110. defines.OPACITY = false;
  42111. }
  42112. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42113. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42114. return false;
  42115. }
  42116. else {
  42117. defines._needNormals = true;
  42118. defines.REFLECTION = true;
  42119. defines.ROUGHNESS = (this._roughness > 0);
  42120. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42121. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42122. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42123. switch (this._reflectionTexture.coordinatesMode) {
  42124. case BABYLON.Texture.EXPLICIT_MODE:
  42125. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42126. break;
  42127. case BABYLON.Texture.PLANAR_MODE:
  42128. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42129. break;
  42130. case BABYLON.Texture.PROJECTION_MODE:
  42131. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42132. break;
  42133. case BABYLON.Texture.SKYBOX_MODE:
  42134. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42135. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42136. break;
  42137. case BABYLON.Texture.SPHERICAL_MODE:
  42138. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42139. break;
  42140. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42141. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42142. break;
  42143. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42144. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42145. break;
  42146. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42147. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42148. break;
  42149. case BABYLON.Texture.CUBIC_MODE:
  42150. case BABYLON.Texture.INVCUBIC_MODE:
  42151. default:
  42152. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42153. break;
  42154. }
  42155. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42156. }
  42157. }
  42158. else {
  42159. defines.REFLECTION = false;
  42160. }
  42161. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42162. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42163. return false;
  42164. }
  42165. else {
  42166. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42167. }
  42168. }
  42169. else {
  42170. defines.EMISSIVE = false;
  42171. }
  42172. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42173. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42174. return false;
  42175. }
  42176. else {
  42177. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42178. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42179. }
  42180. }
  42181. else {
  42182. defines.LIGHTMAP = false;
  42183. }
  42184. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42185. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42186. return false;
  42187. }
  42188. else {
  42189. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42190. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42191. }
  42192. }
  42193. else {
  42194. defines.SPECULAR = false;
  42195. }
  42196. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42197. // Bump texure can not be not blocking.
  42198. if (!this._bumpTexture.isReady()) {
  42199. return false;
  42200. }
  42201. else {
  42202. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42203. defines.PARALLAX = this._useParallax;
  42204. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42205. }
  42206. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42207. }
  42208. else {
  42209. defines.BUMP = false;
  42210. }
  42211. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42212. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42213. return false;
  42214. }
  42215. else {
  42216. defines._needUVs = true;
  42217. defines.REFRACTION = true;
  42218. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42219. }
  42220. }
  42221. else {
  42222. defines.REFRACTION = false;
  42223. }
  42224. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42225. }
  42226. else {
  42227. defines.DIFFUSE = false;
  42228. defines.AMBIENT = false;
  42229. defines.OPACITY = false;
  42230. defines.REFLECTION = false;
  42231. defines.EMISSIVE = false;
  42232. defines.LIGHTMAP = false;
  42233. defines.BUMP = false;
  42234. defines.REFRACTION = false;
  42235. }
  42236. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42237. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42238. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42239. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42240. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42241. }
  42242. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42243. if (!this._imageProcessingConfiguration.isReady()) {
  42244. return false;
  42245. }
  42246. this._imageProcessingConfiguration.prepareDefines(defines);
  42247. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42248. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42249. }
  42250. if (defines._areFresnelDirty) {
  42251. if (StandardMaterial.FresnelEnabled) {
  42252. // Fresnel
  42253. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42254. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42255. this._reflectionFresnelParameters) {
  42256. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42257. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42258. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42259. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42260. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42261. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42262. defines._needNormals = true;
  42263. defines.FRESNEL = true;
  42264. }
  42265. }
  42266. else {
  42267. defines.FRESNEL = false;
  42268. }
  42269. }
  42270. // Misc.
  42271. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42272. // Attribs
  42273. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42274. // Values that need to be evaluated on every frame
  42275. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42276. // Get correct effect
  42277. if (defines.isDirty) {
  42278. defines.markAsProcessed();
  42279. scene.resetCachedMaterial();
  42280. // Fallbacks
  42281. var fallbacks = new BABYLON.EffectFallbacks();
  42282. if (defines.REFLECTION) {
  42283. fallbacks.addFallback(0, "REFLECTION");
  42284. }
  42285. if (defines.SPECULAR) {
  42286. fallbacks.addFallback(0, "SPECULAR");
  42287. }
  42288. if (defines.BUMP) {
  42289. fallbacks.addFallback(0, "BUMP");
  42290. }
  42291. if (defines.PARALLAX) {
  42292. fallbacks.addFallback(1, "PARALLAX");
  42293. }
  42294. if (defines.PARALLAXOCCLUSION) {
  42295. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42296. }
  42297. if (defines.SPECULAROVERALPHA) {
  42298. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42299. }
  42300. if (defines.FOG) {
  42301. fallbacks.addFallback(1, "FOG");
  42302. }
  42303. if (defines.POINTSIZE) {
  42304. fallbacks.addFallback(0, "POINTSIZE");
  42305. }
  42306. if (defines.LOGARITHMICDEPTH) {
  42307. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42308. }
  42309. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42310. if (defines.SPECULARTERM) {
  42311. fallbacks.addFallback(0, "SPECULARTERM");
  42312. }
  42313. if (defines.DIFFUSEFRESNEL) {
  42314. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42315. }
  42316. if (defines.OPACITYFRESNEL) {
  42317. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42318. }
  42319. if (defines.REFLECTIONFRESNEL) {
  42320. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42321. }
  42322. if (defines.EMISSIVEFRESNEL) {
  42323. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42324. }
  42325. if (defines.FRESNEL) {
  42326. fallbacks.addFallback(4, "FRESNEL");
  42327. }
  42328. //Attributes
  42329. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42330. if (defines.NORMAL) {
  42331. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42332. }
  42333. if (defines.UV1) {
  42334. attribs.push(BABYLON.VertexBuffer.UVKind);
  42335. }
  42336. if (defines.UV2) {
  42337. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42338. }
  42339. if (defines.VERTEXCOLOR) {
  42340. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42341. }
  42342. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42343. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42344. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42345. var shaderName = "default";
  42346. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42347. "vFogInfos", "vFogColor", "pointSize",
  42348. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42349. "mBones",
  42350. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42351. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42352. "vReflectionPosition", "vReflectionSize",
  42353. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42354. ];
  42355. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42356. var uniformBuffers = ["Material", "Scene"];
  42357. if (BABYLON.ImageProcessingConfiguration) {
  42358. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42359. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42360. }
  42361. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42362. uniformsNames: uniforms,
  42363. uniformBuffersNames: uniformBuffers,
  42364. samplers: samplers,
  42365. defines: defines,
  42366. maxSimultaneousLights: this._maxSimultaneousLights
  42367. });
  42368. if (this.customShaderNameResolve) {
  42369. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42370. }
  42371. var join = defines.toString();
  42372. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42373. attributes: attribs,
  42374. uniformsNames: uniforms,
  42375. uniformBuffersNames: uniformBuffers,
  42376. samplers: samplers,
  42377. defines: join,
  42378. fallbacks: fallbacks,
  42379. onCompiled: this.onCompiled,
  42380. onError: this.onError,
  42381. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42382. }, engine), defines);
  42383. this.buildUniformLayout();
  42384. }
  42385. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42386. return false;
  42387. }
  42388. defines._renderId = scene.getRenderId();
  42389. this._wasPreviouslyReady = true;
  42390. return true;
  42391. };
  42392. StandardMaterial.prototype.buildUniformLayout = function () {
  42393. // Order is important !
  42394. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42395. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42396. this._uniformBuffer.addUniform("opacityParts", 4);
  42397. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42398. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42399. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42400. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42401. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42402. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42403. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42404. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42405. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42406. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42407. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42408. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42409. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42410. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42411. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42412. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42413. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42414. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42415. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42416. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42417. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42418. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42419. this._uniformBuffer.addUniform("specularMatrix", 16);
  42420. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42421. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42422. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42423. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42424. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42425. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42426. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42427. this._uniformBuffer.addUniform("pointSize", 1);
  42428. this._uniformBuffer.create();
  42429. };
  42430. StandardMaterial.prototype.unbind = function () {
  42431. if (this._activeEffect) {
  42432. var needFlag = false;
  42433. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42434. this._activeEffect.setTexture("reflection2DSampler", null);
  42435. needFlag = true;
  42436. }
  42437. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42438. this._activeEffect.setTexture("refraction2DSampler", null);
  42439. needFlag = true;
  42440. }
  42441. if (needFlag) {
  42442. this._markAllSubMeshesAsTexturesDirty();
  42443. }
  42444. }
  42445. _super.prototype.unbind.call(this);
  42446. };
  42447. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42448. var scene = this.getScene();
  42449. var defines = subMesh._materialDefines;
  42450. if (!defines) {
  42451. return;
  42452. }
  42453. var effect = subMesh.effect;
  42454. if (!effect) {
  42455. return;
  42456. }
  42457. this._activeEffect = effect;
  42458. // Matrices
  42459. this.bindOnlyWorldMatrix(world);
  42460. // Normal Matrix
  42461. if (defines.OBJECTSPACE_NORMALMAP) {
  42462. world.toNormalMatrix(this._normalMatrix);
  42463. this.bindOnlyNormalMatrix(this._normalMatrix);
  42464. }
  42465. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42466. // Bones
  42467. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42468. if (mustRebind) {
  42469. this._uniformBuffer.bindToEffect(effect, "Material");
  42470. this.bindViewProjection(effect);
  42471. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42472. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42473. // Fresnel
  42474. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42475. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42476. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42477. }
  42478. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42479. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42480. }
  42481. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42482. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42483. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42484. }
  42485. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42486. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42487. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42488. }
  42489. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42490. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42491. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42492. }
  42493. }
  42494. // Textures
  42495. if (scene.texturesEnabled) {
  42496. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42497. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42498. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42499. if (this._diffuseTexture.hasAlpha) {
  42500. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42501. }
  42502. }
  42503. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42504. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42505. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42506. }
  42507. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42508. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42509. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42510. }
  42511. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42512. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42513. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42514. if (this._reflectionTexture.boundingBoxSize) {
  42515. var cubeTexture = this._reflectionTexture;
  42516. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42517. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42518. }
  42519. }
  42520. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42521. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42522. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42523. }
  42524. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42525. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42526. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42527. }
  42528. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42529. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42530. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42531. }
  42532. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42533. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42534. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42535. if (scene._mirroredCameraPosition) {
  42536. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42537. }
  42538. else {
  42539. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42540. }
  42541. }
  42542. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42543. var depth = 1.0;
  42544. if (!this._refractionTexture.isCube) {
  42545. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42546. if (this._refractionTexture.depth) {
  42547. depth = this._refractionTexture.depth;
  42548. }
  42549. }
  42550. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42551. }
  42552. }
  42553. // Point size
  42554. if (this.pointsCloud) {
  42555. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42556. }
  42557. if (defines.SPECULARTERM) {
  42558. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42559. }
  42560. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42561. // Diffuse
  42562. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42563. }
  42564. // Textures
  42565. if (scene.texturesEnabled) {
  42566. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42567. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42568. }
  42569. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42570. effect.setTexture("ambientSampler", this._ambientTexture);
  42571. }
  42572. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42573. effect.setTexture("opacitySampler", this._opacityTexture);
  42574. }
  42575. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42576. if (this._reflectionTexture.isCube) {
  42577. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42578. }
  42579. else {
  42580. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42581. }
  42582. }
  42583. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42584. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42585. }
  42586. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42587. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42588. }
  42589. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42590. effect.setTexture("specularSampler", this._specularTexture);
  42591. }
  42592. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42593. effect.setTexture("bumpSampler", this._bumpTexture);
  42594. }
  42595. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42596. var depth = 1.0;
  42597. if (this._refractionTexture.isCube) {
  42598. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42599. }
  42600. else {
  42601. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42602. }
  42603. }
  42604. }
  42605. // Clip plane
  42606. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42607. // Colors
  42608. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42609. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42610. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42611. }
  42612. if (mustRebind || !this.isFrozen) {
  42613. // Lights
  42614. if (scene.lightsEnabled && !this._disableLighting) {
  42615. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42616. }
  42617. // View
  42618. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42619. this.bindView(effect);
  42620. }
  42621. // Fog
  42622. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42623. // Morph targets
  42624. if (defines.NUM_MORPH_INFLUENCERS) {
  42625. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42626. }
  42627. // Log. depth
  42628. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42629. // image processing
  42630. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42631. this._imageProcessingConfiguration.bind(this._activeEffect);
  42632. }
  42633. }
  42634. this._uniformBuffer.update();
  42635. this._afterBind(mesh, this._activeEffect);
  42636. };
  42637. StandardMaterial.prototype.getAnimatables = function () {
  42638. var results = [];
  42639. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42640. results.push(this._diffuseTexture);
  42641. }
  42642. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42643. results.push(this._ambientTexture);
  42644. }
  42645. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42646. results.push(this._opacityTexture);
  42647. }
  42648. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42649. results.push(this._reflectionTexture);
  42650. }
  42651. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42652. results.push(this._emissiveTexture);
  42653. }
  42654. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42655. results.push(this._specularTexture);
  42656. }
  42657. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42658. results.push(this._bumpTexture);
  42659. }
  42660. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42661. results.push(this._lightmapTexture);
  42662. }
  42663. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42664. results.push(this._refractionTexture);
  42665. }
  42666. return results;
  42667. };
  42668. StandardMaterial.prototype.getActiveTextures = function () {
  42669. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42670. if (this._diffuseTexture) {
  42671. activeTextures.push(this._diffuseTexture);
  42672. }
  42673. if (this._ambientTexture) {
  42674. activeTextures.push(this._ambientTexture);
  42675. }
  42676. if (this._opacityTexture) {
  42677. activeTextures.push(this._opacityTexture);
  42678. }
  42679. if (this._reflectionTexture) {
  42680. activeTextures.push(this._reflectionTexture);
  42681. }
  42682. if (this._emissiveTexture) {
  42683. activeTextures.push(this._emissiveTexture);
  42684. }
  42685. if (this._specularTexture) {
  42686. activeTextures.push(this._specularTexture);
  42687. }
  42688. if (this._bumpTexture) {
  42689. activeTextures.push(this._bumpTexture);
  42690. }
  42691. if (this._lightmapTexture) {
  42692. activeTextures.push(this._lightmapTexture);
  42693. }
  42694. if (this._refractionTexture) {
  42695. activeTextures.push(this._refractionTexture);
  42696. }
  42697. return activeTextures;
  42698. };
  42699. StandardMaterial.prototype.hasTexture = function (texture) {
  42700. if (_super.prototype.hasTexture.call(this, texture)) {
  42701. return true;
  42702. }
  42703. if (this._diffuseTexture === texture) {
  42704. return true;
  42705. }
  42706. if (this._ambientTexture === texture) {
  42707. return true;
  42708. }
  42709. if (this._opacityTexture === texture) {
  42710. return true;
  42711. }
  42712. if (this._reflectionTexture === texture) {
  42713. return true;
  42714. }
  42715. if (this._emissiveTexture === texture) {
  42716. return true;
  42717. }
  42718. if (this._specularTexture === texture) {
  42719. return true;
  42720. }
  42721. if (this._bumpTexture === texture) {
  42722. return true;
  42723. }
  42724. if (this._lightmapTexture === texture) {
  42725. return true;
  42726. }
  42727. if (this._refractionTexture === texture) {
  42728. return true;
  42729. }
  42730. return false;
  42731. };
  42732. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42733. if (forceDisposeTextures) {
  42734. if (this._diffuseTexture) {
  42735. this._diffuseTexture.dispose();
  42736. }
  42737. if (this._ambientTexture) {
  42738. this._ambientTexture.dispose();
  42739. }
  42740. if (this._opacityTexture) {
  42741. this._opacityTexture.dispose();
  42742. }
  42743. if (this._reflectionTexture) {
  42744. this._reflectionTexture.dispose();
  42745. }
  42746. if (this._emissiveTexture) {
  42747. this._emissiveTexture.dispose();
  42748. }
  42749. if (this._specularTexture) {
  42750. this._specularTexture.dispose();
  42751. }
  42752. if (this._bumpTexture) {
  42753. this._bumpTexture.dispose();
  42754. }
  42755. if (this._lightmapTexture) {
  42756. this._lightmapTexture.dispose();
  42757. }
  42758. if (this._refractionTexture) {
  42759. this._refractionTexture.dispose();
  42760. }
  42761. }
  42762. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42763. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42764. }
  42765. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42766. };
  42767. StandardMaterial.prototype.clone = function (name) {
  42768. var _this = this;
  42769. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42770. result.name = name;
  42771. result.id = name;
  42772. return result;
  42773. };
  42774. StandardMaterial.prototype.serialize = function () {
  42775. return BABYLON.SerializationHelper.Serialize(this);
  42776. };
  42777. // Statics
  42778. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42779. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42780. };
  42781. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42782. get: function () {
  42783. return StandardMaterial._DiffuseTextureEnabled;
  42784. },
  42785. set: function (value) {
  42786. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42787. return;
  42788. }
  42789. StandardMaterial._DiffuseTextureEnabled = value;
  42790. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42791. },
  42792. enumerable: true,
  42793. configurable: true
  42794. });
  42795. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42796. get: function () {
  42797. return StandardMaterial._AmbientTextureEnabled;
  42798. },
  42799. set: function (value) {
  42800. if (StandardMaterial._AmbientTextureEnabled === value) {
  42801. return;
  42802. }
  42803. StandardMaterial._AmbientTextureEnabled = value;
  42804. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42805. },
  42806. enumerable: true,
  42807. configurable: true
  42808. });
  42809. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42810. get: function () {
  42811. return StandardMaterial._OpacityTextureEnabled;
  42812. },
  42813. set: function (value) {
  42814. if (StandardMaterial._OpacityTextureEnabled === value) {
  42815. return;
  42816. }
  42817. StandardMaterial._OpacityTextureEnabled = value;
  42818. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42819. },
  42820. enumerable: true,
  42821. configurable: true
  42822. });
  42823. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42824. get: function () {
  42825. return StandardMaterial._ReflectionTextureEnabled;
  42826. },
  42827. set: function (value) {
  42828. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42829. return;
  42830. }
  42831. StandardMaterial._ReflectionTextureEnabled = value;
  42832. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42833. },
  42834. enumerable: true,
  42835. configurable: true
  42836. });
  42837. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42838. get: function () {
  42839. return StandardMaterial._EmissiveTextureEnabled;
  42840. },
  42841. set: function (value) {
  42842. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42843. return;
  42844. }
  42845. StandardMaterial._EmissiveTextureEnabled = value;
  42846. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42847. },
  42848. enumerable: true,
  42849. configurable: true
  42850. });
  42851. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42852. get: function () {
  42853. return StandardMaterial._SpecularTextureEnabled;
  42854. },
  42855. set: function (value) {
  42856. if (StandardMaterial._SpecularTextureEnabled === value) {
  42857. return;
  42858. }
  42859. StandardMaterial._SpecularTextureEnabled = value;
  42860. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42861. },
  42862. enumerable: true,
  42863. configurable: true
  42864. });
  42865. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42866. get: function () {
  42867. return StandardMaterial._BumpTextureEnabled;
  42868. },
  42869. set: function (value) {
  42870. if (StandardMaterial._BumpTextureEnabled === value) {
  42871. return;
  42872. }
  42873. StandardMaterial._BumpTextureEnabled = value;
  42874. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42875. },
  42876. enumerable: true,
  42877. configurable: true
  42878. });
  42879. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42880. get: function () {
  42881. return StandardMaterial._LightmapTextureEnabled;
  42882. },
  42883. set: function (value) {
  42884. if (StandardMaterial._LightmapTextureEnabled === value) {
  42885. return;
  42886. }
  42887. StandardMaterial._LightmapTextureEnabled = value;
  42888. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42889. },
  42890. enumerable: true,
  42891. configurable: true
  42892. });
  42893. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42894. get: function () {
  42895. return StandardMaterial._RefractionTextureEnabled;
  42896. },
  42897. set: function (value) {
  42898. if (StandardMaterial._RefractionTextureEnabled === value) {
  42899. return;
  42900. }
  42901. StandardMaterial._RefractionTextureEnabled = value;
  42902. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42903. },
  42904. enumerable: true,
  42905. configurable: true
  42906. });
  42907. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42908. get: function () {
  42909. return StandardMaterial._ColorGradingTextureEnabled;
  42910. },
  42911. set: function (value) {
  42912. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42913. return;
  42914. }
  42915. StandardMaterial._ColorGradingTextureEnabled = value;
  42916. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42917. },
  42918. enumerable: true,
  42919. configurable: true
  42920. });
  42921. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42922. get: function () {
  42923. return StandardMaterial._FresnelEnabled;
  42924. },
  42925. set: function (value) {
  42926. if (StandardMaterial._FresnelEnabled === value) {
  42927. return;
  42928. }
  42929. StandardMaterial._FresnelEnabled = value;
  42930. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42931. },
  42932. enumerable: true,
  42933. configurable: true
  42934. });
  42935. // Flags used to enable or disable a type of texture for all Standard Materials
  42936. StandardMaterial._DiffuseTextureEnabled = true;
  42937. StandardMaterial._AmbientTextureEnabled = true;
  42938. StandardMaterial._OpacityTextureEnabled = true;
  42939. StandardMaterial._ReflectionTextureEnabled = true;
  42940. StandardMaterial._EmissiveTextureEnabled = true;
  42941. StandardMaterial._SpecularTextureEnabled = true;
  42942. StandardMaterial._BumpTextureEnabled = true;
  42943. StandardMaterial._LightmapTextureEnabled = true;
  42944. StandardMaterial._RefractionTextureEnabled = true;
  42945. StandardMaterial._ColorGradingTextureEnabled = true;
  42946. StandardMaterial._FresnelEnabled = true;
  42947. __decorate([
  42948. BABYLON.serializeAsTexture("diffuseTexture")
  42949. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42950. __decorate([
  42951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42952. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42953. __decorate([
  42954. BABYLON.serializeAsTexture("ambientTexture")
  42955. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42956. __decorate([
  42957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42958. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42959. __decorate([
  42960. BABYLON.serializeAsTexture("opacityTexture")
  42961. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42962. __decorate([
  42963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42964. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42965. __decorate([
  42966. BABYLON.serializeAsTexture("reflectionTexture")
  42967. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42968. __decorate([
  42969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42970. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42971. __decorate([
  42972. BABYLON.serializeAsTexture("emissiveTexture")
  42973. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42974. __decorate([
  42975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42976. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42977. __decorate([
  42978. BABYLON.serializeAsTexture("specularTexture")
  42979. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42980. __decorate([
  42981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42982. ], StandardMaterial.prototype, "specularTexture", void 0);
  42983. __decorate([
  42984. BABYLON.serializeAsTexture("bumpTexture")
  42985. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42986. __decorate([
  42987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42988. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42989. __decorate([
  42990. BABYLON.serializeAsTexture("lightmapTexture")
  42991. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42992. __decorate([
  42993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42994. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42995. __decorate([
  42996. BABYLON.serializeAsTexture("refractionTexture")
  42997. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42998. __decorate([
  42999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43000. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43001. __decorate([
  43002. BABYLON.serializeAsColor3("ambient")
  43003. ], StandardMaterial.prototype, "ambientColor", void 0);
  43004. __decorate([
  43005. BABYLON.serializeAsColor3("diffuse")
  43006. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43007. __decorate([
  43008. BABYLON.serializeAsColor3("specular")
  43009. ], StandardMaterial.prototype, "specularColor", void 0);
  43010. __decorate([
  43011. BABYLON.serializeAsColor3("emissive")
  43012. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43013. __decorate([
  43014. BABYLON.serialize()
  43015. ], StandardMaterial.prototype, "specularPower", void 0);
  43016. __decorate([
  43017. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43018. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43019. __decorate([
  43020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43021. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43022. __decorate([
  43023. BABYLON.serialize("useEmissiveAsIllumination")
  43024. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43025. __decorate([
  43026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43027. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43028. __decorate([
  43029. BABYLON.serialize("linkEmissiveWithDiffuse")
  43030. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43031. __decorate([
  43032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43033. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43034. __decorate([
  43035. BABYLON.serialize("useSpecularOverAlpha")
  43036. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43037. __decorate([
  43038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43039. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43040. __decorate([
  43041. BABYLON.serialize("useReflectionOverAlpha")
  43042. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43043. __decorate([
  43044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43045. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43046. __decorate([
  43047. BABYLON.serialize("disableLighting")
  43048. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43049. __decorate([
  43050. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43051. ], StandardMaterial.prototype, "disableLighting", void 0);
  43052. __decorate([
  43053. BABYLON.serialize("useObjectSpaceNormalMap")
  43054. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43055. __decorate([
  43056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43057. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43058. __decorate([
  43059. BABYLON.serialize("useParallax")
  43060. ], StandardMaterial.prototype, "_useParallax", void 0);
  43061. __decorate([
  43062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43063. ], StandardMaterial.prototype, "useParallax", void 0);
  43064. __decorate([
  43065. BABYLON.serialize("useParallaxOcclusion")
  43066. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43067. __decorate([
  43068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43069. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43070. __decorate([
  43071. BABYLON.serialize()
  43072. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43073. __decorate([
  43074. BABYLON.serialize("roughness")
  43075. ], StandardMaterial.prototype, "_roughness", void 0);
  43076. __decorate([
  43077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43078. ], StandardMaterial.prototype, "roughness", void 0);
  43079. __decorate([
  43080. BABYLON.serialize()
  43081. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43082. __decorate([
  43083. BABYLON.serialize()
  43084. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43085. __decorate([
  43086. BABYLON.serialize()
  43087. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43088. __decorate([
  43089. BABYLON.serialize("useLightmapAsShadowmap")
  43090. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43091. __decorate([
  43092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43093. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43094. __decorate([
  43095. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43096. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43097. __decorate([
  43098. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43099. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43100. __decorate([
  43101. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43102. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43103. __decorate([
  43104. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43105. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43106. __decorate([
  43107. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43108. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43109. __decorate([
  43110. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43111. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43112. __decorate([
  43113. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43114. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43115. __decorate([
  43116. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43117. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43118. __decorate([
  43119. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43120. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43121. __decorate([
  43122. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43123. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43124. __decorate([
  43125. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43126. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43127. __decorate([
  43128. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43129. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43130. __decorate([
  43131. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43132. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43133. __decorate([
  43134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43135. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43136. __decorate([
  43137. BABYLON.serialize("maxSimultaneousLights")
  43138. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43139. __decorate([
  43140. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43141. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43142. __decorate([
  43143. BABYLON.serialize("invertNormalMapX")
  43144. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43145. __decorate([
  43146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43147. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43148. __decorate([
  43149. BABYLON.serialize("invertNormalMapY")
  43150. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43151. __decorate([
  43152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43153. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43154. __decorate([
  43155. BABYLON.serialize("twoSidedLighting")
  43156. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43157. __decorate([
  43158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43159. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43160. __decorate([
  43161. BABYLON.serialize()
  43162. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43163. return StandardMaterial;
  43164. }(BABYLON.PushMaterial));
  43165. BABYLON.StandardMaterial = StandardMaterial;
  43166. })(BABYLON || (BABYLON = {}));
  43167. //# sourceMappingURL=babylon.standardMaterial.js.map
  43168. var BABYLON;
  43169. (function (BABYLON) {
  43170. /**
  43171. * Class representing spherical polynomial coefficients to the 3rd degree
  43172. */
  43173. var SphericalPolynomial = /** @class */ (function () {
  43174. function SphericalPolynomial() {
  43175. /**
  43176. * The x coefficients of the spherical polynomial
  43177. */
  43178. this.x = BABYLON.Vector3.Zero();
  43179. /**
  43180. * The y coefficients of the spherical polynomial
  43181. */
  43182. this.y = BABYLON.Vector3.Zero();
  43183. /**
  43184. * The z coefficients of the spherical polynomial
  43185. */
  43186. this.z = BABYLON.Vector3.Zero();
  43187. /**
  43188. * The xx coefficients of the spherical polynomial
  43189. */
  43190. this.xx = BABYLON.Vector3.Zero();
  43191. /**
  43192. * The yy coefficients of the spherical polynomial
  43193. */
  43194. this.yy = BABYLON.Vector3.Zero();
  43195. /**
  43196. * The zz coefficients of the spherical polynomial
  43197. */
  43198. this.zz = BABYLON.Vector3.Zero();
  43199. /**
  43200. * The xy coefficients of the spherical polynomial
  43201. */
  43202. this.xy = BABYLON.Vector3.Zero();
  43203. /**
  43204. * The yz coefficients of the spherical polynomial
  43205. */
  43206. this.yz = BABYLON.Vector3.Zero();
  43207. /**
  43208. * The zx coefficients of the spherical polynomial
  43209. */
  43210. this.zx = BABYLON.Vector3.Zero();
  43211. }
  43212. /**
  43213. * Adds an ambient color to the spherical polynomial
  43214. * @param color the color to add
  43215. */
  43216. SphericalPolynomial.prototype.addAmbient = function (color) {
  43217. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43218. this.xx = this.xx.add(colorVector);
  43219. this.yy = this.yy.add(colorVector);
  43220. this.zz = this.zz.add(colorVector);
  43221. };
  43222. /**
  43223. * Scales the spherical polynomial by the given amount
  43224. * @param scale the amount to scale
  43225. */
  43226. SphericalPolynomial.prototype.scale = function (scale) {
  43227. this.x = this.x.scale(scale);
  43228. this.y = this.y.scale(scale);
  43229. this.z = this.z.scale(scale);
  43230. this.xx = this.xx.scale(scale);
  43231. this.yy = this.yy.scale(scale);
  43232. this.zz = this.zz.scale(scale);
  43233. this.yz = this.yz.scale(scale);
  43234. this.zx = this.zx.scale(scale);
  43235. this.xy = this.xy.scale(scale);
  43236. };
  43237. /**
  43238. * Gets the spherical polynomial from harmonics
  43239. * @param harmonics the spherical harmonics
  43240. * @returns the spherical polynomial
  43241. */
  43242. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43243. var result = new SphericalPolynomial();
  43244. result.x = harmonics.l11.scale(1.02333);
  43245. result.y = harmonics.l1_1.scale(1.02333);
  43246. result.z = harmonics.l10.scale(1.02333);
  43247. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43248. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43249. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43250. result.yz = harmonics.l2_1.scale(0.858086);
  43251. result.zx = harmonics.l21.scale(0.858086);
  43252. result.xy = harmonics.l2_2.scale(0.858086);
  43253. result.scale(1.0 / Math.PI);
  43254. return result;
  43255. };
  43256. /**
  43257. * Constructs a spherical polynomial from an array.
  43258. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43259. * @returns the spherical polynomial
  43260. */
  43261. SphericalPolynomial.FromArray = function (data) {
  43262. var sp = new SphericalPolynomial();
  43263. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43264. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43265. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43266. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43267. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43268. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43269. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43270. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43271. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43272. return sp;
  43273. };
  43274. return SphericalPolynomial;
  43275. }());
  43276. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43277. /**
  43278. * Class representing spherical harmonics coefficients to the 3rd degree
  43279. */
  43280. var SphericalHarmonics = /** @class */ (function () {
  43281. function SphericalHarmonics() {
  43282. /**
  43283. * The l0,0 coefficients of the spherical harmonics
  43284. */
  43285. this.l00 = BABYLON.Vector3.Zero();
  43286. /**
  43287. * The l1,-1 coefficients of the spherical harmonics
  43288. */
  43289. this.l1_1 = BABYLON.Vector3.Zero();
  43290. /**
  43291. * The l1,0 coefficients of the spherical harmonics
  43292. */
  43293. this.l10 = BABYLON.Vector3.Zero();
  43294. /**
  43295. * The l1,1 coefficients of the spherical harmonics
  43296. */
  43297. this.l11 = BABYLON.Vector3.Zero();
  43298. /**
  43299. * The l2,-2 coefficients of the spherical harmonics
  43300. */
  43301. this.l2_2 = BABYLON.Vector3.Zero();
  43302. /**
  43303. * The l2,-1 coefficients of the spherical harmonics
  43304. */
  43305. this.l2_1 = BABYLON.Vector3.Zero();
  43306. /**
  43307. * The l2,0 coefficients of the spherical harmonics
  43308. */
  43309. this.l20 = BABYLON.Vector3.Zero();
  43310. /**
  43311. * The l2,1 coefficients of the spherical harmonics
  43312. */
  43313. this.l21 = BABYLON.Vector3.Zero();
  43314. /**
  43315. * The l2,2 coefficients of the spherical harmonics
  43316. */
  43317. this.lL22 = BABYLON.Vector3.Zero();
  43318. }
  43319. /**
  43320. * Adds a light to the spherical harmonics
  43321. * @param direction the direction of the light
  43322. * @param color the color of the light
  43323. * @param deltaSolidAngle the delta solid angle of the light
  43324. */
  43325. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43326. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43327. var c = colorVector.scale(deltaSolidAngle);
  43328. this.l00 = this.l00.add(c.scale(0.282095));
  43329. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43330. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43331. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43332. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43333. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43334. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43335. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43336. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43337. };
  43338. /**
  43339. * Scales the spherical harmonics by the given amount
  43340. * @param scale the amount to scale
  43341. */
  43342. SphericalHarmonics.prototype.scale = function (scale) {
  43343. this.l00 = this.l00.scale(scale);
  43344. this.l1_1 = this.l1_1.scale(scale);
  43345. this.l10 = this.l10.scale(scale);
  43346. this.l11 = this.l11.scale(scale);
  43347. this.l2_2 = this.l2_2.scale(scale);
  43348. this.l2_1 = this.l2_1.scale(scale);
  43349. this.l20 = this.l20.scale(scale);
  43350. this.l21 = this.l21.scale(scale);
  43351. this.lL22 = this.lL22.scale(scale);
  43352. };
  43353. /**
  43354. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43355. *
  43356. * ```
  43357. * E_lm = A_l * L_lm
  43358. * ```
  43359. *
  43360. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43361. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43362. * the scaling factors are given in equation 9.
  43363. */
  43364. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43365. // Constant (Band 0)
  43366. this.l00 = this.l00.scale(3.141593);
  43367. // Linear (Band 1)
  43368. this.l1_1 = this.l1_1.scale(2.094395);
  43369. this.l10 = this.l10.scale(2.094395);
  43370. this.l11 = this.l11.scale(2.094395);
  43371. // Quadratic (Band 2)
  43372. this.l2_2 = this.l2_2.scale(0.785398);
  43373. this.l2_1 = this.l2_1.scale(0.785398);
  43374. this.l20 = this.l20.scale(0.785398);
  43375. this.l21 = this.l21.scale(0.785398);
  43376. this.lL22 = this.lL22.scale(0.785398);
  43377. };
  43378. /**
  43379. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43380. *
  43381. * ```
  43382. * L = (1/pi) * E * rho
  43383. * ```
  43384. *
  43385. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43386. */
  43387. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43388. this.scale(1.0 / Math.PI);
  43389. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43390. // (The pixel shader must apply albedo after texture fetches, etc).
  43391. };
  43392. /**
  43393. * Gets the spherical harmonics from polynomial
  43394. * @param polynomial the spherical polynomial
  43395. * @returns the spherical harmonics
  43396. */
  43397. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43398. var result = new SphericalHarmonics();
  43399. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43400. result.l1_1 = polynomial.y.scale(0.977204);
  43401. result.l10 = polynomial.z.scale(0.977204);
  43402. result.l11 = polynomial.x.scale(0.977204);
  43403. result.l2_2 = polynomial.xy.scale(1.16538);
  43404. result.l2_1 = polynomial.yz.scale(1.16538);
  43405. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43406. result.l21 = polynomial.zx.scale(1.16538);
  43407. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43408. result.scale(Math.PI);
  43409. return result;
  43410. };
  43411. /**
  43412. * Constructs a spherical harmonics from an array.
  43413. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43414. * @returns the spherical harmonics
  43415. */
  43416. SphericalHarmonics.FromArray = function (data) {
  43417. var sh = new SphericalHarmonics();
  43418. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43419. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43420. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43421. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43422. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43423. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43424. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43425. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43426. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43427. return sh;
  43428. };
  43429. return SphericalHarmonics;
  43430. }());
  43431. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43432. })(BABYLON || (BABYLON = {}));
  43433. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43434. var BABYLON;
  43435. (function (BABYLON) {
  43436. var FileFaceOrientation = /** @class */ (function () {
  43437. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43438. this.name = name;
  43439. this.worldAxisForNormal = worldAxisForNormal;
  43440. this.worldAxisForFileX = worldAxisForFileX;
  43441. this.worldAxisForFileY = worldAxisForFileY;
  43442. }
  43443. return FileFaceOrientation;
  43444. }());
  43445. ;
  43446. /**
  43447. * Helper class dealing with the extraction of spherical polynomial dataArray
  43448. * from a cube map.
  43449. */
  43450. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43451. function CubeMapToSphericalPolynomialTools() {
  43452. }
  43453. /**
  43454. * Converts a texture to the according Spherical Polynomial data.
  43455. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43456. *
  43457. * @param texture The texture to extract the information from.
  43458. * @return The Spherical Polynomial data.
  43459. */
  43460. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43461. if (!texture.isCube) {
  43462. // Only supports cube Textures currently.
  43463. return null;
  43464. }
  43465. var size = texture.getSize().width;
  43466. var right = texture.readPixels(0);
  43467. var left = texture.readPixels(1);
  43468. var up;
  43469. var down;
  43470. if (texture.isRenderTarget) {
  43471. up = texture.readPixels(3);
  43472. down = texture.readPixels(2);
  43473. }
  43474. else {
  43475. up = texture.readPixels(2);
  43476. down = texture.readPixels(3);
  43477. }
  43478. var front = texture.readPixels(4);
  43479. var back = texture.readPixels(5);
  43480. var gammaSpace = texture.gammaSpace;
  43481. // Always read as RGBA.
  43482. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43483. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43484. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43485. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43486. }
  43487. var cubeInfo = {
  43488. size: size,
  43489. right: right,
  43490. left: left,
  43491. up: up,
  43492. down: down,
  43493. front: front,
  43494. back: back,
  43495. format: format,
  43496. type: type,
  43497. gammaSpace: gammaSpace,
  43498. };
  43499. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43500. };
  43501. /**
  43502. * Converts a cubemap to the according Spherical Polynomial data.
  43503. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43504. *
  43505. * @param cubeInfo The Cube map to extract the information from.
  43506. * @return The Spherical Polynomial data.
  43507. */
  43508. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43509. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43510. var totalSolidAngle = 0.0;
  43511. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43512. var du = 2.0 / cubeInfo.size;
  43513. var dv = du;
  43514. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43515. var minUV = du * 0.5 - 1.0;
  43516. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43517. var fileFace = this.FileFaces[faceIndex];
  43518. var dataArray = cubeInfo[fileFace.name];
  43519. var v = minUV;
  43520. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43521. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43522. // Because SP is still linear, so summation is fine in that basis.
  43523. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43524. for (var y = 0; y < cubeInfo.size; y++) {
  43525. var u = minUV;
  43526. for (var x = 0; x < cubeInfo.size; x++) {
  43527. // World direction (not normalised)
  43528. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43529. worldDirection.normalize();
  43530. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43531. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43532. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43533. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43534. // Handle Integer types.
  43535. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43536. r /= 255;
  43537. g /= 255;
  43538. b /= 255;
  43539. }
  43540. // Handle Gamma space textures.
  43541. if (cubeInfo.gammaSpace) {
  43542. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43543. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43544. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43545. }
  43546. var color = new BABYLON.Color3(r, g, b);
  43547. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43548. totalSolidAngle += deltaSolidAngle;
  43549. u += du;
  43550. }
  43551. v += dv;
  43552. }
  43553. }
  43554. // Solid angle for entire sphere is 4*pi
  43555. var sphereSolidAngle = 4.0 * Math.PI;
  43556. // Adjust the solid angle to allow for how many faces we processed.
  43557. var facesProcessed = 6.0;
  43558. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43559. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43560. // This is needed because the numerical integration over the cube uses a
  43561. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43562. // and also to compensate for accumulative error due to float precision in the summation.
  43563. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43564. sphericalHarmonics.scale(correctionFactor);
  43565. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43566. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43567. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43568. };
  43569. CubeMapToSphericalPolynomialTools.FileFaces = [
  43570. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43571. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43572. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43573. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43574. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43575. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43576. ];
  43577. return CubeMapToSphericalPolynomialTools;
  43578. }());
  43579. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43580. })(BABYLON || (BABYLON = {}));
  43581. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43582. var BABYLON;
  43583. (function (BABYLON) {
  43584. /**
  43585. * Manages the defines for the PBR Material.
  43586. * @hiddenChildren
  43587. */
  43588. var PBRMaterialDefines = /** @class */ (function (_super) {
  43589. __extends(PBRMaterialDefines, _super);
  43590. /**
  43591. * Initializes the PBR Material defines.
  43592. */
  43593. function PBRMaterialDefines() {
  43594. var _this = _super.call(this) || this;
  43595. _this.PBR = true;
  43596. _this.MAINUV1 = false;
  43597. _this.MAINUV2 = false;
  43598. _this.UV1 = false;
  43599. _this.UV2 = false;
  43600. _this.ALBEDO = false;
  43601. _this.ALBEDODIRECTUV = 0;
  43602. _this.VERTEXCOLOR = false;
  43603. _this.AMBIENT = false;
  43604. _this.AMBIENTDIRECTUV = 0;
  43605. _this.AMBIENTINGRAYSCALE = false;
  43606. _this.OPACITY = false;
  43607. _this.VERTEXALPHA = false;
  43608. _this.OPACITYDIRECTUV = 0;
  43609. _this.OPACITYRGB = false;
  43610. _this.ALPHATEST = false;
  43611. _this.DEPTHPREPASS = false;
  43612. _this.ALPHABLEND = false;
  43613. _this.ALPHAFROMALBEDO = false;
  43614. _this.ALPHATESTVALUE = "0.5";
  43615. _this.SPECULAROVERALPHA = false;
  43616. _this.RADIANCEOVERALPHA = false;
  43617. _this.ALPHAFRESNEL = false;
  43618. _this.LINEARALPHAFRESNEL = false;
  43619. _this.PREMULTIPLYALPHA = false;
  43620. _this.EMISSIVE = false;
  43621. _this.EMISSIVEDIRECTUV = 0;
  43622. _this.REFLECTIVITY = false;
  43623. _this.REFLECTIVITYDIRECTUV = 0;
  43624. _this.SPECULARTERM = false;
  43625. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43626. _this.MICROSURFACEAUTOMATIC = false;
  43627. _this.LODBASEDMICROSFURACE = false;
  43628. _this.MICROSURFACEMAP = false;
  43629. _this.MICROSURFACEMAPDIRECTUV = 0;
  43630. _this.METALLICWORKFLOW = false;
  43631. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43632. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43633. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43634. _this.AOSTOREINMETALMAPRED = false;
  43635. _this.ENVIRONMENTBRDF = false;
  43636. _this.NORMAL = false;
  43637. _this.TANGENT = false;
  43638. _this.BUMP = false;
  43639. _this.BUMPDIRECTUV = 0;
  43640. _this.OBJECTSPACE_NORMALMAP = false;
  43641. _this.PARALLAX = false;
  43642. _this.PARALLAXOCCLUSION = false;
  43643. _this.NORMALXYSCALE = true;
  43644. _this.LIGHTMAP = false;
  43645. _this.LIGHTMAPDIRECTUV = 0;
  43646. _this.USELIGHTMAPASSHADOWMAP = false;
  43647. _this.GAMMALIGHTMAP = false;
  43648. _this.REFLECTION = false;
  43649. _this.REFLECTIONMAP_3D = false;
  43650. _this.REFLECTIONMAP_SPHERICAL = false;
  43651. _this.REFLECTIONMAP_PLANAR = false;
  43652. _this.REFLECTIONMAP_CUBIC = false;
  43653. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43654. _this.REFLECTIONMAP_PROJECTION = false;
  43655. _this.REFLECTIONMAP_SKYBOX = false;
  43656. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43657. _this.REFLECTIONMAP_EXPLICIT = false;
  43658. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43659. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43660. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43661. _this.INVERTCUBICMAP = false;
  43662. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43663. _this.USESPHERICALINVERTEX = false;
  43664. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43665. _this.LODINREFLECTIONALPHA = false;
  43666. _this.GAMMAREFLECTION = false;
  43667. _this.RGBDREFLECTION = false;
  43668. _this.RADIANCEOCCLUSION = false;
  43669. _this.HORIZONOCCLUSION = false;
  43670. _this.REFRACTION = false;
  43671. _this.REFRACTIONMAP_3D = false;
  43672. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43673. _this.LODINREFRACTIONALPHA = false;
  43674. _this.GAMMAREFRACTION = false;
  43675. _this.RGBDREFRACTION = false;
  43676. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43677. _this.INSTANCES = false;
  43678. _this.NUM_BONE_INFLUENCERS = 0;
  43679. _this.BonesPerMesh = 0;
  43680. _this.NONUNIFORMSCALING = false;
  43681. _this.MORPHTARGETS = false;
  43682. _this.MORPHTARGETS_NORMAL = false;
  43683. _this.MORPHTARGETS_TANGENT = false;
  43684. _this.NUM_MORPH_INFLUENCERS = 0;
  43685. _this.IMAGEPROCESSING = false;
  43686. _this.VIGNETTE = false;
  43687. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43688. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43689. _this.TONEMAPPING = false;
  43690. _this.TONEMAPPING_ACES = false;
  43691. _this.CONTRAST = false;
  43692. _this.COLORCURVES = false;
  43693. _this.COLORGRADING = false;
  43694. _this.COLORGRADING3D = false;
  43695. _this.SAMPLER3DGREENDEPTH = false;
  43696. _this.SAMPLER3DBGRMAP = false;
  43697. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43698. _this.EXPOSURE = false;
  43699. _this.USEPHYSICALLIGHTFALLOFF = false;
  43700. _this.USEGLTFLIGHTFALLOFF = false;
  43701. _this.TWOSIDEDLIGHTING = false;
  43702. _this.SHADOWFLOAT = false;
  43703. _this.CLIPPLANE = false;
  43704. _this.CLIPPLANE2 = false;
  43705. _this.CLIPPLANE3 = false;
  43706. _this.CLIPPLANE4 = false;
  43707. _this.POINTSIZE = false;
  43708. _this.FOG = false;
  43709. _this.LOGARITHMICDEPTH = false;
  43710. _this.FORCENORMALFORWARD = false;
  43711. _this.SPECULARAA = false;
  43712. _this.UNLIT = false;
  43713. _this.rebuild();
  43714. return _this;
  43715. }
  43716. /**
  43717. * Resets the PBR Material defines.
  43718. */
  43719. PBRMaterialDefines.prototype.reset = function () {
  43720. _super.prototype.reset.call(this);
  43721. this.ALPHATESTVALUE = "0.5";
  43722. this.PBR = true;
  43723. };
  43724. return PBRMaterialDefines;
  43725. }(BABYLON.MaterialDefines));
  43726. /**
  43727. * The Physically based material base class of BJS.
  43728. *
  43729. * This offers the main features of a standard PBR material.
  43730. * For more information, please refer to the documentation :
  43731. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43732. */
  43733. var PBRBaseMaterial = /** @class */ (function (_super) {
  43734. __extends(PBRBaseMaterial, _super);
  43735. /**
  43736. * Instantiates a new PBRMaterial instance.
  43737. *
  43738. * @param name The material name
  43739. * @param scene The scene the material will be use in.
  43740. */
  43741. function PBRBaseMaterial(name, scene) {
  43742. var _this = _super.call(this, name, scene) || this;
  43743. /**
  43744. * Intensity of the direct lights e.g. the four lights available in your scene.
  43745. * This impacts both the direct diffuse and specular highlights.
  43746. */
  43747. _this._directIntensity = 1.0;
  43748. /**
  43749. * Intensity of the emissive part of the material.
  43750. * This helps controlling the emissive effect without modifying the emissive color.
  43751. */
  43752. _this._emissiveIntensity = 1.0;
  43753. /**
  43754. * Intensity of the environment e.g. how much the environment will light the object
  43755. * either through harmonics for rough material or through the refelction for shiny ones.
  43756. */
  43757. _this._environmentIntensity = 1.0;
  43758. /**
  43759. * This is a special control allowing the reduction of the specular highlights coming from the
  43760. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43761. */
  43762. _this._specularIntensity = 1.0;
  43763. /**
  43764. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43765. */
  43766. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43767. /**
  43768. * Debug Control allowing disabling the bump map on this material.
  43769. */
  43770. _this._disableBumpMap = false;
  43771. /**
  43772. * AKA Occlusion Texture Intensity in other nomenclature.
  43773. */
  43774. _this._ambientTextureStrength = 1.0;
  43775. /**
  43776. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43777. * 1 means it completely occludes it
  43778. * 0 mean it has no impact
  43779. */
  43780. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43781. /**
  43782. * The color of a material in ambient lighting.
  43783. */
  43784. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43785. /**
  43786. * AKA Diffuse Color in other nomenclature.
  43787. */
  43788. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43789. /**
  43790. * AKA Specular Color in other nomenclature.
  43791. */
  43792. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43793. /**
  43794. * The color applied when light is reflected from a material.
  43795. */
  43796. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43797. /**
  43798. * The color applied when light is emitted from a material.
  43799. */
  43800. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43801. /**
  43802. * AKA Glossiness in other nomenclature.
  43803. */
  43804. _this._microSurface = 0.9;
  43805. /**
  43806. * source material index of refraction (IOR)' / 'destination material IOR.
  43807. */
  43808. _this._indexOfRefraction = 0.66;
  43809. /**
  43810. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43811. */
  43812. _this._invertRefractionY = false;
  43813. /**
  43814. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43815. * Materials half opaque for instance using refraction could benefit from this control.
  43816. */
  43817. _this._linkRefractionWithTransparency = false;
  43818. /**
  43819. * Specifies that the material will use the light map as a show map.
  43820. */
  43821. _this._useLightmapAsShadowmap = false;
  43822. /**
  43823. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43824. * makes the reflect vector face the model (under horizon).
  43825. */
  43826. _this._useHorizonOcclusion = true;
  43827. /**
  43828. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43829. * too much the area relying on ambient texture to define their ambient occlusion.
  43830. */
  43831. _this._useRadianceOcclusion = true;
  43832. /**
  43833. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43834. */
  43835. _this._useAlphaFromAlbedoTexture = false;
  43836. /**
  43837. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43838. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43839. */
  43840. _this._useSpecularOverAlpha = true;
  43841. /**
  43842. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43843. */
  43844. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43845. /**
  43846. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43847. */
  43848. _this._useRoughnessFromMetallicTextureAlpha = true;
  43849. /**
  43850. * Specifies if the metallic texture contains the roughness information in its green channel.
  43851. */
  43852. _this._useRoughnessFromMetallicTextureGreen = false;
  43853. /**
  43854. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43855. */
  43856. _this._useMetallnessFromMetallicTextureBlue = false;
  43857. /**
  43858. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43859. */
  43860. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43861. /**
  43862. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43863. */
  43864. _this._useAmbientInGrayScale = false;
  43865. /**
  43866. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43867. * The material will try to infer what glossiness each pixel should be.
  43868. */
  43869. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43870. /**
  43871. * Defines the falloff type used in this material.
  43872. * It by default is Physical.
  43873. */
  43874. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43875. /**
  43876. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43877. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43878. */
  43879. _this._useRadianceOverAlpha = true;
  43880. /**
  43881. * Allows using an object space normal map (instead of tangent space).
  43882. */
  43883. _this._useObjectSpaceNormalMap = false;
  43884. /**
  43885. * Allows using the bump map in parallax mode.
  43886. */
  43887. _this._useParallax = false;
  43888. /**
  43889. * Allows using the bump map in parallax occlusion mode.
  43890. */
  43891. _this._useParallaxOcclusion = false;
  43892. /**
  43893. * Controls the scale bias of the parallax mode.
  43894. */
  43895. _this._parallaxScaleBias = 0.05;
  43896. /**
  43897. * If sets to true, disables all the lights affecting the material.
  43898. */
  43899. _this._disableLighting = false;
  43900. /**
  43901. * Number of Simultaneous lights allowed on the material.
  43902. */
  43903. _this._maxSimultaneousLights = 4;
  43904. /**
  43905. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43906. */
  43907. _this._invertNormalMapX = false;
  43908. /**
  43909. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43910. */
  43911. _this._invertNormalMapY = false;
  43912. /**
  43913. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43914. */
  43915. _this._twoSidedLighting = false;
  43916. /**
  43917. * Defines the alpha limits in alpha test mode.
  43918. */
  43919. _this._alphaCutOff = 0.4;
  43920. /**
  43921. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43922. */
  43923. _this._forceAlphaTest = false;
  43924. /**
  43925. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43926. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43927. */
  43928. _this._useAlphaFresnel = false;
  43929. /**
  43930. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43931. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43932. */
  43933. _this._useLinearAlphaFresnel = false;
  43934. /**
  43935. * The transparency mode of the material.
  43936. */
  43937. _this._transparencyMode = null;
  43938. /**
  43939. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43940. * from cos thetav and roughness:
  43941. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43942. */
  43943. _this._environmentBRDFTexture = null;
  43944. /**
  43945. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43946. */
  43947. _this._forceIrradianceInFragment = false;
  43948. /**
  43949. * Force normal to face away from face.
  43950. */
  43951. _this._forceNormalForward = false;
  43952. /**
  43953. * Enables specular anti aliasing in the PBR shader.
  43954. * It will both interacts on the Geometry for analytical and IBL lighting.
  43955. * It also prefilter the roughness map based on the bump values.
  43956. */
  43957. _this._enableSpecularAntiAliasing = false;
  43958. /**
  43959. * Stores the available render targets.
  43960. */
  43961. _this._renderTargets = new BABYLON.SmartArray(16);
  43962. /**
  43963. * Sets the global ambient color for the material used in lighting calculations.
  43964. */
  43965. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43966. /**
  43967. * If set to true, no lighting calculations will be applied.
  43968. */
  43969. _this._unlit = false;
  43970. // Setup the default processing configuration to the scene.
  43971. _this._attachImageProcessingConfiguration(null);
  43972. _this.getRenderTargetTextures = function () {
  43973. _this._renderTargets.reset();
  43974. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43975. _this._renderTargets.push(_this._reflectionTexture);
  43976. }
  43977. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43978. _this._renderTargets.push(_this._refractionTexture);
  43979. }
  43980. return _this._renderTargets;
  43981. };
  43982. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43983. return _this;
  43984. }
  43985. /**
  43986. * Attaches a new image processing configuration to the PBR Material.
  43987. * @param configuration
  43988. */
  43989. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43990. var _this = this;
  43991. if (configuration === this._imageProcessingConfiguration) {
  43992. return;
  43993. }
  43994. // Detaches observer.
  43995. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43996. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43997. }
  43998. // Pick the scene configuration if needed.
  43999. if (!configuration) {
  44000. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44001. }
  44002. else {
  44003. this._imageProcessingConfiguration = configuration;
  44004. }
  44005. // Attaches observer.
  44006. if (this._imageProcessingConfiguration) {
  44007. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44008. _this._markAllSubMeshesAsImageProcessingDirty();
  44009. });
  44010. }
  44011. };
  44012. /**
  44013. * Gets the name of the material class.
  44014. */
  44015. PBRBaseMaterial.prototype.getClassName = function () {
  44016. return "PBRBaseMaterial";
  44017. };
  44018. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44019. /**
  44020. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44021. */
  44022. get: function () {
  44023. return this._useLogarithmicDepth;
  44024. },
  44025. /**
  44026. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44027. */
  44028. set: function (value) {
  44029. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44030. },
  44031. enumerable: true,
  44032. configurable: true
  44033. });
  44034. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44035. /**
  44036. * Gets the current transparency mode.
  44037. */
  44038. get: function () {
  44039. return this._transparencyMode;
  44040. },
  44041. /**
  44042. * Sets the transparency mode of the material.
  44043. *
  44044. * | Value | Type | Description |
  44045. * | ----- | ----------------------------------- | ----------- |
  44046. * | 0 | OPAQUE | |
  44047. * | 1 | ALPHATEST | |
  44048. * | 2 | ALPHABLEND | |
  44049. * | 3 | ALPHATESTANDBLEND | |
  44050. *
  44051. */
  44052. set: function (value) {
  44053. if (this._transparencyMode === value) {
  44054. return;
  44055. }
  44056. this._transparencyMode = value;
  44057. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44058. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44059. },
  44060. enumerable: true,
  44061. configurable: true
  44062. });
  44063. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44064. /**
  44065. * Returns true if alpha blending should be disabled.
  44066. */
  44067. get: function () {
  44068. return (this._linkRefractionWithTransparency ||
  44069. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44070. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44071. },
  44072. enumerable: true,
  44073. configurable: true
  44074. });
  44075. /**
  44076. * Specifies whether or not this material should be rendered in alpha blend mode.
  44077. */
  44078. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44079. if (this._disableAlphaBlending) {
  44080. return false;
  44081. }
  44082. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44083. };
  44084. /**
  44085. * Specifies if the mesh will require alpha blending.
  44086. * @param mesh - BJS mesh.
  44087. */
  44088. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44089. if (this._disableAlphaBlending) {
  44090. return false;
  44091. }
  44092. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44093. };
  44094. /**
  44095. * Specifies whether or not this material should be rendered in alpha test mode.
  44096. */
  44097. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44098. if (this._forceAlphaTest) {
  44099. return true;
  44100. }
  44101. if (this._linkRefractionWithTransparency) {
  44102. return false;
  44103. }
  44104. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44105. };
  44106. /**
  44107. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44108. */
  44109. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44110. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44111. };
  44112. /**
  44113. * Gets the texture used for the alpha test.
  44114. */
  44115. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44116. return this._albedoTexture;
  44117. };
  44118. /**
  44119. * Specifies that the submesh is ready to be used.
  44120. * @param mesh - BJS mesh.
  44121. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44122. * @param useInstances - Specifies that instances should be used.
  44123. * @returns - boolean indicating that the submesh is ready or not.
  44124. */
  44125. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44126. if (subMesh.effect && this.isFrozen) {
  44127. if (this._wasPreviouslyReady) {
  44128. return true;
  44129. }
  44130. }
  44131. if (!subMesh._materialDefines) {
  44132. subMesh._materialDefines = new PBRMaterialDefines();
  44133. }
  44134. var defines = subMesh._materialDefines;
  44135. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44136. if (defines._renderId === this.getScene().getRenderId()) {
  44137. return true;
  44138. }
  44139. }
  44140. var scene = this.getScene();
  44141. var engine = scene.getEngine();
  44142. if (defines._areTexturesDirty) {
  44143. if (scene.texturesEnabled) {
  44144. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44145. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44146. return false;
  44147. }
  44148. }
  44149. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44150. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44151. return false;
  44152. }
  44153. }
  44154. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44155. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44156. return false;
  44157. }
  44158. }
  44159. var reflectionTexture = this._getReflectionTexture();
  44160. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44161. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44162. return false;
  44163. }
  44164. }
  44165. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44166. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44167. return false;
  44168. }
  44169. }
  44170. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44171. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44172. return false;
  44173. }
  44174. }
  44175. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44176. if (this._metallicTexture) {
  44177. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44178. return false;
  44179. }
  44180. }
  44181. else if (this._reflectivityTexture) {
  44182. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44183. return false;
  44184. }
  44185. }
  44186. if (this._microSurfaceTexture) {
  44187. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44188. return false;
  44189. }
  44190. }
  44191. }
  44192. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44193. // Bump texture cannot be not blocking.
  44194. if (!this._bumpTexture.isReady()) {
  44195. return false;
  44196. }
  44197. }
  44198. var refractionTexture = this._getRefractionTexture();
  44199. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44200. if (!refractionTexture.isReadyOrNotBlocking()) {
  44201. return false;
  44202. }
  44203. }
  44204. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44205. // This is blocking.
  44206. if (!this._environmentBRDFTexture.isReady()) {
  44207. return false;
  44208. }
  44209. }
  44210. }
  44211. }
  44212. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44213. if (!this._imageProcessingConfiguration.isReady()) {
  44214. return false;
  44215. }
  44216. }
  44217. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44218. mesh.createNormals(true);
  44219. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44220. }
  44221. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44222. if (effect) {
  44223. scene.resetCachedMaterial();
  44224. subMesh.setEffect(effect, defines);
  44225. this.buildUniformLayout();
  44226. }
  44227. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44228. return false;
  44229. }
  44230. defines._renderId = scene.getRenderId();
  44231. this._wasPreviouslyReady = true;
  44232. return true;
  44233. };
  44234. /**
  44235. * Specifies if the material uses metallic roughness workflow.
  44236. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44237. */
  44238. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44239. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44240. return true;
  44241. }
  44242. return false;
  44243. };
  44244. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44245. if (onCompiled === void 0) { onCompiled = null; }
  44246. if (onError === void 0) { onError = null; }
  44247. if (useInstances === void 0) { useInstances = null; }
  44248. if (useClipPlane === void 0) { useClipPlane = null; }
  44249. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44250. if (!defines.isDirty) {
  44251. return null;
  44252. }
  44253. defines.markAsProcessed();
  44254. var scene = this.getScene();
  44255. var engine = scene.getEngine();
  44256. // Fallbacks
  44257. var fallbacks = new BABYLON.EffectFallbacks();
  44258. var fallbackRank = 0;
  44259. if (defines.USESPHERICALINVERTEX) {
  44260. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44261. }
  44262. if (defines.FOG) {
  44263. fallbacks.addFallback(fallbackRank, "FOG");
  44264. }
  44265. if (defines.SPECULARAA) {
  44266. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44267. }
  44268. if (defines.POINTSIZE) {
  44269. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44270. }
  44271. if (defines.LOGARITHMICDEPTH) {
  44272. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44273. }
  44274. if (defines.PARALLAX) {
  44275. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44276. }
  44277. if (defines.PARALLAXOCCLUSION) {
  44278. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44279. }
  44280. if (defines.ENVIRONMENTBRDF) {
  44281. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44282. }
  44283. if (defines.TANGENT) {
  44284. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44285. }
  44286. if (defines.BUMP) {
  44287. fallbacks.addFallback(fallbackRank++, "BUMP");
  44288. }
  44289. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44290. if (defines.SPECULARTERM) {
  44291. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44292. }
  44293. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44294. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44295. }
  44296. if (defines.LIGHTMAP) {
  44297. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44298. }
  44299. if (defines.NORMAL) {
  44300. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44301. }
  44302. if (defines.AMBIENT) {
  44303. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44304. }
  44305. if (defines.EMISSIVE) {
  44306. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44307. }
  44308. if (defines.VERTEXCOLOR) {
  44309. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44310. }
  44311. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44312. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44313. }
  44314. if (defines.MORPHTARGETS) {
  44315. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44316. }
  44317. //Attributes
  44318. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44319. if (defines.NORMAL) {
  44320. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44321. }
  44322. if (defines.TANGENT) {
  44323. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44324. }
  44325. if (defines.UV1) {
  44326. attribs.push(BABYLON.VertexBuffer.UVKind);
  44327. }
  44328. if (defines.UV2) {
  44329. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44330. }
  44331. if (defines.VERTEXCOLOR) {
  44332. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44333. }
  44334. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44335. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44336. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44337. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44338. "vFogInfos", "vFogColor", "pointSize",
  44339. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44340. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44341. "mBones",
  44342. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44343. "vLightingIntensity",
  44344. "logarithmicDepthConstant",
  44345. "vSphericalX", "vSphericalY", "vSphericalZ",
  44346. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44347. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44348. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44349. "vTangentSpaceParams"
  44350. ];
  44351. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44352. "bumpSampler", "lightmapSampler", "opacitySampler",
  44353. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44354. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44355. "microSurfaceSampler", "environmentBrdfSampler"];
  44356. var uniformBuffers = ["Material", "Scene"];
  44357. if (BABYLON.ImageProcessingConfiguration) {
  44358. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44359. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44360. }
  44361. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44362. uniformsNames: uniforms,
  44363. uniformBuffersNames: uniformBuffers,
  44364. samplers: samplers,
  44365. defines: defines,
  44366. maxSimultaneousLights: this._maxSimultaneousLights
  44367. });
  44368. var join = defines.toString();
  44369. return engine.createEffect("pbr", {
  44370. attributes: attribs,
  44371. uniformsNames: uniforms,
  44372. uniformBuffersNames: uniformBuffers,
  44373. samplers: samplers,
  44374. defines: join,
  44375. fallbacks: fallbacks,
  44376. onCompiled: onCompiled,
  44377. onError: onError,
  44378. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44379. }, engine);
  44380. };
  44381. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44382. if (useInstances === void 0) { useInstances = null; }
  44383. if (useClipPlane === void 0) { useClipPlane = null; }
  44384. var scene = this.getScene();
  44385. var engine = scene.getEngine();
  44386. // Lights
  44387. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44388. defines._needNormals = true;
  44389. // Textures
  44390. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44391. if (defines._areTexturesDirty) {
  44392. defines._needUVs = false;
  44393. if (scene.texturesEnabled) {
  44394. if (scene.getEngine().getCaps().textureLOD) {
  44395. defines.LODBASEDMICROSFURACE = true;
  44396. }
  44397. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44398. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44399. }
  44400. else {
  44401. defines.ALBEDO = false;
  44402. }
  44403. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44404. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44405. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44406. }
  44407. else {
  44408. defines.AMBIENT = false;
  44409. }
  44410. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44411. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44412. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44413. }
  44414. else {
  44415. defines.OPACITY = false;
  44416. }
  44417. var reflectionTexture = this._getReflectionTexture();
  44418. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44419. defines.REFLECTION = true;
  44420. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44421. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44422. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44423. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44424. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44425. defines.INVERTCUBICMAP = true;
  44426. }
  44427. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44428. switch (reflectionTexture.coordinatesMode) {
  44429. case BABYLON.Texture.EXPLICIT_MODE:
  44430. defines.REFLECTIONMAP_EXPLICIT = true;
  44431. break;
  44432. case BABYLON.Texture.PLANAR_MODE:
  44433. defines.REFLECTIONMAP_PLANAR = true;
  44434. break;
  44435. case BABYLON.Texture.PROJECTION_MODE:
  44436. defines.REFLECTIONMAP_PROJECTION = true;
  44437. break;
  44438. case BABYLON.Texture.SKYBOX_MODE:
  44439. defines.REFLECTIONMAP_SKYBOX = true;
  44440. break;
  44441. case BABYLON.Texture.SPHERICAL_MODE:
  44442. defines.REFLECTIONMAP_SPHERICAL = true;
  44443. break;
  44444. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44445. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44446. break;
  44447. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44448. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44449. break;
  44450. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44451. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44452. break;
  44453. case BABYLON.Texture.CUBIC_MODE:
  44454. case BABYLON.Texture.INVCUBIC_MODE:
  44455. default:
  44456. defines.REFLECTIONMAP_CUBIC = true;
  44457. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44458. break;
  44459. }
  44460. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44461. if (reflectionTexture.sphericalPolynomial) {
  44462. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44463. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44464. defines.USESPHERICALINVERTEX = false;
  44465. }
  44466. else {
  44467. defines.USESPHERICALINVERTEX = true;
  44468. }
  44469. }
  44470. }
  44471. else {
  44472. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44473. }
  44474. }
  44475. else {
  44476. defines.REFLECTION = false;
  44477. defines.REFLECTIONMAP_3D = false;
  44478. defines.REFLECTIONMAP_SPHERICAL = false;
  44479. defines.REFLECTIONMAP_PLANAR = false;
  44480. defines.REFLECTIONMAP_CUBIC = false;
  44481. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44482. defines.REFLECTIONMAP_PROJECTION = false;
  44483. defines.REFLECTIONMAP_SKYBOX = false;
  44484. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44485. defines.REFLECTIONMAP_EXPLICIT = false;
  44486. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44487. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44488. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44489. defines.INVERTCUBICMAP = false;
  44490. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44491. defines.USESPHERICALINVERTEX = false;
  44492. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44493. defines.LODINREFLECTIONALPHA = false;
  44494. defines.GAMMAREFLECTION = false;
  44495. defines.RGBDREFLECTION = false;
  44496. }
  44497. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44498. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44499. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44500. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44501. }
  44502. else {
  44503. defines.LIGHTMAP = false;
  44504. }
  44505. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44506. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44507. }
  44508. else {
  44509. defines.EMISSIVE = false;
  44510. }
  44511. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44512. if (this._metallicTexture) {
  44513. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44514. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44515. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44516. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44517. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44518. }
  44519. else if (this._reflectivityTexture) {
  44520. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44521. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44522. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44523. }
  44524. else {
  44525. defines.REFLECTIVITY = false;
  44526. }
  44527. if (this._microSurfaceTexture) {
  44528. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44529. }
  44530. else {
  44531. defines.MICROSURFACEMAP = false;
  44532. }
  44533. }
  44534. else {
  44535. defines.REFLECTIVITY = false;
  44536. defines.MICROSURFACEMAP = false;
  44537. }
  44538. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44539. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44540. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44541. defines.PARALLAX = true;
  44542. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44543. }
  44544. else {
  44545. defines.PARALLAX = false;
  44546. }
  44547. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44548. }
  44549. else {
  44550. defines.BUMP = false;
  44551. }
  44552. var refractionTexture = this._getRefractionTexture();
  44553. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44554. defines.REFRACTION = true;
  44555. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44556. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44557. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44558. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44559. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44560. if (this._linkRefractionWithTransparency) {
  44561. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44562. }
  44563. }
  44564. else {
  44565. defines.REFRACTION = false;
  44566. }
  44567. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44568. defines.ENVIRONMENTBRDF = true;
  44569. }
  44570. else {
  44571. defines.ENVIRONMENTBRDF = false;
  44572. }
  44573. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44574. defines.ALPHAFROMALBEDO = true;
  44575. }
  44576. else {
  44577. defines.ALPHAFROMALBEDO = false;
  44578. }
  44579. }
  44580. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44581. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44582. defines.USEPHYSICALLIGHTFALLOFF = false;
  44583. defines.USEGLTFLIGHTFALLOFF = false;
  44584. }
  44585. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44586. defines.USEPHYSICALLIGHTFALLOFF = false;
  44587. defines.USEGLTFLIGHTFALLOFF = true;
  44588. }
  44589. else {
  44590. defines.USEPHYSICALLIGHTFALLOFF = true;
  44591. defines.USEGLTFLIGHTFALLOFF = false;
  44592. }
  44593. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44594. if (!this.backFaceCulling && this._twoSidedLighting) {
  44595. defines.TWOSIDEDLIGHTING = true;
  44596. }
  44597. else {
  44598. defines.TWOSIDEDLIGHTING = false;
  44599. }
  44600. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44601. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44602. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44603. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44604. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44605. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44606. }
  44607. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44608. this._imageProcessingConfiguration.prepareDefines(defines);
  44609. }
  44610. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44611. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44612. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44613. // Misc.
  44614. if (defines._areMiscDirty) {
  44615. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44616. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44617. }
  44618. // Values that need to be evaluated on every frame
  44619. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44620. // Attribs
  44621. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44622. };
  44623. /**
  44624. * Force shader compilation
  44625. */
  44626. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44627. var _this = this;
  44628. var localOptions = __assign({ clipPlane: false }, options);
  44629. var defines = new PBRMaterialDefines();
  44630. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44631. if (effect.isReady()) {
  44632. if (onCompiled) {
  44633. onCompiled(this);
  44634. }
  44635. }
  44636. else {
  44637. effect.onCompileObservable.add(function () {
  44638. if (onCompiled) {
  44639. onCompiled(_this);
  44640. }
  44641. });
  44642. }
  44643. };
  44644. /**
  44645. * Initializes the uniform buffer layout for the shader.
  44646. */
  44647. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44648. // Order is important !
  44649. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44650. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44651. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44652. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44653. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44654. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44655. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44656. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44657. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44658. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44659. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44660. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44661. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44662. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44663. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44664. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44665. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44666. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44667. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44668. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44669. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44670. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44671. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44672. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44673. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44674. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44675. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44676. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44677. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44678. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44679. this._uniformBuffer.addUniform("pointSize", 1);
  44680. this._uniformBuffer.create();
  44681. };
  44682. /**
  44683. * Unbinds the textures.
  44684. */
  44685. PBRBaseMaterial.prototype.unbind = function () {
  44686. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44687. this._uniformBuffer.setTexture("reflectionSampler", null);
  44688. }
  44689. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44690. this._uniformBuffer.setTexture("refractionSampler", null);
  44691. }
  44692. _super.prototype.unbind.call(this);
  44693. };
  44694. /**
  44695. * Binds the submesh data.
  44696. * @param world - The world matrix.
  44697. * @param mesh - The BJS mesh.
  44698. * @param subMesh - A submesh of the BJS mesh.
  44699. */
  44700. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44701. var scene = this.getScene();
  44702. var defines = subMesh._materialDefines;
  44703. if (!defines) {
  44704. return;
  44705. }
  44706. var effect = subMesh.effect;
  44707. if (!effect) {
  44708. return;
  44709. }
  44710. this._activeEffect = effect;
  44711. // Matrices
  44712. this.bindOnlyWorldMatrix(world);
  44713. // Normal Matrix
  44714. if (defines.OBJECTSPACE_NORMALMAP) {
  44715. world.toNormalMatrix(this._normalMatrix);
  44716. this.bindOnlyNormalMatrix(this._normalMatrix);
  44717. }
  44718. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44719. // Bones
  44720. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44721. var reflectionTexture = null;
  44722. if (mustRebind) {
  44723. this._uniformBuffer.bindToEffect(effect, "Material");
  44724. this.bindViewProjection(effect);
  44725. reflectionTexture = this._getReflectionTexture();
  44726. var refractionTexture = this._getRefractionTexture();
  44727. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44728. // Texture uniforms
  44729. if (scene.texturesEnabled) {
  44730. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44731. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44732. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44733. }
  44734. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44735. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44736. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44737. }
  44738. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44739. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44740. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44741. }
  44742. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44743. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44744. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44745. if (reflectionTexture.boundingBoxSize) {
  44746. var cubeTexture = reflectionTexture;
  44747. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44748. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44749. }
  44750. var polynomials = reflectionTexture.sphericalPolynomial;
  44751. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44752. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44753. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44754. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44755. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44756. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44757. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44758. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44759. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44760. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44761. }
  44762. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44763. }
  44764. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44765. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44766. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44767. }
  44768. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44769. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44770. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44771. }
  44772. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44773. if (this._metallicTexture) {
  44774. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44775. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44776. }
  44777. else if (this._reflectivityTexture) {
  44778. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44779. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44780. }
  44781. if (this._microSurfaceTexture) {
  44782. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44783. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44784. }
  44785. }
  44786. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44787. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44788. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44789. if (scene._mirroredCameraPosition) {
  44790. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44791. }
  44792. else {
  44793. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44794. }
  44795. }
  44796. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44797. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44798. var depth = 1.0;
  44799. if (!refractionTexture.isCube) {
  44800. if (refractionTexture.depth) {
  44801. depth = refractionTexture.depth;
  44802. }
  44803. }
  44804. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44805. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44806. }
  44807. }
  44808. // Point size
  44809. if (this.pointsCloud) {
  44810. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44811. }
  44812. // Colors
  44813. if (defines.METALLICWORKFLOW) {
  44814. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44815. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44816. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44817. }
  44818. else {
  44819. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44820. }
  44821. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44822. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44823. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44824. // Misc
  44825. this._lightingInfos.x = this._directIntensity;
  44826. this._lightingInfos.y = this._emissiveIntensity;
  44827. this._lightingInfos.z = this._environmentIntensity;
  44828. this._lightingInfos.w = this._specularIntensity;
  44829. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44830. }
  44831. // Textures
  44832. if (scene.texturesEnabled) {
  44833. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44834. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44835. }
  44836. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44837. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44838. }
  44839. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44840. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44841. }
  44842. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44843. if (defines.LODBASEDMICROSFURACE) {
  44844. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44845. }
  44846. else {
  44847. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44848. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44849. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44850. }
  44851. }
  44852. if (defines.ENVIRONMENTBRDF) {
  44853. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44854. }
  44855. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44856. if (defines.LODBASEDMICROSFURACE) {
  44857. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44858. }
  44859. else {
  44860. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44861. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44862. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44863. }
  44864. }
  44865. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44866. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44867. }
  44868. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44869. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44870. }
  44871. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44872. if (this._metallicTexture) {
  44873. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44874. }
  44875. else if (this._reflectivityTexture) {
  44876. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44877. }
  44878. if (this._microSurfaceTexture) {
  44879. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44880. }
  44881. }
  44882. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44883. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44884. }
  44885. }
  44886. // Clip plane
  44887. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44888. // Colors
  44889. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44890. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44891. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44892. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44893. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44894. }
  44895. if (mustRebind || !this.isFrozen) {
  44896. // Lights
  44897. if (scene.lightsEnabled && !this._disableLighting) {
  44898. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44899. }
  44900. // View
  44901. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44902. this.bindView(effect);
  44903. }
  44904. // Fog
  44905. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44906. // Morph targets
  44907. if (defines.NUM_MORPH_INFLUENCERS) {
  44908. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44909. }
  44910. // image processing
  44911. this._imageProcessingConfiguration.bind(this._activeEffect);
  44912. // Log. depth
  44913. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44914. }
  44915. this._uniformBuffer.update();
  44916. this._afterBind(mesh, this._activeEffect);
  44917. };
  44918. /**
  44919. * Returns the animatable textures.
  44920. * @returns - Array of animatable textures.
  44921. */
  44922. PBRBaseMaterial.prototype.getAnimatables = function () {
  44923. var results = [];
  44924. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44925. results.push(this._albedoTexture);
  44926. }
  44927. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44928. results.push(this._ambientTexture);
  44929. }
  44930. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44931. results.push(this._opacityTexture);
  44932. }
  44933. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44934. results.push(this._reflectionTexture);
  44935. }
  44936. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44937. results.push(this._emissiveTexture);
  44938. }
  44939. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44940. results.push(this._metallicTexture);
  44941. }
  44942. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44943. results.push(this._reflectivityTexture);
  44944. }
  44945. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44946. results.push(this._bumpTexture);
  44947. }
  44948. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44949. results.push(this._lightmapTexture);
  44950. }
  44951. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44952. results.push(this._refractionTexture);
  44953. }
  44954. return results;
  44955. };
  44956. /**
  44957. * Returns the texture used for reflections.
  44958. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44959. */
  44960. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44961. if (this._reflectionTexture) {
  44962. return this._reflectionTexture;
  44963. }
  44964. return this.getScene().environmentTexture;
  44965. };
  44966. /**
  44967. * Returns the texture used for refraction or null if none is used.
  44968. * @returns - Refection texture if present. If no refraction texture and refraction
  44969. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44970. */
  44971. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44972. if (this._refractionTexture) {
  44973. return this._refractionTexture;
  44974. }
  44975. if (this._linkRefractionWithTransparency) {
  44976. return this.getScene().environmentTexture;
  44977. }
  44978. return null;
  44979. };
  44980. /**
  44981. * Disposes the resources of the material.
  44982. * @param forceDisposeEffect - Forces the disposal of effects.
  44983. * @param forceDisposeTextures - Forces the disposal of all textures.
  44984. */
  44985. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44986. if (forceDisposeTextures) {
  44987. if (this._albedoTexture) {
  44988. this._albedoTexture.dispose();
  44989. }
  44990. if (this._ambientTexture) {
  44991. this._ambientTexture.dispose();
  44992. }
  44993. if (this._opacityTexture) {
  44994. this._opacityTexture.dispose();
  44995. }
  44996. if (this._reflectionTexture) {
  44997. this._reflectionTexture.dispose();
  44998. }
  44999. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45000. this._environmentBRDFTexture.dispose();
  45001. }
  45002. if (this._emissiveTexture) {
  45003. this._emissiveTexture.dispose();
  45004. }
  45005. if (this._metallicTexture) {
  45006. this._metallicTexture.dispose();
  45007. }
  45008. if (this._reflectivityTexture) {
  45009. this._reflectivityTexture.dispose();
  45010. }
  45011. if (this._bumpTexture) {
  45012. this._bumpTexture.dispose();
  45013. }
  45014. if (this._lightmapTexture) {
  45015. this._lightmapTexture.dispose();
  45016. }
  45017. if (this._refractionTexture) {
  45018. this._refractionTexture.dispose();
  45019. }
  45020. }
  45021. this._renderTargets.dispose();
  45022. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45023. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45024. }
  45025. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45026. };
  45027. /**
  45028. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45029. */
  45030. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45031. /**
  45032. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45033. * to enhance interoperability with other engines.
  45034. */
  45035. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45036. /**
  45037. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45038. * to enhance interoperability with other materials.
  45039. */
  45040. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45041. /**
  45042. * Stores the reflectivity values based on metallic roughness workflow.
  45043. */
  45044. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45045. __decorate([
  45046. BABYLON.serializeAsImageProcessingConfiguration()
  45047. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45048. __decorate([
  45049. BABYLON.serialize()
  45050. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45051. __decorate([
  45052. BABYLON.serialize()
  45053. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45054. return PBRBaseMaterial;
  45055. }(BABYLON.PushMaterial));
  45056. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45057. })(BABYLON || (BABYLON = {}));
  45058. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45059. var BABYLON;
  45060. (function (BABYLON) {
  45061. /**
  45062. * The Physically based simple base material of BJS.
  45063. *
  45064. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45065. * It is used as the base class for both the specGloss and metalRough conventions.
  45066. */
  45067. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45068. __extends(PBRBaseSimpleMaterial, _super);
  45069. /**
  45070. * Instantiates a new PBRMaterial instance.
  45071. *
  45072. * @param name The material name
  45073. * @param scene The scene the material will be use in.
  45074. */
  45075. function PBRBaseSimpleMaterial(name, scene) {
  45076. var _this = _super.call(this, name, scene) || this;
  45077. /**
  45078. * Number of Simultaneous lights allowed on the material.
  45079. */
  45080. _this.maxSimultaneousLights = 4;
  45081. /**
  45082. * If sets to true, disables all the lights affecting the material.
  45083. */
  45084. _this.disableLighting = false;
  45085. /**
  45086. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45087. */
  45088. _this.invertNormalMapX = false;
  45089. /**
  45090. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45091. */
  45092. _this.invertNormalMapY = false;
  45093. /**
  45094. * Emissivie color used to self-illuminate the model.
  45095. */
  45096. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45097. /**
  45098. * Occlusion Channel Strenght.
  45099. */
  45100. _this.occlusionStrength = 1.0;
  45101. _this.useLightmapAsShadowmap = false;
  45102. _this._useAlphaFromAlbedoTexture = true;
  45103. _this._useAmbientInGrayScale = true;
  45104. return _this;
  45105. }
  45106. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45107. /**
  45108. * Gets the current double sided mode.
  45109. */
  45110. get: function () {
  45111. return this._twoSidedLighting;
  45112. },
  45113. /**
  45114. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45115. */
  45116. set: function (value) {
  45117. if (this._twoSidedLighting === value) {
  45118. return;
  45119. }
  45120. this._twoSidedLighting = value;
  45121. this.backFaceCulling = !value;
  45122. this._markAllSubMeshesAsTexturesDirty();
  45123. },
  45124. enumerable: true,
  45125. configurable: true
  45126. });
  45127. /**
  45128. * Return the active textures of the material.
  45129. */
  45130. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45131. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45132. if (this.environmentTexture) {
  45133. activeTextures.push(this.environmentTexture);
  45134. }
  45135. if (this.normalTexture) {
  45136. activeTextures.push(this.normalTexture);
  45137. }
  45138. if (this.emissiveTexture) {
  45139. activeTextures.push(this.emissiveTexture);
  45140. }
  45141. if (this.occlusionTexture) {
  45142. activeTextures.push(this.occlusionTexture);
  45143. }
  45144. if (this.lightmapTexture) {
  45145. activeTextures.push(this.lightmapTexture);
  45146. }
  45147. return activeTextures;
  45148. };
  45149. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45150. if (_super.prototype.hasTexture.call(this, texture)) {
  45151. return true;
  45152. }
  45153. if (this.lightmapTexture === texture) {
  45154. return true;
  45155. }
  45156. return false;
  45157. };
  45158. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45159. return "PBRBaseSimpleMaterial";
  45160. };
  45161. __decorate([
  45162. BABYLON.serialize(),
  45163. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45164. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45165. __decorate([
  45166. BABYLON.serialize(),
  45167. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45168. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45169. __decorate([
  45170. BABYLON.serializeAsTexture(),
  45171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45172. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45173. __decorate([
  45174. BABYLON.serialize(),
  45175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45176. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45177. __decorate([
  45178. BABYLON.serialize(),
  45179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45180. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45181. __decorate([
  45182. BABYLON.serializeAsTexture(),
  45183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45184. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45185. __decorate([
  45186. BABYLON.serializeAsColor3("emissive"),
  45187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45188. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45189. __decorate([
  45190. BABYLON.serializeAsTexture(),
  45191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45192. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45193. __decorate([
  45194. BABYLON.serialize(),
  45195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45196. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45197. __decorate([
  45198. BABYLON.serializeAsTexture(),
  45199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45200. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45201. __decorate([
  45202. BABYLON.serialize(),
  45203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45204. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45205. __decorate([
  45206. BABYLON.serialize()
  45207. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45208. __decorate([
  45209. BABYLON.serializeAsTexture(),
  45210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45211. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45212. __decorate([
  45213. BABYLON.serialize(),
  45214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45215. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45216. return PBRBaseSimpleMaterial;
  45217. }(BABYLON.PBRBaseMaterial));
  45218. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45219. })(BABYLON || (BABYLON = {}));
  45220. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45221. var BABYLON;
  45222. (function (BABYLON) {
  45223. /**
  45224. * The Physically based material of BJS.
  45225. *
  45226. * This offers the main features of a standard PBR material.
  45227. * For more information, please refer to the documentation :
  45228. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45229. */
  45230. var PBRMaterial = /** @class */ (function (_super) {
  45231. __extends(PBRMaterial, _super);
  45232. /**
  45233. * Instantiates a new PBRMaterial instance.
  45234. *
  45235. * @param name The material name
  45236. * @param scene The scene the material will be use in.
  45237. */
  45238. function PBRMaterial(name, scene) {
  45239. var _this = _super.call(this, name, scene) || this;
  45240. /**
  45241. * Intensity of the direct lights e.g. the four lights available in your scene.
  45242. * This impacts both the direct diffuse and specular highlights.
  45243. */
  45244. _this.directIntensity = 1.0;
  45245. /**
  45246. * Intensity of the emissive part of the material.
  45247. * This helps controlling the emissive effect without modifying the emissive color.
  45248. */
  45249. _this.emissiveIntensity = 1.0;
  45250. /**
  45251. * Intensity of the environment e.g. how much the environment will light the object
  45252. * either through harmonics for rough material or through the refelction for shiny ones.
  45253. */
  45254. _this.environmentIntensity = 1.0;
  45255. /**
  45256. * This is a special control allowing the reduction of the specular highlights coming from the
  45257. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45258. */
  45259. _this.specularIntensity = 1.0;
  45260. /**
  45261. * Debug Control allowing disabling the bump map on this material.
  45262. */
  45263. _this.disableBumpMap = false;
  45264. /**
  45265. * AKA Occlusion Texture Intensity in other nomenclature.
  45266. */
  45267. _this.ambientTextureStrength = 1.0;
  45268. /**
  45269. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45270. * 1 means it completely occludes it
  45271. * 0 mean it has no impact
  45272. */
  45273. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45274. /**
  45275. * The color of a material in ambient lighting.
  45276. */
  45277. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45278. /**
  45279. * AKA Diffuse Color in other nomenclature.
  45280. */
  45281. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45282. /**
  45283. * AKA Specular Color in other nomenclature.
  45284. */
  45285. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45286. /**
  45287. * The color reflected from the material.
  45288. */
  45289. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45290. /**
  45291. * The color emitted from the material.
  45292. */
  45293. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45294. /**
  45295. * AKA Glossiness in other nomenclature.
  45296. */
  45297. _this.microSurface = 1.0;
  45298. /**
  45299. * source material index of refraction (IOR)' / 'destination material IOR.
  45300. */
  45301. _this.indexOfRefraction = 0.66;
  45302. /**
  45303. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45304. */
  45305. _this.invertRefractionY = false;
  45306. /**
  45307. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45308. * Materials half opaque for instance using refraction could benefit from this control.
  45309. */
  45310. _this.linkRefractionWithTransparency = false;
  45311. _this.useLightmapAsShadowmap = false;
  45312. /**
  45313. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45314. */
  45315. _this.useAlphaFromAlbedoTexture = false;
  45316. /**
  45317. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45318. */
  45319. _this.forceAlphaTest = false;
  45320. /**
  45321. * Defines the alpha limits in alpha test mode.
  45322. */
  45323. _this.alphaCutOff = 0.4;
  45324. /**
  45325. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45326. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45327. */
  45328. _this.useSpecularOverAlpha = true;
  45329. /**
  45330. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45331. */
  45332. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45333. /**
  45334. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45335. */
  45336. _this.useRoughnessFromMetallicTextureAlpha = true;
  45337. /**
  45338. * Specifies if the metallic texture contains the roughness information in its green channel.
  45339. */
  45340. _this.useRoughnessFromMetallicTextureGreen = false;
  45341. /**
  45342. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45343. */
  45344. _this.useMetallnessFromMetallicTextureBlue = false;
  45345. /**
  45346. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45347. */
  45348. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45349. /**
  45350. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45351. */
  45352. _this.useAmbientInGrayScale = false;
  45353. /**
  45354. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45355. * The material will try to infer what glossiness each pixel should be.
  45356. */
  45357. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45358. /**
  45359. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45360. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45361. */
  45362. _this.useRadianceOverAlpha = true;
  45363. /**
  45364. * Allows using an object space normal map (instead of tangent space).
  45365. */
  45366. _this.useObjectSpaceNormalMap = false;
  45367. /**
  45368. * Allows using the bump map in parallax mode.
  45369. */
  45370. _this.useParallax = false;
  45371. /**
  45372. * Allows using the bump map in parallax occlusion mode.
  45373. */
  45374. _this.useParallaxOcclusion = false;
  45375. /**
  45376. * Controls the scale bias of the parallax mode.
  45377. */
  45378. _this.parallaxScaleBias = 0.05;
  45379. /**
  45380. * If sets to true, disables all the lights affecting the material.
  45381. */
  45382. _this.disableLighting = false;
  45383. /**
  45384. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45385. */
  45386. _this.forceIrradianceInFragment = false;
  45387. /**
  45388. * Number of Simultaneous lights allowed on the material.
  45389. */
  45390. _this.maxSimultaneousLights = 4;
  45391. /**
  45392. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45393. */
  45394. _this.invertNormalMapX = false;
  45395. /**
  45396. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45397. */
  45398. _this.invertNormalMapY = false;
  45399. /**
  45400. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45401. */
  45402. _this.twoSidedLighting = false;
  45403. /**
  45404. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45405. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45406. */
  45407. _this.useAlphaFresnel = false;
  45408. /**
  45409. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45410. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45411. */
  45412. _this.useLinearAlphaFresnel = false;
  45413. /**
  45414. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45415. * And/Or occlude the blended part.
  45416. */
  45417. _this.environmentBRDFTexture = null;
  45418. /**
  45419. * Force normal to face away from face.
  45420. */
  45421. _this.forceNormalForward = false;
  45422. /**
  45423. * Enables specular anti aliasing in the PBR shader.
  45424. * It will both interacts on the Geometry for analytical and IBL lighting.
  45425. * It also prefilter the roughness map based on the bump values.
  45426. */
  45427. _this.enableSpecularAntiAliasing = false;
  45428. /**
  45429. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45430. * makes the reflect vector face the model (under horizon).
  45431. */
  45432. _this.useHorizonOcclusion = true;
  45433. /**
  45434. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45435. * too much the area relying on ambient texture to define their ambient occlusion.
  45436. */
  45437. _this.useRadianceOcclusion = true;
  45438. /**
  45439. * If set to true, no lighting calculations will be applied.
  45440. */
  45441. _this.unlit = false;
  45442. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45443. return _this;
  45444. }
  45445. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45446. /**
  45447. * BJS is using an harcoded light falloff based on a manually sets up range.
  45448. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45449. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45450. */
  45451. get: function () {
  45452. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45453. },
  45454. /**
  45455. * BJS is using an harcoded light falloff based on a manually sets up range.
  45456. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45457. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45458. */
  45459. set: function (value) {
  45460. if (value !== this.usePhysicalLightFalloff) {
  45461. // Ensure the effect will be rebuilt.
  45462. this._markAllSubMeshesAsTexturesDirty();
  45463. if (value) {
  45464. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45465. }
  45466. else {
  45467. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45468. }
  45469. }
  45470. },
  45471. enumerable: true,
  45472. configurable: true
  45473. });
  45474. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45475. /**
  45476. * In order to support the falloff compatibility with gltf, a special mode has been added
  45477. * to reproduce the gltf light falloff.
  45478. */
  45479. get: function () {
  45480. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45481. },
  45482. /**
  45483. * In order to support the falloff compatibility with gltf, a special mode has been added
  45484. * to reproduce the gltf light falloff.
  45485. */
  45486. set: function (value) {
  45487. if (value !== this.useGLTFLightFalloff) {
  45488. // Ensure the effect will be rebuilt.
  45489. this._markAllSubMeshesAsTexturesDirty();
  45490. if (value) {
  45491. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45492. }
  45493. else {
  45494. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45495. }
  45496. }
  45497. },
  45498. enumerable: true,
  45499. configurable: true
  45500. });
  45501. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45502. /**
  45503. * Gets the image processing configuration used either in this material.
  45504. */
  45505. get: function () {
  45506. return this._imageProcessingConfiguration;
  45507. },
  45508. /**
  45509. * Sets the Default image processing configuration used either in the this material.
  45510. *
  45511. * If sets to null, the scene one is in use.
  45512. */
  45513. set: function (value) {
  45514. this._attachImageProcessingConfiguration(value);
  45515. // Ensure the effect will be rebuilt.
  45516. this._markAllSubMeshesAsTexturesDirty();
  45517. },
  45518. enumerable: true,
  45519. configurable: true
  45520. });
  45521. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45522. /**
  45523. * Gets wether the color curves effect is enabled.
  45524. */
  45525. get: function () {
  45526. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45527. },
  45528. /**
  45529. * Sets wether the color curves effect is enabled.
  45530. */
  45531. set: function (value) {
  45532. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45533. },
  45534. enumerable: true,
  45535. configurable: true
  45536. });
  45537. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45538. /**
  45539. * Gets wether the color grading effect is enabled.
  45540. */
  45541. get: function () {
  45542. return this.imageProcessingConfiguration.colorGradingEnabled;
  45543. },
  45544. /**
  45545. * Gets wether the color grading effect is enabled.
  45546. */
  45547. set: function (value) {
  45548. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45549. },
  45550. enumerable: true,
  45551. configurable: true
  45552. });
  45553. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45554. /**
  45555. * Gets wether tonemapping is enabled or not.
  45556. */
  45557. get: function () {
  45558. return this._imageProcessingConfiguration.toneMappingEnabled;
  45559. },
  45560. /**
  45561. * Sets wether tonemapping is enabled or not
  45562. */
  45563. set: function (value) {
  45564. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45565. },
  45566. enumerable: true,
  45567. configurable: true
  45568. });
  45569. ;
  45570. ;
  45571. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45572. /**
  45573. * The camera exposure used on this material.
  45574. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45575. * This corresponds to a photographic exposure.
  45576. */
  45577. get: function () {
  45578. return this._imageProcessingConfiguration.exposure;
  45579. },
  45580. /**
  45581. * The camera exposure used on this material.
  45582. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45583. * This corresponds to a photographic exposure.
  45584. */
  45585. set: function (value) {
  45586. this._imageProcessingConfiguration.exposure = value;
  45587. },
  45588. enumerable: true,
  45589. configurable: true
  45590. });
  45591. ;
  45592. ;
  45593. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45594. /**
  45595. * Gets The camera contrast used on this material.
  45596. */
  45597. get: function () {
  45598. return this._imageProcessingConfiguration.contrast;
  45599. },
  45600. /**
  45601. * Sets The camera contrast used on this material.
  45602. */
  45603. set: function (value) {
  45604. this._imageProcessingConfiguration.contrast = value;
  45605. },
  45606. enumerable: true,
  45607. configurable: true
  45608. });
  45609. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45610. /**
  45611. * Gets the Color Grading 2D Lookup Texture.
  45612. */
  45613. get: function () {
  45614. return this._imageProcessingConfiguration.colorGradingTexture;
  45615. },
  45616. /**
  45617. * Sets the Color Grading 2D Lookup Texture.
  45618. */
  45619. set: function (value) {
  45620. this._imageProcessingConfiguration.colorGradingTexture = value;
  45621. },
  45622. enumerable: true,
  45623. configurable: true
  45624. });
  45625. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45626. /**
  45627. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45628. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45629. * 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;
  45630. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45631. */
  45632. get: function () {
  45633. return this._imageProcessingConfiguration.colorCurves;
  45634. },
  45635. /**
  45636. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45637. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45638. * 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;
  45639. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45640. */
  45641. set: function (value) {
  45642. this._imageProcessingConfiguration.colorCurves = value;
  45643. },
  45644. enumerable: true,
  45645. configurable: true
  45646. });
  45647. /**
  45648. * Returns the name of this material class.
  45649. */
  45650. PBRMaterial.prototype.getClassName = function () {
  45651. return "PBRMaterial";
  45652. };
  45653. /**
  45654. * Returns an array of the actively used textures.
  45655. * @returns - Array of BaseTextures
  45656. */
  45657. PBRMaterial.prototype.getActiveTextures = function () {
  45658. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45659. if (this._albedoTexture) {
  45660. activeTextures.push(this._albedoTexture);
  45661. }
  45662. if (this._ambientTexture) {
  45663. activeTextures.push(this._ambientTexture);
  45664. }
  45665. if (this._opacityTexture) {
  45666. activeTextures.push(this._opacityTexture);
  45667. }
  45668. if (this._reflectionTexture) {
  45669. activeTextures.push(this._reflectionTexture);
  45670. }
  45671. if (this._emissiveTexture) {
  45672. activeTextures.push(this._emissiveTexture);
  45673. }
  45674. if (this._reflectivityTexture) {
  45675. activeTextures.push(this._reflectivityTexture);
  45676. }
  45677. if (this._metallicTexture) {
  45678. activeTextures.push(this._metallicTexture);
  45679. }
  45680. if (this._microSurfaceTexture) {
  45681. activeTextures.push(this._microSurfaceTexture);
  45682. }
  45683. if (this._bumpTexture) {
  45684. activeTextures.push(this._bumpTexture);
  45685. }
  45686. if (this._lightmapTexture) {
  45687. activeTextures.push(this._lightmapTexture);
  45688. }
  45689. if (this._refractionTexture) {
  45690. activeTextures.push(this._refractionTexture);
  45691. }
  45692. return activeTextures;
  45693. };
  45694. /**
  45695. * Checks to see if a texture is used in the material.
  45696. * @param texture - Base texture to use.
  45697. * @returns - Boolean specifying if a texture is used in the material.
  45698. */
  45699. PBRMaterial.prototype.hasTexture = function (texture) {
  45700. if (_super.prototype.hasTexture.call(this, texture)) {
  45701. return true;
  45702. }
  45703. if (this._albedoTexture === texture) {
  45704. return true;
  45705. }
  45706. if (this._ambientTexture === texture) {
  45707. return true;
  45708. }
  45709. if (this._opacityTexture === texture) {
  45710. return true;
  45711. }
  45712. if (this._reflectionTexture === texture) {
  45713. return true;
  45714. }
  45715. if (this._reflectivityTexture === texture) {
  45716. return true;
  45717. }
  45718. if (this._metallicTexture === texture) {
  45719. return true;
  45720. }
  45721. if (this._microSurfaceTexture === texture) {
  45722. return true;
  45723. }
  45724. if (this._bumpTexture === texture) {
  45725. return true;
  45726. }
  45727. if (this._lightmapTexture === texture) {
  45728. return true;
  45729. }
  45730. if (this._refractionTexture === texture) {
  45731. return true;
  45732. }
  45733. return false;
  45734. };
  45735. /**
  45736. * Makes a duplicate of the current material.
  45737. * @param name - name to use for the new material.
  45738. */
  45739. PBRMaterial.prototype.clone = function (name) {
  45740. var _this = this;
  45741. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45742. clone.id = name;
  45743. clone.name = name;
  45744. return clone;
  45745. };
  45746. /**
  45747. * Serializes this PBR Material.
  45748. * @returns - An object with the serialized material.
  45749. */
  45750. PBRMaterial.prototype.serialize = function () {
  45751. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45752. serializationObject.customType = "BABYLON.PBRMaterial";
  45753. return serializationObject;
  45754. };
  45755. // Statics
  45756. /**
  45757. * Parses a PBR Material from a serialized object.
  45758. * @param source - Serialized object.
  45759. * @param scene - BJS scene instance.
  45760. * @param rootUrl - url for the scene object
  45761. * @returns - PBRMaterial
  45762. */
  45763. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45764. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45765. };
  45766. /**
  45767. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45768. */
  45769. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45770. /**
  45771. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45772. */
  45773. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45774. /**
  45775. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45776. */
  45777. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45778. /**
  45779. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45780. * They are also discarded below the alpha cutoff threshold to improve performances.
  45781. */
  45782. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45783. /**
  45784. * Defines the default value of how much AO map is occluding the analytical lights
  45785. * (point spot...).
  45786. */
  45787. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45788. __decorate([
  45789. BABYLON.serialize(),
  45790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45791. ], PBRMaterial.prototype, "directIntensity", void 0);
  45792. __decorate([
  45793. BABYLON.serialize(),
  45794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45795. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45796. __decorate([
  45797. BABYLON.serialize(),
  45798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45799. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45800. __decorate([
  45801. BABYLON.serialize(),
  45802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45803. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45804. __decorate([
  45805. BABYLON.serialize(),
  45806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45807. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45808. __decorate([
  45809. BABYLON.serializeAsTexture(),
  45810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45811. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45812. __decorate([
  45813. BABYLON.serializeAsTexture(),
  45814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45815. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45816. __decorate([
  45817. BABYLON.serialize(),
  45818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45819. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45820. __decorate([
  45821. BABYLON.serialize(),
  45822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45823. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45824. __decorate([
  45825. BABYLON.serializeAsTexture(),
  45826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45827. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45828. __decorate([
  45829. BABYLON.serializeAsTexture(),
  45830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45831. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45832. __decorate([
  45833. BABYLON.serializeAsTexture(),
  45834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45835. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45836. __decorate([
  45837. BABYLON.serializeAsTexture(),
  45838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45839. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45840. __decorate([
  45841. BABYLON.serializeAsTexture(),
  45842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45843. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45844. __decorate([
  45845. BABYLON.serialize(),
  45846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45847. ], PBRMaterial.prototype, "metallic", void 0);
  45848. __decorate([
  45849. BABYLON.serialize(),
  45850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45851. ], PBRMaterial.prototype, "roughness", void 0);
  45852. __decorate([
  45853. BABYLON.serializeAsTexture(),
  45854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45855. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45856. __decorate([
  45857. BABYLON.serializeAsTexture(),
  45858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45859. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45860. __decorate([
  45861. BABYLON.serializeAsTexture(),
  45862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45863. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45864. __decorate([
  45865. BABYLON.serializeAsTexture(),
  45866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45867. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45868. __decorate([
  45869. BABYLON.serializeAsColor3("ambient"),
  45870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45871. ], PBRMaterial.prototype, "ambientColor", void 0);
  45872. __decorate([
  45873. BABYLON.serializeAsColor3("albedo"),
  45874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45875. ], PBRMaterial.prototype, "albedoColor", void 0);
  45876. __decorate([
  45877. BABYLON.serializeAsColor3("reflectivity"),
  45878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45879. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45880. __decorate([
  45881. BABYLON.serializeAsColor3("reflection"),
  45882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45883. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45884. __decorate([
  45885. BABYLON.serializeAsColor3("emissive"),
  45886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45887. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45888. __decorate([
  45889. BABYLON.serialize(),
  45890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45891. ], PBRMaterial.prototype, "microSurface", void 0);
  45892. __decorate([
  45893. BABYLON.serialize(),
  45894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45895. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45896. __decorate([
  45897. BABYLON.serialize(),
  45898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45899. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45900. __decorate([
  45901. BABYLON.serialize(),
  45902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45903. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45904. __decorate([
  45905. BABYLON.serialize(),
  45906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45907. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45908. __decorate([
  45909. BABYLON.serialize(),
  45910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45911. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45912. __decorate([
  45913. BABYLON.serialize(),
  45914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45915. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45916. __decorate([
  45917. BABYLON.serialize(),
  45918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45919. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45920. __decorate([
  45921. BABYLON.serialize(),
  45922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45923. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45924. __decorate([
  45925. BABYLON.serialize(),
  45926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45927. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45928. __decorate([
  45929. BABYLON.serialize(),
  45930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45931. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45932. __decorate([
  45933. BABYLON.serialize(),
  45934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45935. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45936. __decorate([
  45937. BABYLON.serialize(),
  45938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45939. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45940. __decorate([
  45941. BABYLON.serialize(),
  45942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45943. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45944. __decorate([
  45945. BABYLON.serialize(),
  45946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45947. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45948. __decorate([
  45949. BABYLON.serialize(),
  45950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45951. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45952. __decorate([
  45953. BABYLON.serialize()
  45954. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45955. __decorate([
  45956. BABYLON.serialize()
  45957. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45958. __decorate([
  45959. BABYLON.serialize(),
  45960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45961. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45962. __decorate([
  45963. BABYLON.serialize(),
  45964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45965. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45966. __decorate([
  45967. BABYLON.serialize(),
  45968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45969. ], PBRMaterial.prototype, "useParallax", void 0);
  45970. __decorate([
  45971. BABYLON.serialize(),
  45972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45973. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45974. __decorate([
  45975. BABYLON.serialize(),
  45976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45977. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45978. __decorate([
  45979. BABYLON.serialize(),
  45980. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45981. ], PBRMaterial.prototype, "disableLighting", void 0);
  45982. __decorate([
  45983. BABYLON.serialize(),
  45984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45985. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45986. __decorate([
  45987. BABYLON.serialize(),
  45988. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45989. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45990. __decorate([
  45991. BABYLON.serialize(),
  45992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45993. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45994. __decorate([
  45995. BABYLON.serialize(),
  45996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45997. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45998. __decorate([
  45999. BABYLON.serialize(),
  46000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46001. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46002. __decorate([
  46003. BABYLON.serialize(),
  46004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46005. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46006. __decorate([
  46007. BABYLON.serialize(),
  46008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46009. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46010. __decorate([
  46011. BABYLON.serializeAsTexture(),
  46012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46013. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46014. __decorate([
  46015. BABYLON.serialize(),
  46016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46017. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46018. __decorate([
  46019. BABYLON.serialize(),
  46020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46021. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46022. __decorate([
  46023. BABYLON.serialize(),
  46024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46025. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46026. __decorate([
  46027. BABYLON.serialize(),
  46028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46029. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46030. __decorate([
  46031. BABYLON.serialize(),
  46032. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46033. ], PBRMaterial.prototype, "unlit", void 0);
  46034. return PBRMaterial;
  46035. }(BABYLON.PBRBaseMaterial));
  46036. BABYLON.PBRMaterial = PBRMaterial;
  46037. })(BABYLON || (BABYLON = {}));
  46038. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46039. var BABYLON;
  46040. (function (BABYLON) {
  46041. /**
  46042. * The PBR material of BJS following the metal roughness convention.
  46043. *
  46044. * This fits to the PBR convention in the GLTF definition:
  46045. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46046. */
  46047. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46048. __extends(PBRMetallicRoughnessMaterial, _super);
  46049. /**
  46050. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46051. *
  46052. * @param name The material name
  46053. * @param scene The scene the material will be use in.
  46054. */
  46055. function PBRMetallicRoughnessMaterial(name, scene) {
  46056. var _this = _super.call(this, name, scene) || this;
  46057. _this._useRoughnessFromMetallicTextureAlpha = false;
  46058. _this._useRoughnessFromMetallicTextureGreen = true;
  46059. _this._useMetallnessFromMetallicTextureBlue = true;
  46060. _this.metallic = 1.0;
  46061. _this.roughness = 1.0;
  46062. return _this;
  46063. }
  46064. /**
  46065. * Return the currrent class name of the material.
  46066. */
  46067. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46068. return "PBRMetallicRoughnessMaterial";
  46069. };
  46070. /**
  46071. * Return the active textures of the material.
  46072. */
  46073. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46074. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46075. if (this.baseTexture) {
  46076. activeTextures.push(this.baseTexture);
  46077. }
  46078. if (this.metallicRoughnessTexture) {
  46079. activeTextures.push(this.metallicRoughnessTexture);
  46080. }
  46081. return activeTextures;
  46082. };
  46083. /**
  46084. * Checks to see if a texture is used in the material.
  46085. * @param texture - Base texture to use.
  46086. * @returns - Boolean specifying if a texture is used in the material.
  46087. */
  46088. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46089. if (_super.prototype.hasTexture.call(this, texture)) {
  46090. return true;
  46091. }
  46092. if (this.baseTexture === texture) {
  46093. return true;
  46094. }
  46095. if (this.metallicRoughnessTexture === texture) {
  46096. return true;
  46097. }
  46098. return false;
  46099. };
  46100. /**
  46101. * Makes a duplicate of the current material.
  46102. * @param name - name to use for the new material.
  46103. */
  46104. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46105. var _this = this;
  46106. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46107. clone.id = name;
  46108. clone.name = name;
  46109. return clone;
  46110. };
  46111. /**
  46112. * Serialize the material to a parsable JSON object.
  46113. */
  46114. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46115. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46116. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46117. return serializationObject;
  46118. };
  46119. /**
  46120. * Parses a JSON object correponding to the serialize function.
  46121. */
  46122. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46123. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46124. };
  46125. __decorate([
  46126. BABYLON.serializeAsColor3(),
  46127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46128. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46129. __decorate([
  46130. BABYLON.serializeAsTexture(),
  46131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46132. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46133. __decorate([
  46134. BABYLON.serialize(),
  46135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46136. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46137. __decorate([
  46138. BABYLON.serialize(),
  46139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46140. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46141. __decorate([
  46142. BABYLON.serializeAsTexture(),
  46143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46144. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46145. return PBRMetallicRoughnessMaterial;
  46146. }(BABYLON.PBRBaseSimpleMaterial));
  46147. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46148. })(BABYLON || (BABYLON = {}));
  46149. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46150. var BABYLON;
  46151. (function (BABYLON) {
  46152. /**
  46153. * The PBR material of BJS following the specular glossiness convention.
  46154. *
  46155. * This fits to the PBR convention in the GLTF definition:
  46156. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46157. */
  46158. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46159. __extends(PBRSpecularGlossinessMaterial, _super);
  46160. /**
  46161. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46162. *
  46163. * @param name The material name
  46164. * @param scene The scene the material will be use in.
  46165. */
  46166. function PBRSpecularGlossinessMaterial(name, scene) {
  46167. var _this = _super.call(this, name, scene) || this;
  46168. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46169. return _this;
  46170. }
  46171. /**
  46172. * Return the currrent class name of the material.
  46173. */
  46174. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46175. return "PBRSpecularGlossinessMaterial";
  46176. };
  46177. /**
  46178. * Return the active textures of the material.
  46179. */
  46180. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46181. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46182. if (this.diffuseTexture) {
  46183. activeTextures.push(this.diffuseTexture);
  46184. }
  46185. if (this.specularGlossinessTexture) {
  46186. activeTextures.push(this.specularGlossinessTexture);
  46187. }
  46188. return activeTextures;
  46189. };
  46190. /**
  46191. * Checks to see if a texture is used in the material.
  46192. * @param texture - Base texture to use.
  46193. * @returns - Boolean specifying if a texture is used in the material.
  46194. */
  46195. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46196. if (_super.prototype.hasTexture.call(this, texture)) {
  46197. return true;
  46198. }
  46199. if (this.diffuseTexture === texture) {
  46200. return true;
  46201. }
  46202. if (this.specularGlossinessTexture === texture) {
  46203. return true;
  46204. }
  46205. return false;
  46206. };
  46207. /**
  46208. * Makes a duplicate of the current material.
  46209. * @param name - name to use for the new material.
  46210. */
  46211. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46212. var _this = this;
  46213. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46214. clone.id = name;
  46215. clone.name = name;
  46216. return clone;
  46217. };
  46218. /**
  46219. * Serialize the material to a parsable JSON object.
  46220. */
  46221. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46222. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46223. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46224. return serializationObject;
  46225. };
  46226. /**
  46227. * Parses a JSON object correponding to the serialize function.
  46228. */
  46229. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46230. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46231. };
  46232. __decorate([
  46233. BABYLON.serializeAsColor3("diffuse"),
  46234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46235. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46236. __decorate([
  46237. BABYLON.serializeAsTexture(),
  46238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46239. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46240. __decorate([
  46241. BABYLON.serializeAsColor3("specular"),
  46242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46243. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46244. __decorate([
  46245. BABYLON.serialize(),
  46246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46247. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46248. __decorate([
  46249. BABYLON.serializeAsTexture(),
  46250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46251. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46252. return PBRSpecularGlossinessMaterial;
  46253. }(BABYLON.PBRBaseSimpleMaterial));
  46254. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46255. })(BABYLON || (BABYLON = {}));
  46256. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46257. var BABYLON;
  46258. (function (BABYLON) {
  46259. BABYLON.CameraInputTypes = {};
  46260. var CameraInputsManager = /** @class */ (function () {
  46261. function CameraInputsManager(camera) {
  46262. this.attached = {};
  46263. this.camera = camera;
  46264. this.checkInputs = function () { };
  46265. }
  46266. /**
  46267. * Add an input method to a camera
  46268. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46269. * @param input camera input method
  46270. */
  46271. CameraInputsManager.prototype.add = function (input) {
  46272. var type = input.getSimpleName();
  46273. if (this.attached[type]) {
  46274. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46275. return;
  46276. }
  46277. this.attached[type] = input;
  46278. input.camera = this.camera;
  46279. //for checkInputs, we are dynamically creating a function
  46280. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46281. if (input.checkInputs) {
  46282. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46283. }
  46284. if (this.attachedElement) {
  46285. input.attachControl(this.attachedElement);
  46286. }
  46287. };
  46288. /**
  46289. * Remove a specific input method from a camera
  46290. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46291. * @param inputToRemove camera input method
  46292. */
  46293. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46294. for (var cam in this.attached) {
  46295. var input = this.attached[cam];
  46296. if (input === inputToRemove) {
  46297. input.detachControl(this.attachedElement);
  46298. input.camera = null;
  46299. delete this.attached[cam];
  46300. this.rebuildInputCheck();
  46301. }
  46302. }
  46303. };
  46304. CameraInputsManager.prototype.removeByType = function (inputType) {
  46305. for (var cam in this.attached) {
  46306. var input = this.attached[cam];
  46307. if (input.getClassName() === inputType) {
  46308. input.detachControl(this.attachedElement);
  46309. input.camera = null;
  46310. delete this.attached[cam];
  46311. this.rebuildInputCheck();
  46312. }
  46313. }
  46314. };
  46315. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46316. var current = this.checkInputs;
  46317. return function () {
  46318. current();
  46319. fn();
  46320. };
  46321. };
  46322. CameraInputsManager.prototype.attachInput = function (input) {
  46323. if (this.attachedElement) {
  46324. input.attachControl(this.attachedElement, this.noPreventDefault);
  46325. }
  46326. };
  46327. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46328. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46329. if (this.attachedElement) {
  46330. return;
  46331. }
  46332. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46333. this.attachedElement = element;
  46334. this.noPreventDefault = noPreventDefault;
  46335. for (var cam in this.attached) {
  46336. this.attached[cam].attachControl(element, noPreventDefault);
  46337. }
  46338. };
  46339. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46340. if (disconnect === void 0) { disconnect = false; }
  46341. if (this.attachedElement !== element) {
  46342. return;
  46343. }
  46344. for (var cam in this.attached) {
  46345. this.attached[cam].detachControl(element);
  46346. if (disconnect) {
  46347. this.attached[cam].camera = null;
  46348. }
  46349. }
  46350. this.attachedElement = null;
  46351. };
  46352. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46353. this.checkInputs = function () { };
  46354. for (var cam in this.attached) {
  46355. var input = this.attached[cam];
  46356. if (input.checkInputs) {
  46357. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46358. }
  46359. }
  46360. };
  46361. /**
  46362. * Remove all attached input methods from a camera
  46363. */
  46364. CameraInputsManager.prototype.clear = function () {
  46365. if (this.attachedElement) {
  46366. this.detachElement(this.attachedElement, true);
  46367. }
  46368. this.attached = {};
  46369. this.attachedElement = null;
  46370. this.checkInputs = function () { };
  46371. };
  46372. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46373. var inputs = {};
  46374. for (var cam in this.attached) {
  46375. var input = this.attached[cam];
  46376. var res = BABYLON.SerializationHelper.Serialize(input);
  46377. inputs[input.getClassName()] = res;
  46378. }
  46379. serializedCamera.inputsmgr = inputs;
  46380. };
  46381. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46382. var parsedInputs = parsedCamera.inputsmgr;
  46383. if (parsedInputs) {
  46384. this.clear();
  46385. for (var n in parsedInputs) {
  46386. var construct = BABYLON.CameraInputTypes[n];
  46387. if (construct) {
  46388. var parsedinput = parsedInputs[n];
  46389. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46390. this.add(input);
  46391. }
  46392. }
  46393. }
  46394. else {
  46395. //2016-03-08 this part is for managing backward compatibility
  46396. for (var n in this.attached) {
  46397. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46398. if (construct) {
  46399. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46400. this.remove(this.attached[n]);
  46401. this.add(input);
  46402. }
  46403. }
  46404. }
  46405. };
  46406. return CameraInputsManager;
  46407. }());
  46408. BABYLON.CameraInputsManager = CameraInputsManager;
  46409. })(BABYLON || (BABYLON = {}));
  46410. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46411. var BABYLON;
  46412. (function (BABYLON) {
  46413. var TargetCamera = /** @class */ (function (_super) {
  46414. __extends(TargetCamera, _super);
  46415. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46416. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46417. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46418. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46419. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46420. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46421. _this.speed = 2.0;
  46422. _this.noRotationConstraint = false;
  46423. _this.lockedTarget = null;
  46424. /** @hidden */
  46425. _this._currentTarget = BABYLON.Vector3.Zero();
  46426. /** @hidden */
  46427. _this._viewMatrix = BABYLON.Matrix.Zero();
  46428. /** @hidden */
  46429. _this._camMatrix = BABYLON.Matrix.Zero();
  46430. /** @hidden */
  46431. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46432. /** @hidden */
  46433. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46434. /** @hidden */
  46435. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46436. /** @hidden */
  46437. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46438. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46439. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46440. _this._defaultUp = BABYLON.Vector3.Up();
  46441. _this._cachedRotationZ = 0;
  46442. return _this;
  46443. }
  46444. TargetCamera.prototype.getFrontPosition = function (distance) {
  46445. this.getWorldMatrix();
  46446. var direction = this.getTarget().subtract(this.position);
  46447. direction.normalize();
  46448. direction.scaleInPlace(distance);
  46449. return this.globalPosition.add(direction);
  46450. };
  46451. /** @hidden */
  46452. TargetCamera.prototype._getLockedTargetPosition = function () {
  46453. if (!this.lockedTarget) {
  46454. return null;
  46455. }
  46456. if (this.lockedTarget.absolutePosition) {
  46457. this.lockedTarget.computeWorldMatrix();
  46458. }
  46459. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46460. };
  46461. TargetCamera.prototype.storeState = function () {
  46462. this._storedPosition = this.position.clone();
  46463. this._storedRotation = this.rotation.clone();
  46464. if (this.rotationQuaternion) {
  46465. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46466. }
  46467. return _super.prototype.storeState.call(this);
  46468. };
  46469. /**
  46470. * Restored camera state. You must call storeState() first
  46471. * @returns whether it was successful or not
  46472. * @hidden
  46473. */
  46474. TargetCamera.prototype._restoreStateValues = function () {
  46475. if (!_super.prototype._restoreStateValues.call(this)) {
  46476. return false;
  46477. }
  46478. this.position = this._storedPosition.clone();
  46479. this.rotation = this._storedRotation.clone();
  46480. if (this.rotationQuaternion) {
  46481. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46482. }
  46483. this.cameraDirection.copyFromFloats(0, 0, 0);
  46484. this.cameraRotation.copyFromFloats(0, 0);
  46485. return true;
  46486. };
  46487. // Cache
  46488. /** @hidden */
  46489. TargetCamera.prototype._initCache = function () {
  46490. _super.prototype._initCache.call(this);
  46491. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46492. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46493. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46494. };
  46495. /** @hidden */
  46496. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46497. if (!ignoreParentClass) {
  46498. _super.prototype._updateCache.call(this);
  46499. }
  46500. var lockedTargetPosition = this._getLockedTargetPosition();
  46501. if (!lockedTargetPosition) {
  46502. this._cache.lockedTarget = null;
  46503. }
  46504. else {
  46505. if (!this._cache.lockedTarget) {
  46506. this._cache.lockedTarget = lockedTargetPosition.clone();
  46507. }
  46508. else {
  46509. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46510. }
  46511. }
  46512. this._cache.rotation.copyFrom(this.rotation);
  46513. if (this.rotationQuaternion)
  46514. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46515. };
  46516. // Synchronized
  46517. /** @hidden */
  46518. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46519. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46520. return false;
  46521. }
  46522. var lockedTargetPosition = this._getLockedTargetPosition();
  46523. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46524. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46525. };
  46526. // Methods
  46527. /** @hidden */
  46528. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46529. var engine = this.getEngine();
  46530. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46531. };
  46532. // Target
  46533. /** @hidden */
  46534. TargetCamera.prototype.setTarget = function (target) {
  46535. this.upVector.normalize();
  46536. if (this.position.z === target.z) {
  46537. this.position.z += BABYLON.Epsilon;
  46538. }
  46539. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46540. this._camMatrix.invert();
  46541. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46542. var vDir = target.subtract(this.position);
  46543. if (vDir.x >= 0.0) {
  46544. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46545. }
  46546. else {
  46547. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46548. }
  46549. this.rotation.z = 0;
  46550. if (isNaN(this.rotation.x)) {
  46551. this.rotation.x = 0;
  46552. }
  46553. if (isNaN(this.rotation.y)) {
  46554. this.rotation.y = 0;
  46555. }
  46556. if (isNaN(this.rotation.z)) {
  46557. this.rotation.z = 0;
  46558. }
  46559. if (this.rotationQuaternion) {
  46560. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46561. }
  46562. };
  46563. /**
  46564. * Return the current target position of the camera. This value is expressed in local space.
  46565. */
  46566. TargetCamera.prototype.getTarget = function () {
  46567. return this._currentTarget;
  46568. };
  46569. /** @hidden */
  46570. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46571. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46572. };
  46573. /** @hidden */
  46574. TargetCamera.prototype._updatePosition = function () {
  46575. if (this.parent) {
  46576. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46577. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46578. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46579. return;
  46580. }
  46581. this.position.addInPlace(this.cameraDirection);
  46582. };
  46583. /** @hidden */
  46584. TargetCamera.prototype._checkInputs = function () {
  46585. var needToMove = this._decideIfNeedsToMove();
  46586. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46587. // Move
  46588. if (needToMove) {
  46589. this._updatePosition();
  46590. }
  46591. // Rotate
  46592. if (needToRotate) {
  46593. this.rotation.x += this.cameraRotation.x;
  46594. this.rotation.y += this.cameraRotation.y;
  46595. //rotate, if quaternion is set and rotation was used
  46596. if (this.rotationQuaternion) {
  46597. var len = this.rotation.lengthSquared();
  46598. if (len) {
  46599. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46600. }
  46601. }
  46602. if (!this.noRotationConstraint) {
  46603. var limit = (Math.PI / 2) * 0.95;
  46604. if (this.rotation.x > limit)
  46605. this.rotation.x = limit;
  46606. if (this.rotation.x < -limit)
  46607. this.rotation.x = -limit;
  46608. }
  46609. }
  46610. // Inertia
  46611. if (needToMove) {
  46612. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46613. this.cameraDirection.x = 0;
  46614. }
  46615. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46616. this.cameraDirection.y = 0;
  46617. }
  46618. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46619. this.cameraDirection.z = 0;
  46620. }
  46621. this.cameraDirection.scaleInPlace(this.inertia);
  46622. }
  46623. if (needToRotate) {
  46624. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46625. this.cameraRotation.x = 0;
  46626. }
  46627. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46628. this.cameraRotation.y = 0;
  46629. }
  46630. this.cameraRotation.scaleInPlace(this.inertia);
  46631. }
  46632. _super.prototype._checkInputs.call(this);
  46633. };
  46634. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46635. if (this.rotationQuaternion) {
  46636. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46637. }
  46638. else {
  46639. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46640. }
  46641. };
  46642. /**
  46643. * 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)
  46644. * @returns the current camera
  46645. */
  46646. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46647. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46648. return this;
  46649. };
  46650. /** @hidden */
  46651. TargetCamera.prototype._getViewMatrix = function () {
  46652. if (this.lockedTarget) {
  46653. this.setTarget(this._getLockedTargetPosition());
  46654. }
  46655. // Compute
  46656. this._updateCameraRotationMatrix();
  46657. // Apply the changed rotation to the upVector.
  46658. if (this._cachedRotationZ != this.rotation.z) {
  46659. this._rotateUpVectorWithCameraRotationMatrix();
  46660. this._cachedRotationZ = this.rotation.z;
  46661. }
  46662. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46663. // Computing target and final matrix
  46664. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46665. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46666. return this._viewMatrix;
  46667. };
  46668. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46669. if (this.parent) {
  46670. var parentWorldMatrix = this.parent.getWorldMatrix();
  46671. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46672. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46673. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46674. this._markSyncedWithParent();
  46675. }
  46676. else {
  46677. this._globalPosition.copyFrom(position);
  46678. this._globalCurrentTarget.copyFrom(target);
  46679. this._globalCurrentUpVector.copyFrom(up);
  46680. }
  46681. if (this.getScene().useRightHandedSystem) {
  46682. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46683. }
  46684. else {
  46685. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46686. }
  46687. };
  46688. /**
  46689. * @override
  46690. * Override Camera.createRigCamera
  46691. */
  46692. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46693. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46694. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46695. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46696. if (!this.rotationQuaternion) {
  46697. this.rotationQuaternion = new BABYLON.Quaternion();
  46698. }
  46699. rigCamera._cameraRigParams = {};
  46700. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46701. }
  46702. return rigCamera;
  46703. }
  46704. return null;
  46705. };
  46706. /**
  46707. * @hidden
  46708. * @override
  46709. * Override Camera._updateRigCameras
  46710. */
  46711. TargetCamera.prototype._updateRigCameras = function () {
  46712. var camLeft = this._rigCameras[0];
  46713. var camRight = this._rigCameras[1];
  46714. switch (this.cameraRigMode) {
  46715. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46716. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46717. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46718. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46719. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46720. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46721. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46722. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46723. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46724. camLeft.setTarget(this.getTarget());
  46725. camRight.setTarget(this.getTarget());
  46726. break;
  46727. case BABYLON.Camera.RIG_MODE_VR:
  46728. if (camLeft.rotationQuaternion) {
  46729. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46730. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46731. }
  46732. else {
  46733. camLeft.rotation.copyFrom(this.rotation);
  46734. camRight.rotation.copyFrom(this.rotation);
  46735. }
  46736. camLeft.position.copyFrom(this.position);
  46737. camRight.position.copyFrom(this.position);
  46738. break;
  46739. }
  46740. _super.prototype._updateRigCameras.call(this);
  46741. };
  46742. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46743. if (!this._rigCamTransformMatrix) {
  46744. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46745. }
  46746. var target = this.getTarget();
  46747. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46748. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46749. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46750. };
  46751. TargetCamera.prototype.getClassName = function () {
  46752. return "TargetCamera";
  46753. };
  46754. __decorate([
  46755. BABYLON.serializeAsVector3()
  46756. ], TargetCamera.prototype, "rotation", void 0);
  46757. __decorate([
  46758. BABYLON.serialize()
  46759. ], TargetCamera.prototype, "speed", void 0);
  46760. __decorate([
  46761. BABYLON.serializeAsMeshReference("lockedTargetId")
  46762. ], TargetCamera.prototype, "lockedTarget", void 0);
  46763. return TargetCamera;
  46764. }(BABYLON.Camera));
  46765. BABYLON.TargetCamera = TargetCamera;
  46766. })(BABYLON || (BABYLON = {}));
  46767. //# sourceMappingURL=babylon.targetCamera.js.map
  46768. var BABYLON;
  46769. (function (BABYLON) {
  46770. var FreeCameraMouseInput = /** @class */ (function () {
  46771. function FreeCameraMouseInput(touchEnabled) {
  46772. if (touchEnabled === void 0) { touchEnabled = true; }
  46773. this.touchEnabled = touchEnabled;
  46774. this.buttons = [0, 1, 2];
  46775. this.angularSensibility = 2000.0;
  46776. this.previousPosition = null;
  46777. }
  46778. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46779. var _this = this;
  46780. var engine = this.camera.getEngine();
  46781. if (!this._pointerInput) {
  46782. this._pointerInput = function (p, s) {
  46783. var evt = p.event;
  46784. if (engine.isInVRExclusivePointerMode) {
  46785. return;
  46786. }
  46787. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46788. return;
  46789. }
  46790. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46791. return;
  46792. }
  46793. var srcElement = (evt.srcElement || evt.target);
  46794. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46795. try {
  46796. srcElement.setPointerCapture(evt.pointerId);
  46797. }
  46798. catch (e) {
  46799. //Nothing to do with the error. Execution will continue.
  46800. }
  46801. _this.previousPosition = {
  46802. x: evt.clientX,
  46803. y: evt.clientY
  46804. };
  46805. if (!noPreventDefault) {
  46806. evt.preventDefault();
  46807. element.focus();
  46808. }
  46809. }
  46810. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46811. try {
  46812. srcElement.releasePointerCapture(evt.pointerId);
  46813. }
  46814. catch (e) {
  46815. //Nothing to do with the error.
  46816. }
  46817. _this.previousPosition = null;
  46818. if (!noPreventDefault) {
  46819. evt.preventDefault();
  46820. }
  46821. }
  46822. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46823. if (!_this.previousPosition || engine.isPointerLock) {
  46824. return;
  46825. }
  46826. var offsetX = evt.clientX - _this.previousPosition.x;
  46827. if (_this.camera.getScene().useRightHandedSystem)
  46828. offsetX *= -1;
  46829. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46830. offsetX *= -1;
  46831. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46832. var offsetY = evt.clientY - _this.previousPosition.y;
  46833. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46834. _this.previousPosition = {
  46835. x: evt.clientX,
  46836. y: evt.clientY
  46837. };
  46838. if (!noPreventDefault) {
  46839. evt.preventDefault();
  46840. }
  46841. }
  46842. };
  46843. }
  46844. this._onMouseMove = function (evt) {
  46845. if (!engine.isPointerLock) {
  46846. return;
  46847. }
  46848. if (engine.isInVRExclusivePointerMode) {
  46849. return;
  46850. }
  46851. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46852. if (_this.camera.getScene().useRightHandedSystem)
  46853. offsetX *= -1;
  46854. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46855. offsetX *= -1;
  46856. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46857. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46858. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46859. _this.previousPosition = null;
  46860. if (!noPreventDefault) {
  46861. evt.preventDefault();
  46862. }
  46863. };
  46864. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46865. element.addEventListener("mousemove", this._onMouseMove, false);
  46866. };
  46867. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46868. if (this._observer && element) {
  46869. this.camera.getScene().onPointerObservable.remove(this._observer);
  46870. if (this._onMouseMove) {
  46871. element.removeEventListener("mousemove", this._onMouseMove);
  46872. }
  46873. this._observer = null;
  46874. this._onMouseMove = null;
  46875. this.previousPosition = null;
  46876. }
  46877. };
  46878. FreeCameraMouseInput.prototype.getClassName = function () {
  46879. return "FreeCameraMouseInput";
  46880. };
  46881. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46882. return "mouse";
  46883. };
  46884. __decorate([
  46885. BABYLON.serialize()
  46886. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46887. __decorate([
  46888. BABYLON.serialize()
  46889. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46890. return FreeCameraMouseInput;
  46891. }());
  46892. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46893. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46894. })(BABYLON || (BABYLON = {}));
  46895. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46896. var BABYLON;
  46897. (function (BABYLON) {
  46898. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46899. function FreeCameraKeyboardMoveInput() {
  46900. this._keys = new Array();
  46901. this.keysUp = [38];
  46902. this.keysDown = [40];
  46903. this.keysLeft = [37];
  46904. this.keysRight = [39];
  46905. }
  46906. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46907. var _this = this;
  46908. if (this._onCanvasBlurObserver) {
  46909. return;
  46910. }
  46911. this._scene = this.camera.getScene();
  46912. this._engine = this._scene.getEngine();
  46913. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46914. _this._keys = [];
  46915. });
  46916. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46917. var evt = info.event;
  46918. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46919. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46920. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46921. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46922. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46923. var index = _this._keys.indexOf(evt.keyCode);
  46924. if (index === -1) {
  46925. _this._keys.push(evt.keyCode);
  46926. }
  46927. if (!noPreventDefault) {
  46928. evt.preventDefault();
  46929. }
  46930. }
  46931. }
  46932. else {
  46933. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46934. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46935. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46936. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46937. var index = _this._keys.indexOf(evt.keyCode);
  46938. if (index >= 0) {
  46939. _this._keys.splice(index, 1);
  46940. }
  46941. if (!noPreventDefault) {
  46942. evt.preventDefault();
  46943. }
  46944. }
  46945. }
  46946. });
  46947. };
  46948. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46949. if (this._scene) {
  46950. if (this._onKeyboardObserver) {
  46951. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46952. }
  46953. if (this._onCanvasBlurObserver) {
  46954. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46955. }
  46956. this._onKeyboardObserver = null;
  46957. this._onCanvasBlurObserver = null;
  46958. }
  46959. this._keys = [];
  46960. };
  46961. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46962. if (this._onKeyboardObserver) {
  46963. var camera = this.camera;
  46964. // Keyboard
  46965. for (var index = 0; index < this._keys.length; index++) {
  46966. var keyCode = this._keys[index];
  46967. var speed = camera._computeLocalCameraSpeed();
  46968. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46969. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46970. }
  46971. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46972. camera._localDirection.copyFromFloats(0, 0, speed);
  46973. }
  46974. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46975. camera._localDirection.copyFromFloats(speed, 0, 0);
  46976. }
  46977. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46978. camera._localDirection.copyFromFloats(0, 0, -speed);
  46979. }
  46980. if (camera.getScene().useRightHandedSystem) {
  46981. camera._localDirection.z *= -1;
  46982. }
  46983. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46984. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46985. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46986. }
  46987. }
  46988. };
  46989. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46990. return "FreeCameraKeyboardMoveInput";
  46991. };
  46992. /** @hidden */
  46993. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46994. this._keys = [];
  46995. };
  46996. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46997. return "keyboard";
  46998. };
  46999. __decorate([
  47000. BABYLON.serialize()
  47001. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47002. __decorate([
  47003. BABYLON.serialize()
  47004. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47005. __decorate([
  47006. BABYLON.serialize()
  47007. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47008. __decorate([
  47009. BABYLON.serialize()
  47010. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47011. return FreeCameraKeyboardMoveInput;
  47012. }());
  47013. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47014. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47015. })(BABYLON || (BABYLON = {}));
  47016. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47017. var BABYLON;
  47018. (function (BABYLON) {
  47019. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47020. __extends(FreeCameraInputsManager, _super);
  47021. function FreeCameraInputsManager(camera) {
  47022. return _super.call(this, camera) || this;
  47023. }
  47024. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47025. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47026. return this;
  47027. };
  47028. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47029. if (touchEnabled === void 0) { touchEnabled = true; }
  47030. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47031. return this;
  47032. };
  47033. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47034. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47035. return this;
  47036. };
  47037. FreeCameraInputsManager.prototype.addTouch = function () {
  47038. this.add(new BABYLON.FreeCameraTouchInput());
  47039. return this;
  47040. };
  47041. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47042. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47043. return this;
  47044. };
  47045. return FreeCameraInputsManager;
  47046. }(BABYLON.CameraInputsManager));
  47047. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47048. })(BABYLON || (BABYLON = {}));
  47049. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47050. var BABYLON;
  47051. (function (BABYLON) {
  47052. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47053. // Forcing to use the Universal camera
  47054. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47055. });
  47056. var FreeCamera = /** @class */ (function (_super) {
  47057. __extends(FreeCamera, _super);
  47058. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47059. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47060. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47061. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47062. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47063. _this.checkCollisions = false;
  47064. _this.applyGravity = false;
  47065. _this._needMoveForGravity = false;
  47066. _this._oldPosition = BABYLON.Vector3.Zero();
  47067. _this._diffPosition = BABYLON.Vector3.Zero();
  47068. _this._newPosition = BABYLON.Vector3.Zero();
  47069. // Collisions
  47070. _this._collisionMask = -1;
  47071. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47072. if (collidedMesh === void 0) { collidedMesh = null; }
  47073. //TODO move this to the collision coordinator!
  47074. if (_this.getScene().workerCollisions)
  47075. newPosition.multiplyInPlace(_this._collider._radius);
  47076. var updatePosition = function (newPos) {
  47077. _this._newPosition.copyFrom(newPos);
  47078. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47079. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47080. _this.position.addInPlace(_this._diffPosition);
  47081. if (_this.onCollide && collidedMesh) {
  47082. _this.onCollide(collidedMesh);
  47083. }
  47084. }
  47085. };
  47086. updatePosition(newPosition);
  47087. };
  47088. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47089. _this.inputs.addKeyboard().addMouse();
  47090. return _this;
  47091. }
  47092. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47093. //-- begin properties for backward compatibility for inputs
  47094. /**
  47095. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47096. * Higher values reduce sensitivity.
  47097. */
  47098. get: function () {
  47099. var mouse = this.inputs.attached["mouse"];
  47100. if (mouse)
  47101. return mouse.angularSensibility;
  47102. return 0;
  47103. },
  47104. /**
  47105. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47106. * Higher values reduce sensitivity.
  47107. */
  47108. set: function (value) {
  47109. var mouse = this.inputs.attached["mouse"];
  47110. if (mouse)
  47111. mouse.angularSensibility = value;
  47112. },
  47113. enumerable: true,
  47114. configurable: true
  47115. });
  47116. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47117. get: function () {
  47118. var keyboard = this.inputs.attached["keyboard"];
  47119. if (keyboard)
  47120. return keyboard.keysUp;
  47121. return [];
  47122. },
  47123. set: function (value) {
  47124. var keyboard = this.inputs.attached["keyboard"];
  47125. if (keyboard)
  47126. keyboard.keysUp = value;
  47127. },
  47128. enumerable: true,
  47129. configurable: true
  47130. });
  47131. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47132. get: function () {
  47133. var keyboard = this.inputs.attached["keyboard"];
  47134. if (keyboard)
  47135. return keyboard.keysDown;
  47136. return [];
  47137. },
  47138. set: function (value) {
  47139. var keyboard = this.inputs.attached["keyboard"];
  47140. if (keyboard)
  47141. keyboard.keysDown = value;
  47142. },
  47143. enumerable: true,
  47144. configurable: true
  47145. });
  47146. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47147. get: function () {
  47148. var keyboard = this.inputs.attached["keyboard"];
  47149. if (keyboard)
  47150. return keyboard.keysLeft;
  47151. return [];
  47152. },
  47153. set: function (value) {
  47154. var keyboard = this.inputs.attached["keyboard"];
  47155. if (keyboard)
  47156. keyboard.keysLeft = value;
  47157. },
  47158. enumerable: true,
  47159. configurable: true
  47160. });
  47161. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47162. get: function () {
  47163. var keyboard = this.inputs.attached["keyboard"];
  47164. if (keyboard)
  47165. return keyboard.keysRight;
  47166. return [];
  47167. },
  47168. set: function (value) {
  47169. var keyboard = this.inputs.attached["keyboard"];
  47170. if (keyboard)
  47171. keyboard.keysRight = value;
  47172. },
  47173. enumerable: true,
  47174. configurable: true
  47175. });
  47176. // Controls
  47177. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47178. this.inputs.attachElement(element, noPreventDefault);
  47179. };
  47180. FreeCamera.prototype.detachControl = function (element) {
  47181. this.inputs.detachElement(element);
  47182. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47183. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47184. };
  47185. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47186. get: function () {
  47187. return this._collisionMask;
  47188. },
  47189. set: function (mask) {
  47190. this._collisionMask = !isNaN(mask) ? mask : -1;
  47191. },
  47192. enumerable: true,
  47193. configurable: true
  47194. });
  47195. /** @hidden */
  47196. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47197. var globalPosition;
  47198. if (this.parent) {
  47199. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47200. }
  47201. else {
  47202. globalPosition = this.position;
  47203. }
  47204. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47205. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47206. if (!this._collider) {
  47207. this._collider = new BABYLON.Collider();
  47208. }
  47209. this._collider._radius = this.ellipsoid;
  47210. this._collider.collisionMask = this._collisionMask;
  47211. //no need for clone, as long as gravity is not on.
  47212. var actualDisplacement = displacement;
  47213. //add gravity to the direction to prevent the dual-collision checking
  47214. if (this.applyGravity) {
  47215. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47216. actualDisplacement = displacement.add(this.getScene().gravity);
  47217. }
  47218. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47219. };
  47220. /** @hidden */
  47221. FreeCamera.prototype._checkInputs = function () {
  47222. if (!this._localDirection) {
  47223. this._localDirection = BABYLON.Vector3.Zero();
  47224. this._transformedDirection = BABYLON.Vector3.Zero();
  47225. }
  47226. this.inputs.checkInputs();
  47227. _super.prototype._checkInputs.call(this);
  47228. };
  47229. /** @hidden */
  47230. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47231. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47232. };
  47233. /** @hidden */
  47234. FreeCamera.prototype._updatePosition = function () {
  47235. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47236. this._collideWithWorld(this.cameraDirection);
  47237. }
  47238. else {
  47239. _super.prototype._updatePosition.call(this);
  47240. }
  47241. };
  47242. FreeCamera.prototype.dispose = function () {
  47243. this.inputs.clear();
  47244. _super.prototype.dispose.call(this);
  47245. };
  47246. FreeCamera.prototype.getClassName = function () {
  47247. return "FreeCamera";
  47248. };
  47249. __decorate([
  47250. BABYLON.serializeAsVector3()
  47251. ], FreeCamera.prototype, "ellipsoid", void 0);
  47252. __decorate([
  47253. BABYLON.serializeAsVector3()
  47254. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47255. __decorate([
  47256. BABYLON.serialize()
  47257. ], FreeCamera.prototype, "checkCollisions", void 0);
  47258. __decorate([
  47259. BABYLON.serialize()
  47260. ], FreeCamera.prototype, "applyGravity", void 0);
  47261. return FreeCamera;
  47262. }(BABYLON.TargetCamera));
  47263. BABYLON.FreeCamera = FreeCamera;
  47264. })(BABYLON || (BABYLON = {}));
  47265. //# sourceMappingURL=babylon.freeCamera.js.map
  47266. var BABYLON;
  47267. (function (BABYLON) {
  47268. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47269. function ArcRotateCameraKeyboardMoveInput() {
  47270. this._keys = new Array();
  47271. this.keysUp = [38];
  47272. this.keysDown = [40];
  47273. this.keysLeft = [37];
  47274. this.keysRight = [39];
  47275. this.keysReset = [220];
  47276. this.panningSensibility = 50.0;
  47277. this.zoomingSensibility = 25.0;
  47278. this.useAltToZoom = true;
  47279. }
  47280. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47281. var _this = this;
  47282. if (this._onCanvasBlurObserver) {
  47283. return;
  47284. }
  47285. this._scene = this.camera.getScene();
  47286. this._engine = this._scene.getEngine();
  47287. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47288. _this._keys = [];
  47289. });
  47290. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47291. var evt = info.event;
  47292. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47293. _this._ctrlPressed = evt.ctrlKey;
  47294. _this._altPressed = evt.altKey;
  47295. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47296. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47297. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47298. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47299. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47300. var index = _this._keys.indexOf(evt.keyCode);
  47301. if (index === -1) {
  47302. _this._keys.push(evt.keyCode);
  47303. }
  47304. if (evt.preventDefault) {
  47305. if (!noPreventDefault) {
  47306. evt.preventDefault();
  47307. }
  47308. }
  47309. }
  47310. }
  47311. else {
  47312. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47313. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47314. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47315. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47316. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47317. var index = _this._keys.indexOf(evt.keyCode);
  47318. if (index >= 0) {
  47319. _this._keys.splice(index, 1);
  47320. }
  47321. if (evt.preventDefault) {
  47322. if (!noPreventDefault) {
  47323. evt.preventDefault();
  47324. }
  47325. }
  47326. }
  47327. }
  47328. });
  47329. };
  47330. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47331. if (this._scene) {
  47332. if (this._onKeyboardObserver) {
  47333. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47334. }
  47335. if (this._onCanvasBlurObserver) {
  47336. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47337. }
  47338. this._onKeyboardObserver = null;
  47339. this._onCanvasBlurObserver = null;
  47340. }
  47341. this._keys = [];
  47342. };
  47343. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47344. if (this._onKeyboardObserver) {
  47345. var camera = this.camera;
  47346. for (var index = 0; index < this._keys.length; index++) {
  47347. var keyCode = this._keys[index];
  47348. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47349. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47350. camera.inertialPanningX -= 1 / this.panningSensibility;
  47351. }
  47352. else {
  47353. camera.inertialAlphaOffset -= 0.01;
  47354. }
  47355. }
  47356. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47357. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47358. camera.inertialPanningY += 1 / this.panningSensibility;
  47359. }
  47360. else if (this._altPressed && this.useAltToZoom) {
  47361. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47362. }
  47363. else {
  47364. camera.inertialBetaOffset -= 0.01;
  47365. }
  47366. }
  47367. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47368. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47369. camera.inertialPanningX += 1 / this.panningSensibility;
  47370. }
  47371. else {
  47372. camera.inertialAlphaOffset += 0.01;
  47373. }
  47374. }
  47375. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47376. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47377. camera.inertialPanningY -= 1 / this.panningSensibility;
  47378. }
  47379. else if (this._altPressed && this.useAltToZoom) {
  47380. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47381. }
  47382. else {
  47383. camera.inertialBetaOffset += 0.01;
  47384. }
  47385. }
  47386. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47387. camera.restoreState();
  47388. }
  47389. }
  47390. }
  47391. };
  47392. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47393. return "ArcRotateCameraKeyboardMoveInput";
  47394. };
  47395. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47396. return "keyboard";
  47397. };
  47398. __decorate([
  47399. BABYLON.serialize()
  47400. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47401. __decorate([
  47402. BABYLON.serialize()
  47403. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47404. __decorate([
  47405. BABYLON.serialize()
  47406. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47407. __decorate([
  47408. BABYLON.serialize()
  47409. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47410. __decorate([
  47411. BABYLON.serialize()
  47412. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47413. __decorate([
  47414. BABYLON.serialize()
  47415. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47416. __decorate([
  47417. BABYLON.serialize()
  47418. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47419. __decorate([
  47420. BABYLON.serialize()
  47421. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47422. return ArcRotateCameraKeyboardMoveInput;
  47423. }());
  47424. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47425. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47426. })(BABYLON || (BABYLON = {}));
  47427. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47428. var BABYLON;
  47429. (function (BABYLON) {
  47430. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47431. function ArcRotateCameraMouseWheelInput() {
  47432. this.wheelPrecision = 3.0;
  47433. /**
  47434. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47435. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47436. */
  47437. this.wheelDeltaPercentage = 0;
  47438. }
  47439. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47440. var _this = this;
  47441. this._wheel = function (p, s) {
  47442. //sanity check - this should be a PointerWheel event.
  47443. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47444. return;
  47445. var event = p.event;
  47446. var delta = 0;
  47447. if (event.wheelDelta) {
  47448. if (_this.wheelDeltaPercentage) {
  47449. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47450. if (event.wheelDelta > 0) {
  47451. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47452. }
  47453. else {
  47454. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47455. }
  47456. }
  47457. else {
  47458. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47459. }
  47460. }
  47461. else if (event.detail) {
  47462. delta = -event.detail / _this.wheelPrecision;
  47463. }
  47464. if (delta)
  47465. _this.camera.inertialRadiusOffset += delta;
  47466. if (event.preventDefault) {
  47467. if (!noPreventDefault) {
  47468. event.preventDefault();
  47469. }
  47470. }
  47471. };
  47472. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47473. };
  47474. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47475. if (this._observer && element) {
  47476. this.camera.getScene().onPointerObservable.remove(this._observer);
  47477. this._observer = null;
  47478. this._wheel = null;
  47479. }
  47480. };
  47481. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47482. return "ArcRotateCameraMouseWheelInput";
  47483. };
  47484. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47485. return "mousewheel";
  47486. };
  47487. __decorate([
  47488. BABYLON.serialize()
  47489. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47490. __decorate([
  47491. BABYLON.serialize()
  47492. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47493. return ArcRotateCameraMouseWheelInput;
  47494. }());
  47495. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47496. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47497. })(BABYLON || (BABYLON = {}));
  47498. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47499. var BABYLON;
  47500. (function (BABYLON) {
  47501. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47502. function ArcRotateCameraPointersInput() {
  47503. this.buttons = [0, 1, 2];
  47504. this.angularSensibilityX = 1000.0;
  47505. this.angularSensibilityY = 1000.0;
  47506. this.pinchPrecision = 12.0;
  47507. /**
  47508. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47509. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47510. */
  47511. this.pinchDeltaPercentage = 0;
  47512. this.panningSensibility = 1000.0;
  47513. this.multiTouchPanning = true;
  47514. this.multiTouchPanAndZoom = true;
  47515. this._isPanClick = false;
  47516. this.pinchInwards = true;
  47517. }
  47518. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47519. var _this = this;
  47520. var engine = this.camera.getEngine();
  47521. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47522. var pointA = null;
  47523. var pointB = null;
  47524. var previousPinchSquaredDistance = 0;
  47525. var initialDistance = 0;
  47526. var twoFingerActivityCount = 0;
  47527. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47528. this._pointerInput = function (p, s) {
  47529. var evt = p.event;
  47530. var isTouch = p.event.pointerType === "touch";
  47531. if (engine.isInVRExclusivePointerMode) {
  47532. return;
  47533. }
  47534. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47535. return;
  47536. }
  47537. var srcElement = (evt.srcElement || evt.target);
  47538. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47539. try {
  47540. srcElement.setPointerCapture(evt.pointerId);
  47541. }
  47542. catch (e) {
  47543. //Nothing to do with the error. Execution will continue.
  47544. }
  47545. // Manage panning with pan button click
  47546. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47547. // manage pointers
  47548. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47549. if (pointA === null) {
  47550. pointA = cacheSoloPointer;
  47551. }
  47552. else if (pointB === null) {
  47553. pointB = cacheSoloPointer;
  47554. }
  47555. if (!noPreventDefault) {
  47556. evt.preventDefault();
  47557. element.focus();
  47558. }
  47559. }
  47560. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47561. _this.camera.restoreState();
  47562. }
  47563. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47564. try {
  47565. srcElement.releasePointerCapture(evt.pointerId);
  47566. }
  47567. catch (e) {
  47568. //Nothing to do with the error.
  47569. }
  47570. cacheSoloPointer = null;
  47571. previousPinchSquaredDistance = 0;
  47572. previousMultiTouchPanPosition.isPaning = false;
  47573. previousMultiTouchPanPosition.isPinching = false;
  47574. twoFingerActivityCount = 0;
  47575. initialDistance = 0;
  47576. if (!isTouch) {
  47577. pointB = null; // Mouse and pen are mono pointer
  47578. }
  47579. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47580. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47581. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47582. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47583. if (engine._badOS) {
  47584. pointA = pointB = null;
  47585. }
  47586. else {
  47587. //only remove the impacted pointer in case of multitouch allowing on most
  47588. //platforms switching from rotate to zoom and pan seamlessly.
  47589. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47590. pointA = pointB;
  47591. pointB = null;
  47592. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47593. }
  47594. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47595. pointB = null;
  47596. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47597. }
  47598. else {
  47599. pointA = pointB = null;
  47600. }
  47601. }
  47602. if (!noPreventDefault) {
  47603. evt.preventDefault();
  47604. }
  47605. }
  47606. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47607. if (!noPreventDefault) {
  47608. evt.preventDefault();
  47609. }
  47610. // One button down
  47611. if (pointA && pointB === null && cacheSoloPointer) {
  47612. if (_this.panningSensibility !== 0 &&
  47613. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47614. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47615. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47616. }
  47617. else {
  47618. var offsetX = evt.clientX - cacheSoloPointer.x;
  47619. var offsetY = evt.clientY - cacheSoloPointer.y;
  47620. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47621. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47622. }
  47623. cacheSoloPointer.x = evt.clientX;
  47624. cacheSoloPointer.y = evt.clientY;
  47625. }
  47626. // Two buttons down: pinch/pan
  47627. else if (pointA && pointB) {
  47628. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47629. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47630. ed.x = evt.clientX;
  47631. ed.y = evt.clientY;
  47632. var direction = _this.pinchInwards ? 1 : -1;
  47633. var distX = pointA.x - pointB.x;
  47634. var distY = pointA.y - pointB.y;
  47635. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47636. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47637. if (previousPinchSquaredDistance === 0) {
  47638. initialDistance = pinchDistance;
  47639. previousPinchSquaredDistance = pinchSquaredDistance;
  47640. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47641. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47642. return;
  47643. }
  47644. if (_this.multiTouchPanAndZoom) {
  47645. if (_this.pinchDeltaPercentage) {
  47646. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47647. }
  47648. else {
  47649. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47650. (_this.pinchPrecision *
  47651. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47652. direction);
  47653. }
  47654. if (_this.panningSensibility !== 0) {
  47655. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47656. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47657. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47658. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47659. previousMultiTouchPanPosition.x = pointersCenterX;
  47660. previousMultiTouchPanPosition.y = pointersCenterY;
  47661. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47662. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47663. }
  47664. }
  47665. else {
  47666. twoFingerActivityCount++;
  47667. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47668. if (_this.pinchDeltaPercentage) {
  47669. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47670. }
  47671. else {
  47672. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47673. (_this.pinchPrecision *
  47674. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47675. direction);
  47676. }
  47677. previousMultiTouchPanPosition.isPaning = false;
  47678. previousMultiTouchPanPosition.isPinching = true;
  47679. }
  47680. else {
  47681. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47682. if (!previousMultiTouchPanPosition.isPaning) {
  47683. previousMultiTouchPanPosition.isPaning = true;
  47684. previousMultiTouchPanPosition.isPinching = false;
  47685. previousMultiTouchPanPosition.x = ed.x;
  47686. previousMultiTouchPanPosition.y = ed.y;
  47687. return;
  47688. }
  47689. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47690. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47691. }
  47692. }
  47693. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47694. previousMultiTouchPanPosition.x = ed.x;
  47695. previousMultiTouchPanPosition.y = ed.y;
  47696. }
  47697. }
  47698. previousPinchSquaredDistance = pinchSquaredDistance;
  47699. }
  47700. }
  47701. };
  47702. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47703. this._onContextMenu = function (evt) {
  47704. evt.preventDefault();
  47705. };
  47706. if (!this.camera._useCtrlForPanning) {
  47707. element.addEventListener("contextmenu", this._onContextMenu, false);
  47708. }
  47709. this._onLostFocus = function () {
  47710. //this._keys = [];
  47711. pointA = pointB = null;
  47712. previousPinchSquaredDistance = 0;
  47713. previousMultiTouchPanPosition.isPaning = false;
  47714. previousMultiTouchPanPosition.isPinching = false;
  47715. twoFingerActivityCount = 0;
  47716. cacheSoloPointer = null;
  47717. initialDistance = 0;
  47718. };
  47719. this._onMouseMove = function (evt) {
  47720. if (!engine.isPointerLock) {
  47721. return;
  47722. }
  47723. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47724. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47725. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47726. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47727. if (!noPreventDefault) {
  47728. evt.preventDefault();
  47729. }
  47730. };
  47731. this._onGestureStart = function (e) {
  47732. if (window.MSGesture === undefined) {
  47733. return;
  47734. }
  47735. if (!_this._MSGestureHandler) {
  47736. _this._MSGestureHandler = new MSGesture();
  47737. _this._MSGestureHandler.target = element;
  47738. }
  47739. _this._MSGestureHandler.addPointer(e.pointerId);
  47740. };
  47741. this._onGesture = function (e) {
  47742. _this.camera.radius *= e.scale;
  47743. if (e.preventDefault) {
  47744. if (!noPreventDefault) {
  47745. e.stopPropagation();
  47746. e.preventDefault();
  47747. }
  47748. }
  47749. };
  47750. element.addEventListener("mousemove", this._onMouseMove, false);
  47751. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47752. element.addEventListener("MSGestureChange", this._onGesture, false);
  47753. BABYLON.Tools.RegisterTopRootEvents([
  47754. { name: "blur", handler: this._onLostFocus }
  47755. ]);
  47756. };
  47757. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47758. if (this._onLostFocus) {
  47759. BABYLON.Tools.UnregisterTopRootEvents([
  47760. { name: "blur", handler: this._onLostFocus }
  47761. ]);
  47762. }
  47763. if (element && this._observer) {
  47764. this.camera.getScene().onPointerObservable.remove(this._observer);
  47765. this._observer = null;
  47766. if (this._onContextMenu) {
  47767. element.removeEventListener("contextmenu", this._onContextMenu);
  47768. }
  47769. if (this._onMouseMove) {
  47770. element.removeEventListener("mousemove", this._onMouseMove);
  47771. }
  47772. if (this._onGestureStart) {
  47773. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47774. }
  47775. if (this._onGesture) {
  47776. element.removeEventListener("MSGestureChange", this._onGesture);
  47777. }
  47778. this._isPanClick = false;
  47779. this.pinchInwards = true;
  47780. this._onMouseMove = null;
  47781. this._onGestureStart = null;
  47782. this._onGesture = null;
  47783. this._MSGestureHandler = null;
  47784. this._onLostFocus = null;
  47785. this._onContextMenu = null;
  47786. }
  47787. };
  47788. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47789. return "ArcRotateCameraPointersInput";
  47790. };
  47791. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47792. return "pointers";
  47793. };
  47794. __decorate([
  47795. BABYLON.serialize()
  47796. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47797. __decorate([
  47798. BABYLON.serialize()
  47799. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47800. __decorate([
  47801. BABYLON.serialize()
  47802. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47803. __decorate([
  47804. BABYLON.serialize()
  47805. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47806. __decorate([
  47807. BABYLON.serialize()
  47808. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47809. __decorate([
  47810. BABYLON.serialize()
  47811. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47812. __decorate([
  47813. BABYLON.serialize()
  47814. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47815. __decorate([
  47816. BABYLON.serialize()
  47817. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47818. return ArcRotateCameraPointersInput;
  47819. }());
  47820. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47821. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47822. })(BABYLON || (BABYLON = {}));
  47823. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47824. var BABYLON;
  47825. (function (BABYLON) {
  47826. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47827. __extends(ArcRotateCameraInputsManager, _super);
  47828. function ArcRotateCameraInputsManager(camera) {
  47829. return _super.call(this, camera) || this;
  47830. }
  47831. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47832. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47833. return this;
  47834. };
  47835. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47836. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47837. return this;
  47838. };
  47839. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47840. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47841. return this;
  47842. };
  47843. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47844. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47845. return this;
  47846. };
  47847. return ArcRotateCameraInputsManager;
  47848. }(BABYLON.CameraInputsManager));
  47849. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47850. })(BABYLON || (BABYLON = {}));
  47851. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47852. var BABYLON;
  47853. (function (BABYLON) {
  47854. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47855. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47856. });
  47857. var ArcRotateCamera = /** @class */ (function (_super) {
  47858. __extends(ArcRotateCamera, _super);
  47859. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47860. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47861. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47862. _this.inertialAlphaOffset = 0;
  47863. _this.inertialBetaOffset = 0;
  47864. _this.inertialRadiusOffset = 0;
  47865. _this.lowerAlphaLimit = null;
  47866. _this.upperAlphaLimit = null;
  47867. _this.lowerBetaLimit = 0.01;
  47868. _this.upperBetaLimit = Math.PI;
  47869. _this.lowerRadiusLimit = null;
  47870. _this.upperRadiusLimit = null;
  47871. _this.inertialPanningX = 0;
  47872. _this.inertialPanningY = 0;
  47873. _this.pinchToPanMaxDistance = 20;
  47874. _this.panningDistanceLimit = null;
  47875. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47876. _this.panningInertia = 0.9;
  47877. //-- end properties for backward compatibility for inputs
  47878. _this.zoomOnFactor = 1;
  47879. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47880. _this.allowUpsideDown = true;
  47881. /** @hidden */
  47882. _this._viewMatrix = new BABYLON.Matrix();
  47883. // Panning
  47884. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47885. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47886. _this.checkCollisions = false;
  47887. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47888. _this._previousPosition = BABYLON.Vector3.Zero();
  47889. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47890. _this._newPosition = BABYLON.Vector3.Zero();
  47891. _this._computationVector = BABYLON.Vector3.Zero();
  47892. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47893. if (collidedMesh === void 0) { collidedMesh = null; }
  47894. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47895. newPosition.multiplyInPlace(_this._collider._radius);
  47896. }
  47897. if (!collidedMesh) {
  47898. _this._previousPosition.copyFrom(_this.position);
  47899. }
  47900. else {
  47901. _this.setPosition(newPosition);
  47902. if (_this.onCollide) {
  47903. _this.onCollide(collidedMesh);
  47904. }
  47905. }
  47906. // Recompute because of constraints
  47907. var cosa = Math.cos(_this.alpha);
  47908. var sina = Math.sin(_this.alpha);
  47909. var cosb = Math.cos(_this.beta);
  47910. var sinb = Math.sin(_this.beta);
  47911. if (sinb === 0) {
  47912. sinb = 0.0001;
  47913. }
  47914. var target = _this._getTargetPosition();
  47915. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47916. target.addToRef(_this._computationVector, _this._newPosition);
  47917. _this.position.copyFrom(_this._newPosition);
  47918. var up = _this.upVector;
  47919. if (_this.allowUpsideDown && _this.beta < 0) {
  47920. up = up.clone();
  47921. up = up.negate();
  47922. }
  47923. _this._computeViewMatrix(_this.position, target, up);
  47924. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47925. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47926. _this._collisionTriggered = false;
  47927. };
  47928. _this._target = BABYLON.Vector3.Zero();
  47929. if (target) {
  47930. _this.setTarget(target);
  47931. }
  47932. _this.alpha = alpha;
  47933. _this.beta = beta;
  47934. _this.radius = radius;
  47935. _this.getViewMatrix();
  47936. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47937. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47938. return _this;
  47939. }
  47940. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47941. get: function () {
  47942. return this._target;
  47943. },
  47944. set: function (value) {
  47945. this.setTarget(value);
  47946. },
  47947. enumerable: true,
  47948. configurable: true
  47949. });
  47950. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47951. //-- begin properties for backward compatibility for inputs
  47952. get: function () {
  47953. var pointers = this.inputs.attached["pointers"];
  47954. if (pointers)
  47955. return pointers.angularSensibilityX;
  47956. return 0;
  47957. },
  47958. set: function (value) {
  47959. var pointers = this.inputs.attached["pointers"];
  47960. if (pointers) {
  47961. pointers.angularSensibilityX = value;
  47962. }
  47963. },
  47964. enumerable: true,
  47965. configurable: true
  47966. });
  47967. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47968. get: function () {
  47969. var pointers = this.inputs.attached["pointers"];
  47970. if (pointers)
  47971. return pointers.angularSensibilityY;
  47972. return 0;
  47973. },
  47974. set: function (value) {
  47975. var pointers = this.inputs.attached["pointers"];
  47976. if (pointers) {
  47977. pointers.angularSensibilityY = value;
  47978. }
  47979. },
  47980. enumerable: true,
  47981. configurable: true
  47982. });
  47983. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47984. get: function () {
  47985. var pointers = this.inputs.attached["pointers"];
  47986. if (pointers)
  47987. return pointers.pinchPrecision;
  47988. return 0;
  47989. },
  47990. set: function (value) {
  47991. var pointers = this.inputs.attached["pointers"];
  47992. if (pointers) {
  47993. pointers.pinchPrecision = value;
  47994. }
  47995. },
  47996. enumerable: true,
  47997. configurable: true
  47998. });
  47999. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48000. get: function () {
  48001. var pointers = this.inputs.attached["pointers"];
  48002. if (pointers)
  48003. return pointers.pinchDeltaPercentage;
  48004. return 0;
  48005. },
  48006. set: function (value) {
  48007. var pointers = this.inputs.attached["pointers"];
  48008. if (pointers) {
  48009. pointers.pinchDeltaPercentage = value;
  48010. }
  48011. },
  48012. enumerable: true,
  48013. configurable: true
  48014. });
  48015. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48016. get: function () {
  48017. var pointers = this.inputs.attached["pointers"];
  48018. if (pointers)
  48019. return pointers.panningSensibility;
  48020. return 0;
  48021. },
  48022. set: function (value) {
  48023. var pointers = this.inputs.attached["pointers"];
  48024. if (pointers) {
  48025. pointers.panningSensibility = value;
  48026. }
  48027. },
  48028. enumerable: true,
  48029. configurable: true
  48030. });
  48031. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48032. get: function () {
  48033. var keyboard = this.inputs.attached["keyboard"];
  48034. if (keyboard)
  48035. return keyboard.keysUp;
  48036. return [];
  48037. },
  48038. set: function (value) {
  48039. var keyboard = this.inputs.attached["keyboard"];
  48040. if (keyboard)
  48041. keyboard.keysUp = value;
  48042. },
  48043. enumerable: true,
  48044. configurable: true
  48045. });
  48046. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48047. get: function () {
  48048. var keyboard = this.inputs.attached["keyboard"];
  48049. if (keyboard)
  48050. return keyboard.keysDown;
  48051. return [];
  48052. },
  48053. set: function (value) {
  48054. var keyboard = this.inputs.attached["keyboard"];
  48055. if (keyboard)
  48056. keyboard.keysDown = value;
  48057. },
  48058. enumerable: true,
  48059. configurable: true
  48060. });
  48061. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48062. get: function () {
  48063. var keyboard = this.inputs.attached["keyboard"];
  48064. if (keyboard)
  48065. return keyboard.keysLeft;
  48066. return [];
  48067. },
  48068. set: function (value) {
  48069. var keyboard = this.inputs.attached["keyboard"];
  48070. if (keyboard)
  48071. keyboard.keysLeft = value;
  48072. },
  48073. enumerable: true,
  48074. configurable: true
  48075. });
  48076. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48077. get: function () {
  48078. var keyboard = this.inputs.attached["keyboard"];
  48079. if (keyboard)
  48080. return keyboard.keysRight;
  48081. return [];
  48082. },
  48083. set: function (value) {
  48084. var keyboard = this.inputs.attached["keyboard"];
  48085. if (keyboard)
  48086. keyboard.keysRight = value;
  48087. },
  48088. enumerable: true,
  48089. configurable: true
  48090. });
  48091. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48092. get: function () {
  48093. var mousewheel = this.inputs.attached["mousewheel"];
  48094. if (mousewheel)
  48095. return mousewheel.wheelPrecision;
  48096. return 0;
  48097. },
  48098. set: function (value) {
  48099. var mousewheel = this.inputs.attached["mousewheel"];
  48100. if (mousewheel)
  48101. mousewheel.wheelPrecision = value;
  48102. },
  48103. enumerable: true,
  48104. configurable: true
  48105. });
  48106. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48107. get: function () {
  48108. var mousewheel = this.inputs.attached["mousewheel"];
  48109. if (mousewheel)
  48110. return mousewheel.wheelDeltaPercentage;
  48111. return 0;
  48112. },
  48113. set: function (value) {
  48114. var mousewheel = this.inputs.attached["mousewheel"];
  48115. if (mousewheel)
  48116. mousewheel.wheelDeltaPercentage = value;
  48117. },
  48118. enumerable: true,
  48119. configurable: true
  48120. });
  48121. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48122. get: function () {
  48123. return this._bouncingBehavior;
  48124. },
  48125. enumerable: true,
  48126. configurable: true
  48127. });
  48128. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48129. get: function () {
  48130. return this._bouncingBehavior != null;
  48131. },
  48132. set: function (value) {
  48133. if (value === this.useBouncingBehavior) {
  48134. return;
  48135. }
  48136. if (value) {
  48137. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48138. this.addBehavior(this._bouncingBehavior);
  48139. }
  48140. else if (this._bouncingBehavior) {
  48141. this.removeBehavior(this._bouncingBehavior);
  48142. this._bouncingBehavior = null;
  48143. }
  48144. },
  48145. enumerable: true,
  48146. configurable: true
  48147. });
  48148. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48149. get: function () {
  48150. return this._framingBehavior;
  48151. },
  48152. enumerable: true,
  48153. configurable: true
  48154. });
  48155. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48156. get: function () {
  48157. return this._framingBehavior != null;
  48158. },
  48159. set: function (value) {
  48160. if (value === this.useFramingBehavior) {
  48161. return;
  48162. }
  48163. if (value) {
  48164. this._framingBehavior = new BABYLON.FramingBehavior();
  48165. this.addBehavior(this._framingBehavior);
  48166. }
  48167. else if (this._framingBehavior) {
  48168. this.removeBehavior(this._framingBehavior);
  48169. this._framingBehavior = null;
  48170. }
  48171. },
  48172. enumerable: true,
  48173. configurable: true
  48174. });
  48175. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48176. get: function () {
  48177. return this._autoRotationBehavior;
  48178. },
  48179. enumerable: true,
  48180. configurable: true
  48181. });
  48182. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48183. get: function () {
  48184. return this._autoRotationBehavior != null;
  48185. },
  48186. set: function (value) {
  48187. if (value === this.useAutoRotationBehavior) {
  48188. return;
  48189. }
  48190. if (value) {
  48191. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48192. this.addBehavior(this._autoRotationBehavior);
  48193. }
  48194. else if (this._autoRotationBehavior) {
  48195. this.removeBehavior(this._autoRotationBehavior);
  48196. this._autoRotationBehavior = null;
  48197. }
  48198. },
  48199. enumerable: true,
  48200. configurable: true
  48201. });
  48202. // Cache
  48203. /** @hidden */
  48204. ArcRotateCamera.prototype._initCache = function () {
  48205. _super.prototype._initCache.call(this);
  48206. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48207. this._cache.alpha = undefined;
  48208. this._cache.beta = undefined;
  48209. this._cache.radius = undefined;
  48210. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48211. };
  48212. /** @hidden */
  48213. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48214. if (!ignoreParentClass) {
  48215. _super.prototype._updateCache.call(this);
  48216. }
  48217. this._cache._target.copyFrom(this._getTargetPosition());
  48218. this._cache.alpha = this.alpha;
  48219. this._cache.beta = this.beta;
  48220. this._cache.radius = this.radius;
  48221. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48222. };
  48223. ArcRotateCamera.prototype._getTargetPosition = function () {
  48224. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48225. var pos = this._targetHost.getAbsolutePosition();
  48226. if (this._targetBoundingCenter) {
  48227. pos.addToRef(this._targetBoundingCenter, this._target);
  48228. }
  48229. else {
  48230. this._target.copyFrom(pos);
  48231. }
  48232. }
  48233. var lockedTargetPosition = this._getLockedTargetPosition();
  48234. if (lockedTargetPosition) {
  48235. return lockedTargetPosition;
  48236. }
  48237. return this._target;
  48238. };
  48239. ArcRotateCamera.prototype.storeState = function () {
  48240. this._storedAlpha = this.alpha;
  48241. this._storedBeta = this.beta;
  48242. this._storedRadius = this.radius;
  48243. this._storedTarget = this._getTargetPosition().clone();
  48244. return _super.prototype.storeState.call(this);
  48245. };
  48246. /**
  48247. * @hidden
  48248. * Restored camera state. You must call storeState() first
  48249. */
  48250. ArcRotateCamera.prototype._restoreStateValues = function () {
  48251. if (!_super.prototype._restoreStateValues.call(this)) {
  48252. return false;
  48253. }
  48254. this.alpha = this._storedAlpha;
  48255. this.beta = this._storedBeta;
  48256. this.radius = this._storedRadius;
  48257. this.setTarget(this._storedTarget.clone());
  48258. this.inertialAlphaOffset = 0;
  48259. this.inertialBetaOffset = 0;
  48260. this.inertialRadiusOffset = 0;
  48261. this.inertialPanningX = 0;
  48262. this.inertialPanningY = 0;
  48263. return true;
  48264. };
  48265. // Synchronized
  48266. /** @hidden */
  48267. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48268. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48269. return false;
  48270. return this._cache._target.equals(this._getTargetPosition())
  48271. && this._cache.alpha === this.alpha
  48272. && this._cache.beta === this.beta
  48273. && this._cache.radius === this.radius
  48274. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48275. };
  48276. // Methods
  48277. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48278. var _this = this;
  48279. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48280. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48281. this._useCtrlForPanning = useCtrlForPanning;
  48282. this._panningMouseButton = panningMouseButton;
  48283. this.inputs.attachElement(element, noPreventDefault);
  48284. this._reset = function () {
  48285. _this.inertialAlphaOffset = 0;
  48286. _this.inertialBetaOffset = 0;
  48287. _this.inertialRadiusOffset = 0;
  48288. _this.inertialPanningX = 0;
  48289. _this.inertialPanningY = 0;
  48290. };
  48291. };
  48292. ArcRotateCamera.prototype.detachControl = function (element) {
  48293. this.inputs.detachElement(element);
  48294. if (this._reset) {
  48295. this._reset();
  48296. }
  48297. };
  48298. /** @hidden */
  48299. ArcRotateCamera.prototype._checkInputs = function () {
  48300. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48301. if (this._collisionTriggered) {
  48302. return;
  48303. }
  48304. this.inputs.checkInputs();
  48305. // Inertia
  48306. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48307. var inertialAlphaOffset = this.inertialAlphaOffset;
  48308. if (this.beta <= 0)
  48309. inertialAlphaOffset *= -1;
  48310. if (this.getScene().useRightHandedSystem)
  48311. inertialAlphaOffset *= -1;
  48312. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48313. inertialAlphaOffset *= -1;
  48314. this.alpha += inertialAlphaOffset;
  48315. this.beta += this.inertialBetaOffset;
  48316. this.radius -= this.inertialRadiusOffset;
  48317. this.inertialAlphaOffset *= this.inertia;
  48318. this.inertialBetaOffset *= this.inertia;
  48319. this.inertialRadiusOffset *= this.inertia;
  48320. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48321. this.inertialAlphaOffset = 0;
  48322. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48323. this.inertialBetaOffset = 0;
  48324. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48325. this.inertialRadiusOffset = 0;
  48326. }
  48327. // Panning inertia
  48328. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48329. if (!this._localDirection) {
  48330. this._localDirection = BABYLON.Vector3.Zero();
  48331. this._transformedDirection = BABYLON.Vector3.Zero();
  48332. }
  48333. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48334. this._localDirection.multiplyInPlace(this.panningAxis);
  48335. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48336. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48337. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48338. if (!this.panningAxis.y) {
  48339. this._transformedDirection.y = 0;
  48340. }
  48341. if (!this._targetHost) {
  48342. if (this.panningDistanceLimit) {
  48343. this._transformedDirection.addInPlace(this._target);
  48344. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48345. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48346. this._target.copyFrom(this._transformedDirection);
  48347. }
  48348. }
  48349. else {
  48350. this._target.addInPlace(this._transformedDirection);
  48351. }
  48352. }
  48353. this.inertialPanningX *= this.panningInertia;
  48354. this.inertialPanningY *= this.panningInertia;
  48355. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48356. this.inertialPanningX = 0;
  48357. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48358. this.inertialPanningY = 0;
  48359. }
  48360. // Limits
  48361. this._checkLimits();
  48362. _super.prototype._checkInputs.call(this);
  48363. };
  48364. ArcRotateCamera.prototype._checkLimits = function () {
  48365. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48366. if (this.allowUpsideDown && this.beta > Math.PI) {
  48367. this.beta = this.beta - (2 * Math.PI);
  48368. }
  48369. }
  48370. else {
  48371. if (this.beta < this.lowerBetaLimit) {
  48372. this.beta = this.lowerBetaLimit;
  48373. }
  48374. }
  48375. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48376. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48377. this.beta = this.beta + (2 * Math.PI);
  48378. }
  48379. }
  48380. else {
  48381. if (this.beta > this.upperBetaLimit) {
  48382. this.beta = this.upperBetaLimit;
  48383. }
  48384. }
  48385. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48386. this.alpha = this.lowerAlphaLimit;
  48387. }
  48388. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48389. this.alpha = this.upperAlphaLimit;
  48390. }
  48391. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48392. this.radius = this.lowerRadiusLimit;
  48393. }
  48394. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48395. this.radius = this.upperRadiusLimit;
  48396. }
  48397. };
  48398. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48399. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48400. this.radius = this._computationVector.length();
  48401. if (this.radius === 0) {
  48402. this.radius = 0.0001; // Just to avoid division by zero
  48403. }
  48404. // Alpha
  48405. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48406. if (this._computationVector.z < 0) {
  48407. this.alpha = 2 * Math.PI - this.alpha;
  48408. }
  48409. // Beta
  48410. this.beta = Math.acos(this._computationVector.y / this.radius);
  48411. this._checkLimits();
  48412. };
  48413. ArcRotateCamera.prototype.setPosition = function (position) {
  48414. if (this.position.equals(position)) {
  48415. return;
  48416. }
  48417. this.position.copyFrom(position);
  48418. this.rebuildAnglesAndRadius();
  48419. };
  48420. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48421. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48422. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48423. if (target.getBoundingInfo) {
  48424. if (toBoundingCenter) {
  48425. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48426. }
  48427. else {
  48428. this._targetBoundingCenter = null;
  48429. }
  48430. this._targetHost = target;
  48431. this._target = this._getTargetPosition();
  48432. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48433. }
  48434. else {
  48435. var newTarget = target;
  48436. var currentTarget = this._getTargetPosition();
  48437. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48438. return;
  48439. }
  48440. this._targetHost = null;
  48441. this._target = newTarget;
  48442. this._targetBoundingCenter = null;
  48443. this.onMeshTargetChangedObservable.notifyObservers(null);
  48444. }
  48445. this.rebuildAnglesAndRadius();
  48446. };
  48447. /** @hidden */
  48448. ArcRotateCamera.prototype._getViewMatrix = function () {
  48449. // Compute
  48450. var cosa = Math.cos(this.alpha);
  48451. var sina = Math.sin(this.alpha);
  48452. var cosb = Math.cos(this.beta);
  48453. var sinb = Math.sin(this.beta);
  48454. if (sinb === 0) {
  48455. sinb = 0.0001;
  48456. }
  48457. var target = this._getTargetPosition();
  48458. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48459. target.addToRef(this._computationVector, this._newPosition);
  48460. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48461. if (!this._collider) {
  48462. this._collider = new BABYLON.Collider();
  48463. }
  48464. this._collider._radius = this.collisionRadius;
  48465. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48466. this._collisionTriggered = true;
  48467. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48468. }
  48469. else {
  48470. this.position.copyFrom(this._newPosition);
  48471. var up = this.upVector;
  48472. if (this.allowUpsideDown && sinb < 0) {
  48473. up = up.clone();
  48474. up = up.negate();
  48475. }
  48476. this._computeViewMatrix(this.position, target, up);
  48477. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48478. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48479. }
  48480. this._currentTarget = target;
  48481. return this._viewMatrix;
  48482. };
  48483. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48484. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48485. meshes = meshes || this.getScene().meshes;
  48486. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48487. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48488. this.radius = distance * this.zoomOnFactor;
  48489. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48490. };
  48491. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48492. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48493. var meshesOrMinMaxVector;
  48494. var distance;
  48495. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48496. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48497. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48498. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48499. }
  48500. else { //minMaxVector and distance
  48501. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48502. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48503. distance = minMaxVectorAndDistance.distance;
  48504. }
  48505. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48506. if (!doNotUpdateMaxZ) {
  48507. this.maxZ = distance * 2;
  48508. }
  48509. };
  48510. /**
  48511. * @override
  48512. * Override Camera.createRigCamera
  48513. */
  48514. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48515. var alphaShift = 0;
  48516. switch (this.cameraRigMode) {
  48517. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48518. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48519. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48520. case BABYLON.Camera.RIG_MODE_VR:
  48521. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48522. break;
  48523. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48524. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48525. break;
  48526. }
  48527. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48528. rigCam._cameraRigParams = {};
  48529. return rigCam;
  48530. };
  48531. /**
  48532. * @hidden
  48533. * @override
  48534. * Override Camera._updateRigCameras
  48535. */
  48536. ArcRotateCamera.prototype._updateRigCameras = function () {
  48537. var camLeft = this._rigCameras[0];
  48538. var camRight = this._rigCameras[1];
  48539. camLeft.beta = camRight.beta = this.beta;
  48540. camLeft.radius = camRight.radius = this.radius;
  48541. switch (this.cameraRigMode) {
  48542. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48543. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48544. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48545. case BABYLON.Camera.RIG_MODE_VR:
  48546. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48547. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48548. break;
  48549. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48550. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48551. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48552. break;
  48553. }
  48554. _super.prototype._updateRigCameras.call(this);
  48555. };
  48556. ArcRotateCamera.prototype.dispose = function () {
  48557. this.inputs.clear();
  48558. _super.prototype.dispose.call(this);
  48559. };
  48560. ArcRotateCamera.prototype.getClassName = function () {
  48561. return "ArcRotateCamera";
  48562. };
  48563. __decorate([
  48564. BABYLON.serialize()
  48565. ], ArcRotateCamera.prototype, "alpha", void 0);
  48566. __decorate([
  48567. BABYLON.serialize()
  48568. ], ArcRotateCamera.prototype, "beta", void 0);
  48569. __decorate([
  48570. BABYLON.serialize()
  48571. ], ArcRotateCamera.prototype, "radius", void 0);
  48572. __decorate([
  48573. BABYLON.serializeAsVector3("target")
  48574. ], ArcRotateCamera.prototype, "_target", void 0);
  48575. __decorate([
  48576. BABYLON.serialize()
  48577. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48578. __decorate([
  48579. BABYLON.serialize()
  48580. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48581. __decorate([
  48582. BABYLON.serialize()
  48583. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48584. __decorate([
  48585. BABYLON.serialize()
  48586. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48587. __decorate([
  48588. BABYLON.serialize()
  48589. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48590. __decorate([
  48591. BABYLON.serialize()
  48592. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48593. __decorate([
  48594. BABYLON.serialize()
  48595. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48596. __decorate([
  48597. BABYLON.serialize()
  48598. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48599. __decorate([
  48600. BABYLON.serialize()
  48601. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48602. __decorate([
  48603. BABYLON.serialize()
  48604. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48605. __decorate([
  48606. BABYLON.serialize()
  48607. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48608. __decorate([
  48609. BABYLON.serialize()
  48610. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48611. __decorate([
  48612. BABYLON.serialize()
  48613. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48614. __decorate([
  48615. BABYLON.serializeAsVector3()
  48616. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48617. __decorate([
  48618. BABYLON.serialize()
  48619. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48620. __decorate([
  48621. BABYLON.serialize()
  48622. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48623. __decorate([
  48624. BABYLON.serialize()
  48625. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48626. return ArcRotateCamera;
  48627. }(BABYLON.TargetCamera));
  48628. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48629. })(BABYLON || (BABYLON = {}));
  48630. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48631. var BABYLON;
  48632. (function (BABYLON) {
  48633. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48634. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48635. });
  48636. /**
  48637. * The HemisphericLight simulates the ambient environment light,
  48638. * so the passed direction is the light reflection direction, not the incoming direction.
  48639. */
  48640. var HemisphericLight = /** @class */ (function (_super) {
  48641. __extends(HemisphericLight, _super);
  48642. /**
  48643. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48644. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48645. * The HemisphericLight can't cast shadows.
  48646. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48647. * @param name The friendly name of the light
  48648. * @param direction The direction of the light reflection
  48649. * @param scene The scene the light belongs to
  48650. */
  48651. function HemisphericLight(name, direction, scene) {
  48652. var _this = _super.call(this, name, scene) || this;
  48653. /**
  48654. * The groundColor is the light in the opposite direction to the one specified during creation.
  48655. * 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.
  48656. */
  48657. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48658. _this.direction = direction || BABYLON.Vector3.Up();
  48659. return _this;
  48660. }
  48661. HemisphericLight.prototype._buildUniformLayout = function () {
  48662. this._uniformBuffer.addUniform("vLightData", 4);
  48663. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48664. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48665. this._uniformBuffer.addUniform("vLightGround", 3);
  48666. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48667. this._uniformBuffer.addUniform("depthValues", 2);
  48668. this._uniformBuffer.create();
  48669. };
  48670. /**
  48671. * Returns the string "HemisphericLight".
  48672. * @return The class name
  48673. */
  48674. HemisphericLight.prototype.getClassName = function () {
  48675. return "HemisphericLight";
  48676. };
  48677. /**
  48678. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48679. * Returns the updated direction.
  48680. * @param target The target the direction should point to
  48681. * @return The computed direction
  48682. */
  48683. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48684. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48685. return this.direction;
  48686. };
  48687. /**
  48688. * Returns the shadow generator associated to the light.
  48689. * @returns Always null for hemispheric lights because it does not support shadows.
  48690. */
  48691. HemisphericLight.prototype.getShadowGenerator = function () {
  48692. return null;
  48693. };
  48694. /**
  48695. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48696. * @param effect The effect to update
  48697. * @param lightIndex The index of the light in the effect to update
  48698. * @returns The hemispheric light
  48699. */
  48700. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48701. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48702. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48703. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48704. return this;
  48705. };
  48706. /**
  48707. * @hidden internal use only.
  48708. */
  48709. HemisphericLight.prototype._getWorldMatrix = function () {
  48710. if (!this._worldMatrix) {
  48711. this._worldMatrix = BABYLON.Matrix.Identity();
  48712. }
  48713. return this._worldMatrix;
  48714. };
  48715. /**
  48716. * Returns the integer 3.
  48717. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48718. */
  48719. HemisphericLight.prototype.getTypeID = function () {
  48720. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48721. };
  48722. /**
  48723. * Prepares the list of defines specific to the light type.
  48724. * @param defines the list of defines
  48725. * @param lightIndex defines the index of the light for the effect
  48726. */
  48727. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48728. defines["HEMILIGHT" + lightIndex] = true;
  48729. };
  48730. __decorate([
  48731. BABYLON.serializeAsColor3()
  48732. ], HemisphericLight.prototype, "groundColor", void 0);
  48733. __decorate([
  48734. BABYLON.serializeAsVector3()
  48735. ], HemisphericLight.prototype, "direction", void 0);
  48736. return HemisphericLight;
  48737. }(BABYLON.Light));
  48738. BABYLON.HemisphericLight = HemisphericLight;
  48739. })(BABYLON || (BABYLON = {}));
  48740. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48741. var BABYLON;
  48742. (function (BABYLON) {
  48743. /**
  48744. * Base implementation IShadowLight
  48745. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48746. */
  48747. var ShadowLight = /** @class */ (function (_super) {
  48748. __extends(ShadowLight, _super);
  48749. function ShadowLight() {
  48750. var _this = _super !== null && _super.apply(this, arguments) || this;
  48751. _this._needProjectionMatrixCompute = true;
  48752. return _this;
  48753. }
  48754. ShadowLight.prototype._setPosition = function (value) {
  48755. this._position = value;
  48756. };
  48757. Object.defineProperty(ShadowLight.prototype, "position", {
  48758. /**
  48759. * Sets the position the shadow will be casted from. Also use as the light position for both
  48760. * point and spot lights.
  48761. */
  48762. get: function () {
  48763. return this._position;
  48764. },
  48765. /**
  48766. * Sets the position the shadow will be casted from. Also use as the light position for both
  48767. * point and spot lights.
  48768. */
  48769. set: function (value) {
  48770. this._setPosition(value);
  48771. },
  48772. enumerable: true,
  48773. configurable: true
  48774. });
  48775. ShadowLight.prototype._setDirection = function (value) {
  48776. this._direction = value;
  48777. };
  48778. Object.defineProperty(ShadowLight.prototype, "direction", {
  48779. /**
  48780. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48781. * Also use as the light direction on spot and directional lights.
  48782. */
  48783. get: function () {
  48784. return this._direction;
  48785. },
  48786. /**
  48787. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48788. * Also use as the light direction on spot and directional lights.
  48789. */
  48790. set: function (value) {
  48791. this._setDirection(value);
  48792. },
  48793. enumerable: true,
  48794. configurable: true
  48795. });
  48796. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48797. /**
  48798. * Gets the shadow projection clipping minimum z value.
  48799. */
  48800. get: function () {
  48801. return this._shadowMinZ;
  48802. },
  48803. /**
  48804. * Sets the shadow projection clipping minimum z value.
  48805. */
  48806. set: function (value) {
  48807. this._shadowMinZ = value;
  48808. this.forceProjectionMatrixCompute();
  48809. },
  48810. enumerable: true,
  48811. configurable: true
  48812. });
  48813. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48814. /**
  48815. * Sets the shadow projection clipping maximum z value.
  48816. */
  48817. get: function () {
  48818. return this._shadowMaxZ;
  48819. },
  48820. /**
  48821. * Gets the shadow projection clipping maximum z value.
  48822. */
  48823. set: function (value) {
  48824. this._shadowMaxZ = value;
  48825. this.forceProjectionMatrixCompute();
  48826. },
  48827. enumerable: true,
  48828. configurable: true
  48829. });
  48830. /**
  48831. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48832. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48833. */
  48834. ShadowLight.prototype.computeTransformedInformation = function () {
  48835. if (this.parent && this.parent.getWorldMatrix) {
  48836. if (!this.transformedPosition) {
  48837. this.transformedPosition = BABYLON.Vector3.Zero();
  48838. }
  48839. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48840. // In case the direction is present.
  48841. if (this.direction) {
  48842. if (!this.transformedDirection) {
  48843. this.transformedDirection = BABYLON.Vector3.Zero();
  48844. }
  48845. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48846. }
  48847. return true;
  48848. }
  48849. return false;
  48850. };
  48851. /**
  48852. * Return the depth scale used for the shadow map.
  48853. * @returns the depth scale.
  48854. */
  48855. ShadowLight.prototype.getDepthScale = function () {
  48856. return 50.0;
  48857. };
  48858. /**
  48859. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48860. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48861. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48862. */
  48863. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48864. return this.transformedDirection ? this.transformedDirection : this.direction;
  48865. };
  48866. /**
  48867. * Returns the ShadowLight absolute position in the World.
  48868. * @returns the position vector in world space
  48869. */
  48870. ShadowLight.prototype.getAbsolutePosition = function () {
  48871. return this.transformedPosition ? this.transformedPosition : this.position;
  48872. };
  48873. /**
  48874. * Sets the ShadowLight direction toward the passed target.
  48875. * @param target The point tot target in local space
  48876. * @returns the updated ShadowLight direction
  48877. */
  48878. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48879. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48880. return this.direction;
  48881. };
  48882. /**
  48883. * Returns the light rotation in euler definition.
  48884. * @returns the x y z rotation in local space.
  48885. */
  48886. ShadowLight.prototype.getRotation = function () {
  48887. this.direction.normalize();
  48888. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48889. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48890. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48891. };
  48892. /**
  48893. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48894. * @returns true if a cube texture needs to be use
  48895. */
  48896. ShadowLight.prototype.needCube = function () {
  48897. return false;
  48898. };
  48899. /**
  48900. * Detects if the projection matrix requires to be recomputed this frame.
  48901. * @returns true if it requires to be recomputed otherwise, false.
  48902. */
  48903. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48904. return this._needProjectionMatrixCompute;
  48905. };
  48906. /**
  48907. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48908. */
  48909. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48910. this._needProjectionMatrixCompute = true;
  48911. };
  48912. /**
  48913. * Get the world matrix of the sahdow lights.
  48914. * @hidden Internal Use Only
  48915. */
  48916. ShadowLight.prototype._getWorldMatrix = function () {
  48917. if (!this._worldMatrix) {
  48918. this._worldMatrix = BABYLON.Matrix.Identity();
  48919. }
  48920. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48921. return this._worldMatrix;
  48922. };
  48923. /**
  48924. * Gets the minZ used for shadow according to both the scene and the light.
  48925. * @param activeCamera The camera we are returning the min for
  48926. * @returns the depth min z
  48927. */
  48928. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48929. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48930. };
  48931. /**
  48932. * Gets the maxZ used for shadow according to both the scene and the light.
  48933. * @param activeCamera The camera we are returning the max for
  48934. * @returns the depth max z
  48935. */
  48936. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48937. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48938. };
  48939. /**
  48940. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48941. * @param matrix The materix to updated with the projection information
  48942. * @param viewMatrix The transform matrix of the light
  48943. * @param renderList The list of mesh to render in the map
  48944. * @returns The current light
  48945. */
  48946. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48947. if (this.customProjectionMatrixBuilder) {
  48948. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48949. }
  48950. else {
  48951. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48952. }
  48953. return this;
  48954. };
  48955. __decorate([
  48956. BABYLON.serializeAsVector3()
  48957. ], ShadowLight.prototype, "position", null);
  48958. __decorate([
  48959. BABYLON.serializeAsVector3()
  48960. ], ShadowLight.prototype, "direction", null);
  48961. __decorate([
  48962. BABYLON.serialize()
  48963. ], ShadowLight.prototype, "shadowMinZ", null);
  48964. __decorate([
  48965. BABYLON.serialize()
  48966. ], ShadowLight.prototype, "shadowMaxZ", null);
  48967. return ShadowLight;
  48968. }(BABYLON.Light));
  48969. BABYLON.ShadowLight = ShadowLight;
  48970. })(BABYLON || (BABYLON = {}));
  48971. //# sourceMappingURL=babylon.shadowLight.js.map
  48972. var BABYLON;
  48973. (function (BABYLON) {
  48974. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48975. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48976. });
  48977. /**
  48978. * A point light is a light defined by an unique point in world space.
  48979. * The light is emitted in every direction from this point.
  48980. * A good example of a point light is a standard light bulb.
  48981. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48982. */
  48983. var PointLight = /** @class */ (function (_super) {
  48984. __extends(PointLight, _super);
  48985. /**
  48986. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48987. * A PointLight emits the light in every direction.
  48988. * It can cast shadows.
  48989. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48990. * ```javascript
  48991. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48992. * ```
  48993. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48994. * @param name The light friendly name
  48995. * @param position The position of the point light in the scene
  48996. * @param scene The scene the lights belongs to
  48997. */
  48998. function PointLight(name, position, scene) {
  48999. var _this = _super.call(this, name, scene) || this;
  49000. _this._shadowAngle = Math.PI / 2;
  49001. _this.position = position;
  49002. return _this;
  49003. }
  49004. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49005. /**
  49006. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49007. * This specifies what angle the shadow will use to be created.
  49008. *
  49009. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49010. */
  49011. get: function () {
  49012. return this._shadowAngle;
  49013. },
  49014. /**
  49015. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49016. * This specifies what angle the shadow will use to be created.
  49017. *
  49018. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49019. */
  49020. set: function (value) {
  49021. this._shadowAngle = value;
  49022. this.forceProjectionMatrixCompute();
  49023. },
  49024. enumerable: true,
  49025. configurable: true
  49026. });
  49027. Object.defineProperty(PointLight.prototype, "direction", {
  49028. /**
  49029. * Gets the direction if it has been set.
  49030. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49031. */
  49032. get: function () {
  49033. return this._direction;
  49034. },
  49035. /**
  49036. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49037. */
  49038. set: function (value) {
  49039. var previousNeedCube = this.needCube();
  49040. this._direction = value;
  49041. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49042. this._shadowGenerator.recreateShadowMap();
  49043. }
  49044. },
  49045. enumerable: true,
  49046. configurable: true
  49047. });
  49048. /**
  49049. * Returns the string "PointLight"
  49050. * @returns the class name
  49051. */
  49052. PointLight.prototype.getClassName = function () {
  49053. return "PointLight";
  49054. };
  49055. /**
  49056. * Returns the integer 0.
  49057. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49058. */
  49059. PointLight.prototype.getTypeID = function () {
  49060. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49061. };
  49062. /**
  49063. * Specifies wether or not the shadowmap should be a cube texture.
  49064. * @returns true if the shadowmap needs to be a cube texture.
  49065. */
  49066. PointLight.prototype.needCube = function () {
  49067. return !this.direction;
  49068. };
  49069. /**
  49070. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49071. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49072. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49073. */
  49074. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49075. if (this.direction) {
  49076. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49077. }
  49078. else {
  49079. switch (faceIndex) {
  49080. case 0:
  49081. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49082. case 1:
  49083. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49084. case 2:
  49085. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49086. case 3:
  49087. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49088. case 4:
  49089. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49090. case 5:
  49091. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49092. }
  49093. }
  49094. return BABYLON.Vector3.Zero();
  49095. };
  49096. /**
  49097. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49098. * - fov = PI / 2
  49099. * - aspect ratio : 1.0
  49100. * - z-near and far equal to the active camera minZ and maxZ.
  49101. * Returns the PointLight.
  49102. */
  49103. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49104. var activeCamera = this.getScene().activeCamera;
  49105. if (!activeCamera) {
  49106. return;
  49107. }
  49108. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49109. };
  49110. PointLight.prototype._buildUniformLayout = function () {
  49111. this._uniformBuffer.addUniform("vLightData", 4);
  49112. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49113. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49114. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49115. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49116. this._uniformBuffer.addUniform("depthValues", 2);
  49117. this._uniformBuffer.create();
  49118. };
  49119. /**
  49120. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49121. * @param effect The effect to update
  49122. * @param lightIndex The index of the light in the effect to update
  49123. * @returns The point light
  49124. */
  49125. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49126. if (this.computeTransformedInformation()) {
  49127. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49128. }
  49129. else {
  49130. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49131. }
  49132. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49133. return this;
  49134. };
  49135. /**
  49136. * Prepares the list of defines specific to the light type.
  49137. * @param defines the list of defines
  49138. * @param lightIndex defines the index of the light for the effect
  49139. */
  49140. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49141. defines["POINTLIGHT" + lightIndex] = true;
  49142. };
  49143. __decorate([
  49144. BABYLON.serialize()
  49145. ], PointLight.prototype, "shadowAngle", null);
  49146. return PointLight;
  49147. }(BABYLON.ShadowLight));
  49148. BABYLON.PointLight = PointLight;
  49149. })(BABYLON || (BABYLON = {}));
  49150. //# sourceMappingURL=babylon.pointLight.js.map
  49151. var BABYLON;
  49152. (function (BABYLON) {
  49153. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49154. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49155. });
  49156. /**
  49157. * A directional light is defined by a direction (what a surprise!).
  49158. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49159. * 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.
  49160. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49161. */
  49162. var DirectionalLight = /** @class */ (function (_super) {
  49163. __extends(DirectionalLight, _super);
  49164. /**
  49165. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49166. * The directional light is emitted from everywhere in the given direction.
  49167. * It can cast shawdows.
  49168. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49169. * @param name The friendly name of the light
  49170. * @param direction The direction of the light
  49171. * @param scene The scene the light belongs to
  49172. */
  49173. function DirectionalLight(name, direction, scene) {
  49174. var _this = _super.call(this, name, scene) || this;
  49175. _this._shadowFrustumSize = 0;
  49176. _this._shadowOrthoScale = 0.1;
  49177. /**
  49178. * Automatically compute the projection matrix to best fit (including all the casters)
  49179. * on each frame.
  49180. */
  49181. _this.autoUpdateExtends = true;
  49182. // Cache
  49183. _this._orthoLeft = Number.MAX_VALUE;
  49184. _this._orthoRight = Number.MIN_VALUE;
  49185. _this._orthoTop = Number.MIN_VALUE;
  49186. _this._orthoBottom = Number.MAX_VALUE;
  49187. _this.position = direction.scale(-1.0);
  49188. _this.direction = direction;
  49189. return _this;
  49190. }
  49191. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49192. /**
  49193. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49194. */
  49195. get: function () {
  49196. return this._shadowFrustumSize;
  49197. },
  49198. /**
  49199. * Specifies a fix frustum size for the shadow generation.
  49200. */
  49201. set: function (value) {
  49202. this._shadowFrustumSize = value;
  49203. this.forceProjectionMatrixCompute();
  49204. },
  49205. enumerable: true,
  49206. configurable: true
  49207. });
  49208. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49209. /**
  49210. * Gets the shadow projection scale against the optimal computed one.
  49211. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49212. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49213. */
  49214. get: function () {
  49215. return this._shadowOrthoScale;
  49216. },
  49217. /**
  49218. * Sets the shadow projection scale against the optimal computed one.
  49219. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49220. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49221. */
  49222. set: function (value) {
  49223. this._shadowOrthoScale = value;
  49224. this.forceProjectionMatrixCompute();
  49225. },
  49226. enumerable: true,
  49227. configurable: true
  49228. });
  49229. /**
  49230. * Returns the string "DirectionalLight".
  49231. * @return The class name
  49232. */
  49233. DirectionalLight.prototype.getClassName = function () {
  49234. return "DirectionalLight";
  49235. };
  49236. /**
  49237. * Returns the integer 1.
  49238. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49239. */
  49240. DirectionalLight.prototype.getTypeID = function () {
  49241. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49242. };
  49243. /**
  49244. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49245. * Returns the DirectionalLight Shadow projection matrix.
  49246. */
  49247. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49248. if (this.shadowFrustumSize > 0) {
  49249. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49250. }
  49251. else {
  49252. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49253. }
  49254. };
  49255. /**
  49256. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49257. * Returns the DirectionalLight Shadow projection matrix.
  49258. */
  49259. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49260. var activeCamera = this.getScene().activeCamera;
  49261. if (!activeCamera) {
  49262. return;
  49263. }
  49264. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49265. };
  49266. /**
  49267. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49268. * Returns the DirectionalLight Shadow projection matrix.
  49269. */
  49270. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49271. var activeCamera = this.getScene().activeCamera;
  49272. if (!activeCamera) {
  49273. return;
  49274. }
  49275. // Check extends
  49276. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49277. var tempVector3 = BABYLON.Vector3.Zero();
  49278. this._orthoLeft = Number.MAX_VALUE;
  49279. this._orthoRight = Number.MIN_VALUE;
  49280. this._orthoTop = Number.MIN_VALUE;
  49281. this._orthoBottom = Number.MAX_VALUE;
  49282. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49283. var mesh = renderList[meshIndex];
  49284. if (!mesh) {
  49285. continue;
  49286. }
  49287. var boundingInfo = mesh.getBoundingInfo();
  49288. var boundingBox = boundingInfo.boundingBox;
  49289. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49290. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49291. if (tempVector3.x < this._orthoLeft)
  49292. this._orthoLeft = tempVector3.x;
  49293. if (tempVector3.y < this._orthoBottom)
  49294. this._orthoBottom = tempVector3.y;
  49295. if (tempVector3.x > this._orthoRight)
  49296. this._orthoRight = tempVector3.x;
  49297. if (tempVector3.y > this._orthoTop)
  49298. this._orthoTop = tempVector3.y;
  49299. }
  49300. }
  49301. }
  49302. var xOffset = this._orthoRight - this._orthoLeft;
  49303. var yOffset = this._orthoTop - this._orthoBottom;
  49304. 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);
  49305. };
  49306. DirectionalLight.prototype._buildUniformLayout = function () {
  49307. this._uniformBuffer.addUniform("vLightData", 4);
  49308. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49309. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49310. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49311. this._uniformBuffer.addUniform("depthValues", 2);
  49312. this._uniformBuffer.create();
  49313. };
  49314. /**
  49315. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49316. * @param effect The effect to update
  49317. * @param lightIndex The index of the light in the effect to update
  49318. * @returns The directional light
  49319. */
  49320. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49321. if (this.computeTransformedInformation()) {
  49322. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49323. return this;
  49324. }
  49325. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49326. return this;
  49327. };
  49328. /**
  49329. * Gets the minZ used for shadow according to both the scene and the light.
  49330. *
  49331. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49332. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49333. * @param activeCamera The camera we are returning the min for
  49334. * @returns the depth min z
  49335. */
  49336. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49337. return 1;
  49338. };
  49339. /**
  49340. * Gets the maxZ used for shadow according to both the scene and the light.
  49341. *
  49342. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49343. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49344. * @param activeCamera The camera we are returning the max for
  49345. * @returns the depth max z
  49346. */
  49347. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49348. return 1;
  49349. };
  49350. /**
  49351. * Prepares the list of defines specific to the light type.
  49352. * @param defines the list of defines
  49353. * @param lightIndex defines the index of the light for the effect
  49354. */
  49355. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49356. defines["DIRLIGHT" + lightIndex] = true;
  49357. };
  49358. __decorate([
  49359. BABYLON.serialize()
  49360. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49361. __decorate([
  49362. BABYLON.serialize()
  49363. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49364. __decorate([
  49365. BABYLON.serialize()
  49366. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49367. return DirectionalLight;
  49368. }(BABYLON.ShadowLight));
  49369. BABYLON.DirectionalLight = DirectionalLight;
  49370. })(BABYLON || (BABYLON = {}));
  49371. //# sourceMappingURL=babylon.directionalLight.js.map
  49372. var BABYLON;
  49373. (function (BABYLON) {
  49374. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49375. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49376. });
  49377. /**
  49378. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49379. * These values define a cone of light starting from the position, emitting toward the direction.
  49380. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49381. * and the exponent defines the speed of the decay of the light with distance (reach).
  49382. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49383. */
  49384. var SpotLight = /** @class */ (function (_super) {
  49385. __extends(SpotLight, _super);
  49386. /**
  49387. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49388. * It can cast shadows.
  49389. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49390. * @param name The light friendly name
  49391. * @param position The position of the spot light in the scene
  49392. * @param direction The direction of the light in the scene
  49393. * @param angle The cone angle of the light in Radians
  49394. * @param exponent The light decay speed with the distance from the emission spot
  49395. * @param scene The scene the lights belongs to
  49396. */
  49397. function SpotLight(name, position, direction, angle, exponent, scene) {
  49398. var _this = _super.call(this, name, scene) || this;
  49399. _this._innerAngle = 0;
  49400. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49401. _this._projectionTextureLightNear = 1e-6;
  49402. _this._projectionTextureLightFar = 1000.0;
  49403. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49404. _this._projectionTextureViewLightDirty = true;
  49405. _this._projectionTextureProjectionLightDirty = true;
  49406. _this._projectionTextureDirty = true;
  49407. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49408. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49409. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49410. _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);
  49411. _this.position = position;
  49412. _this.direction = direction;
  49413. _this.angle = angle;
  49414. _this.exponent = exponent;
  49415. return _this;
  49416. }
  49417. Object.defineProperty(SpotLight.prototype, "angle", {
  49418. /**
  49419. * Gets the cone angle of the spot light in Radians.
  49420. */
  49421. get: function () {
  49422. return this._angle;
  49423. },
  49424. /**
  49425. * Sets the cone angle of the spot light in Radians.
  49426. */
  49427. set: function (value) {
  49428. this._angle = value;
  49429. this._cosHalfAngle = Math.cos(value * 0.5);
  49430. this._projectionTextureProjectionLightDirty = true;
  49431. this.forceProjectionMatrixCompute();
  49432. this._computeAngleValues();
  49433. },
  49434. enumerable: true,
  49435. configurable: true
  49436. });
  49437. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49438. /**
  49439. * Only used in gltf falloff mode, this defines the angle where
  49440. * the directional falloff will start before cutting at angle which could be seen
  49441. * as outer angle.
  49442. */
  49443. get: function () {
  49444. return this._angle;
  49445. },
  49446. /**
  49447. * Only used in gltf falloff mode, this defines the angle where
  49448. * the directional falloff will start before cutting at angle which could be seen
  49449. * as outer angle.
  49450. */
  49451. set: function (value) {
  49452. this._innerAngle = value;
  49453. this._computeAngleValues();
  49454. },
  49455. enumerable: true,
  49456. configurable: true
  49457. });
  49458. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49459. /**
  49460. * Allows scaling the angle of the light for shadow generation only.
  49461. */
  49462. get: function () {
  49463. return this._shadowAngleScale;
  49464. },
  49465. /**
  49466. * Allows scaling the angle of the light for shadow generation only.
  49467. */
  49468. set: function (value) {
  49469. this._shadowAngleScale = value;
  49470. this.forceProjectionMatrixCompute();
  49471. },
  49472. enumerable: true,
  49473. configurable: true
  49474. });
  49475. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49476. /**
  49477. * Allows reading the projecton texture
  49478. */
  49479. get: function () {
  49480. return this._projectionTextureMatrix;
  49481. },
  49482. enumerable: true,
  49483. configurable: true
  49484. });
  49485. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49486. /**
  49487. * Gets the near clip of the Spotlight for texture projection.
  49488. */
  49489. get: function () {
  49490. return this._projectionTextureLightNear;
  49491. },
  49492. /**
  49493. * Sets the near clip of the Spotlight for texture projection.
  49494. */
  49495. set: function (value) {
  49496. this._projectionTextureLightNear = value;
  49497. this._projectionTextureProjectionLightDirty = true;
  49498. },
  49499. enumerable: true,
  49500. configurable: true
  49501. });
  49502. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49503. /**
  49504. * Gets the far clip of the Spotlight for texture projection.
  49505. */
  49506. get: function () {
  49507. return this._projectionTextureLightFar;
  49508. },
  49509. /**
  49510. * Sets the far clip of the Spotlight for texture projection.
  49511. */
  49512. set: function (value) {
  49513. this._projectionTextureLightFar = value;
  49514. this._projectionTextureProjectionLightDirty = true;
  49515. },
  49516. enumerable: true,
  49517. configurable: true
  49518. });
  49519. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49520. /**
  49521. * Gets the Up vector of the Spotlight for texture projection.
  49522. */
  49523. get: function () {
  49524. return this._projectionTextureUpDirection;
  49525. },
  49526. /**
  49527. * Sets the Up vector of the Spotlight for texture projection.
  49528. */
  49529. set: function (value) {
  49530. this._projectionTextureUpDirection = value;
  49531. this._projectionTextureProjectionLightDirty = true;
  49532. },
  49533. enumerable: true,
  49534. configurable: true
  49535. });
  49536. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49537. /**
  49538. * Gets the projection texture of the light.
  49539. */
  49540. get: function () {
  49541. return this._projectionTexture;
  49542. },
  49543. /**
  49544. * Sets the projection texture of the light.
  49545. */
  49546. set: function (value) {
  49547. this._projectionTexture = value;
  49548. this._projectionTextureDirty = true;
  49549. },
  49550. enumerable: true,
  49551. configurable: true
  49552. });
  49553. /**
  49554. * Returns the string "SpotLight".
  49555. * @returns the class name
  49556. */
  49557. SpotLight.prototype.getClassName = function () {
  49558. return "SpotLight";
  49559. };
  49560. /**
  49561. * Returns the integer 2.
  49562. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49563. */
  49564. SpotLight.prototype.getTypeID = function () {
  49565. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49566. };
  49567. /**
  49568. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49569. */
  49570. SpotLight.prototype._setDirection = function (value) {
  49571. _super.prototype._setDirection.call(this, value);
  49572. this._projectionTextureViewLightDirty = true;
  49573. };
  49574. /**
  49575. * Overrides the position setter to recompute the projection texture view light Matrix.
  49576. */
  49577. SpotLight.prototype._setPosition = function (value) {
  49578. _super.prototype._setPosition.call(this, value);
  49579. this._projectionTextureViewLightDirty = true;
  49580. };
  49581. /**
  49582. * 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.
  49583. * Returns the SpotLight.
  49584. */
  49585. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49586. var activeCamera = this.getScene().activeCamera;
  49587. if (!activeCamera) {
  49588. return;
  49589. }
  49590. this._shadowAngleScale = this._shadowAngleScale || 1;
  49591. var angle = this._shadowAngleScale * this._angle;
  49592. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49593. };
  49594. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49595. this._projectionTextureViewLightDirty = false;
  49596. this._projectionTextureDirty = true;
  49597. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49598. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49599. };
  49600. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49601. this._projectionTextureProjectionLightDirty = false;
  49602. this._projectionTextureDirty = true;
  49603. var light_far = this.projectionTextureLightFar;
  49604. var light_near = this.projectionTextureLightNear;
  49605. var P = light_far / (light_far - light_near);
  49606. var Q = -P * light_near;
  49607. var S = 1.0 / Math.tan(this._angle / 2.0);
  49608. var A = 1.0;
  49609. 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);
  49610. };
  49611. /**
  49612. * Main function for light texture projection matrix computing.
  49613. */
  49614. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49615. this._projectionTextureDirty = false;
  49616. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49617. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49618. };
  49619. SpotLight.prototype._buildUniformLayout = function () {
  49620. this._uniformBuffer.addUniform("vLightData", 4);
  49621. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49622. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49623. this._uniformBuffer.addUniform("vLightDirection", 3);
  49624. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49625. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49626. this._uniformBuffer.addUniform("depthValues", 2);
  49627. this._uniformBuffer.create();
  49628. };
  49629. SpotLight.prototype._computeAngleValues = function () {
  49630. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49631. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49632. };
  49633. /**
  49634. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49635. * @param effect The effect to update
  49636. * @param lightIndex The index of the light in the effect to update
  49637. * @returns The spot light
  49638. */
  49639. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49640. var normalizeDirection;
  49641. if (this.computeTransformedInformation()) {
  49642. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49643. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49644. }
  49645. else {
  49646. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49647. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49648. }
  49649. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49650. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49651. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49652. if (this._projectionTextureViewLightDirty) {
  49653. this._computeProjectionTextureViewLightMatrix();
  49654. }
  49655. if (this._projectionTextureProjectionLightDirty) {
  49656. this._computeProjectionTextureProjectionLightMatrix();
  49657. }
  49658. if (this._projectionTextureDirty) {
  49659. this._computeProjectionTextureMatrix();
  49660. }
  49661. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49662. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49663. }
  49664. return this;
  49665. };
  49666. /**
  49667. * Disposes the light and the associated resources.
  49668. */
  49669. SpotLight.prototype.dispose = function () {
  49670. _super.prototype.dispose.call(this);
  49671. if (this._projectionTexture) {
  49672. this._projectionTexture.dispose();
  49673. }
  49674. };
  49675. /**
  49676. * Prepares the list of defines specific to the light type.
  49677. * @param defines the list of defines
  49678. * @param lightIndex defines the index of the light for the effect
  49679. */
  49680. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49681. defines["SPOTLIGHT" + lightIndex] = true;
  49682. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49683. };
  49684. __decorate([
  49685. BABYLON.serialize()
  49686. ], SpotLight.prototype, "angle", null);
  49687. __decorate([
  49688. BABYLON.serialize()
  49689. ], SpotLight.prototype, "innerAngle", null);
  49690. __decorate([
  49691. BABYLON.serialize()
  49692. ], SpotLight.prototype, "shadowAngleScale", null);
  49693. __decorate([
  49694. BABYLON.serialize()
  49695. ], SpotLight.prototype, "exponent", void 0);
  49696. __decorate([
  49697. BABYLON.serialize()
  49698. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49699. __decorate([
  49700. BABYLON.serialize()
  49701. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49702. __decorate([
  49703. BABYLON.serialize()
  49704. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49705. __decorate([
  49706. BABYLON.serializeAsTexture("projectedLightTexture")
  49707. ], SpotLight.prototype, "_projectionTexture", void 0);
  49708. return SpotLight;
  49709. }(BABYLON.ShadowLight));
  49710. BABYLON.SpotLight = SpotLight;
  49711. })(BABYLON || (BABYLON = {}));
  49712. //# sourceMappingURL=babylon.spotLight.js.map
  49713. var BABYLON;
  49714. (function (BABYLON) {
  49715. /**
  49716. * Class used to override all child animations of a given target
  49717. */
  49718. var AnimationPropertiesOverride = /** @class */ (function () {
  49719. function AnimationPropertiesOverride() {
  49720. /**
  49721. * Gets or sets a value indicating if animation blending must be used
  49722. */
  49723. this.enableBlending = false;
  49724. /**
  49725. * Gets or sets the blending speed to use when enableBlending is true
  49726. */
  49727. this.blendingSpeed = 0.01;
  49728. /**
  49729. * Gets or sets the default loop mode to use
  49730. */
  49731. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49732. }
  49733. return AnimationPropertiesOverride;
  49734. }());
  49735. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49736. })(BABYLON || (BABYLON = {}));
  49737. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49738. var BABYLON;
  49739. (function (BABYLON) {
  49740. /**
  49741. * Represents the range of an animation
  49742. */
  49743. var AnimationRange = /** @class */ (function () {
  49744. /**
  49745. * Initializes the range of an animation
  49746. * @param name The name of the animation range
  49747. * @param from The starting frame of the animation
  49748. * @param to The ending frame of the animation
  49749. */
  49750. function AnimationRange(
  49751. /**The name of the animation range**/
  49752. name,
  49753. /**The starting frame of the animation */
  49754. from,
  49755. /**The ending frame of the animation*/
  49756. to) {
  49757. this.name = name;
  49758. this.from = from;
  49759. this.to = to;
  49760. }
  49761. /**
  49762. * Makes a copy of the animation range
  49763. * @returns A copy of the animation range
  49764. */
  49765. AnimationRange.prototype.clone = function () {
  49766. return new AnimationRange(this.name, this.from, this.to);
  49767. };
  49768. return AnimationRange;
  49769. }());
  49770. BABYLON.AnimationRange = AnimationRange;
  49771. /**
  49772. * Composed of a frame, and an action function
  49773. */
  49774. var AnimationEvent = /** @class */ (function () {
  49775. /**
  49776. * Initializes the animation event
  49777. * @param frame The frame for which the event is triggered
  49778. * @param action The event to perform when triggered
  49779. * @param onlyOnce Specifies if the event should be triggered only once
  49780. */
  49781. function AnimationEvent(
  49782. /** The frame for which the event is triggered **/
  49783. frame,
  49784. /** The event to perform when triggered **/
  49785. action,
  49786. /** Specifies if the event should be triggered only once**/
  49787. onlyOnce) {
  49788. this.frame = frame;
  49789. this.action = action;
  49790. this.onlyOnce = onlyOnce;
  49791. /**
  49792. * Specifies if the animation event is done
  49793. */
  49794. this.isDone = false;
  49795. }
  49796. /** @hidden */
  49797. AnimationEvent.prototype._clone = function () {
  49798. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49799. };
  49800. return AnimationEvent;
  49801. }());
  49802. BABYLON.AnimationEvent = AnimationEvent;
  49803. /**
  49804. * A cursor which tracks a point on a path
  49805. */
  49806. var PathCursor = /** @class */ (function () {
  49807. /**
  49808. * Initializes the path cursor
  49809. * @param path The path to track
  49810. */
  49811. function PathCursor(path) {
  49812. this.path = path;
  49813. /**
  49814. * Stores path cursor callbacks for when an onchange event is triggered
  49815. */
  49816. this._onchange = new Array();
  49817. /**
  49818. * The value of the path cursor
  49819. */
  49820. this.value = 0;
  49821. /**
  49822. * The animation array of the path cursor
  49823. */
  49824. this.animations = new Array();
  49825. }
  49826. /**
  49827. * Gets the cursor point on the path
  49828. * @returns A point on the path cursor at the cursor location
  49829. */
  49830. PathCursor.prototype.getPoint = function () {
  49831. var point = this.path.getPointAtLengthPosition(this.value);
  49832. return new BABYLON.Vector3(point.x, 0, point.y);
  49833. };
  49834. /**
  49835. * Moves the cursor ahead by the step amount
  49836. * @param step The amount to move the cursor forward
  49837. * @returns This path cursor
  49838. */
  49839. PathCursor.prototype.moveAhead = function (step) {
  49840. if (step === void 0) { step = 0.002; }
  49841. this.move(step);
  49842. return this;
  49843. };
  49844. /**
  49845. * Moves the cursor behind by the step amount
  49846. * @param step The amount to move the cursor back
  49847. * @returns This path cursor
  49848. */
  49849. PathCursor.prototype.moveBack = function (step) {
  49850. if (step === void 0) { step = 0.002; }
  49851. this.move(-step);
  49852. return this;
  49853. };
  49854. /**
  49855. * Moves the cursor by the step amount
  49856. * If the step amount is greater than one, an exception is thrown
  49857. * @param step The amount to move the cursor
  49858. * @returns This path cursor
  49859. */
  49860. PathCursor.prototype.move = function (step) {
  49861. if (Math.abs(step) > 1) {
  49862. throw "step size should be less than 1.";
  49863. }
  49864. this.value += step;
  49865. this.ensureLimits();
  49866. this.raiseOnChange();
  49867. return this;
  49868. };
  49869. /**
  49870. * Ensures that the value is limited between zero and one
  49871. * @returns This path cursor
  49872. */
  49873. PathCursor.prototype.ensureLimits = function () {
  49874. while (this.value > 1) {
  49875. this.value -= 1;
  49876. }
  49877. while (this.value < 0) {
  49878. this.value += 1;
  49879. }
  49880. return this;
  49881. };
  49882. /**
  49883. * Runs onchange callbacks on change (used by the animation engine)
  49884. * @returns This path cursor
  49885. */
  49886. PathCursor.prototype.raiseOnChange = function () {
  49887. var _this = this;
  49888. this._onchange.forEach(function (f) { return f(_this); });
  49889. return this;
  49890. };
  49891. /**
  49892. * Executes a function on change
  49893. * @param f A path cursor onchange callback
  49894. * @returns This path cursor
  49895. */
  49896. PathCursor.prototype.onchange = function (f) {
  49897. this._onchange.push(f);
  49898. return this;
  49899. };
  49900. return PathCursor;
  49901. }());
  49902. BABYLON.PathCursor = PathCursor;
  49903. /**
  49904. * Enum for the animation key frame interpolation type
  49905. */
  49906. var AnimationKeyInterpolation;
  49907. (function (AnimationKeyInterpolation) {
  49908. /**
  49909. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49910. */
  49911. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49912. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49913. /**
  49914. * Class used to store any kind of animation
  49915. */
  49916. var Animation = /** @class */ (function () {
  49917. /**
  49918. * Initializes the animation
  49919. * @param name Name of the animation
  49920. * @param targetProperty Property to animate
  49921. * @param framePerSecond The frames per second of the animation
  49922. * @param dataType The data type of the animation
  49923. * @param loopMode The loop mode of the animation
  49924. * @param enableBlendings Specifies if blending should be enabled
  49925. */
  49926. function Animation(
  49927. /**Name of the animation */
  49928. name,
  49929. /**Property to animate */
  49930. targetProperty,
  49931. /**The frames per second of the animation */
  49932. framePerSecond,
  49933. /**The data type of the animation */
  49934. dataType,
  49935. /**The loop mode of the animation */
  49936. loopMode,
  49937. /**Specifies if blending should be enabled */
  49938. enableBlending) {
  49939. this.name = name;
  49940. this.targetProperty = targetProperty;
  49941. this.framePerSecond = framePerSecond;
  49942. this.dataType = dataType;
  49943. this.loopMode = loopMode;
  49944. this.enableBlending = enableBlending;
  49945. /**
  49946. * @hidden Internal use only
  49947. */
  49948. this._runtimeAnimations = new Array();
  49949. /**
  49950. * The set of event that will be linked to this animation
  49951. */
  49952. this._events = new Array();
  49953. /**
  49954. * Stores the blending speed of the animation
  49955. */
  49956. this.blendingSpeed = 0.01;
  49957. /**
  49958. * Stores the animation ranges for the animation
  49959. */
  49960. this._ranges = {};
  49961. this.targetPropertyPath = targetProperty.split(".");
  49962. this.dataType = dataType;
  49963. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49964. }
  49965. /**
  49966. * @hidden Internal use
  49967. */
  49968. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49969. var dataType = undefined;
  49970. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49971. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49972. }
  49973. else if (from instanceof BABYLON.Quaternion) {
  49974. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49975. }
  49976. else if (from instanceof BABYLON.Vector3) {
  49977. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49978. }
  49979. else if (from instanceof BABYLON.Vector2) {
  49980. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49981. }
  49982. else if (from instanceof BABYLON.Color3) {
  49983. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49984. }
  49985. else if (from instanceof BABYLON.Size) {
  49986. dataType = Animation.ANIMATIONTYPE_SIZE;
  49987. }
  49988. if (dataType == undefined) {
  49989. return null;
  49990. }
  49991. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49992. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49993. animation.setKeys(keys);
  49994. if (easingFunction !== undefined) {
  49995. animation.setEasingFunction(easingFunction);
  49996. }
  49997. return animation;
  49998. };
  49999. /**
  50000. * Sets up an animation
  50001. * @param property The property to animate
  50002. * @param animationType The animation type to apply
  50003. * @param framePerSecond The frames per second of the animation
  50004. * @param easingFunction The easing function used in the animation
  50005. * @returns The created animation
  50006. */
  50007. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50008. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50009. animation.setEasingFunction(easingFunction);
  50010. return animation;
  50011. };
  50012. /**
  50013. * Create and start an animation on a node
  50014. * @param name defines the name of the global animation that will be run on all nodes
  50015. * @param node defines the root node where the animation will take place
  50016. * @param targetProperty defines property to animate
  50017. * @param framePerSecond defines the number of frame per second yo use
  50018. * @param totalFrame defines the number of frames in total
  50019. * @param from defines the initial value
  50020. * @param to defines the final value
  50021. * @param loopMode defines which loop mode you want to use (off by default)
  50022. * @param easingFunction defines the easing function to use (linear by default)
  50023. * @param onAnimationEnd defines the callback to call when animation end
  50024. * @returns the animatable created for this animation
  50025. */
  50026. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50027. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50028. if (!animation) {
  50029. return null;
  50030. }
  50031. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50032. };
  50033. /**
  50034. * Create and start an animation on a node and its descendants
  50035. * @param name defines the name of the global animation that will be run on all nodes
  50036. * @param node defines the root node where the animation will take place
  50037. * @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
  50038. * @param targetProperty defines property to animate
  50039. * @param framePerSecond defines the number of frame per second to use
  50040. * @param totalFrame defines the number of frames in total
  50041. * @param from defines the initial value
  50042. * @param to defines the final value
  50043. * @param loopMode defines which loop mode you want to use (off by default)
  50044. * @param easingFunction defines the easing function to use (linear by default)
  50045. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50046. * @returns the list of animatables created for all nodes
  50047. * @example https://www.babylonjs-playground.com/#MH0VLI
  50048. */
  50049. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50050. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50051. if (!animation) {
  50052. return null;
  50053. }
  50054. var scene = node.getScene();
  50055. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50056. };
  50057. /**
  50058. * Creates a new animation, merges it with the existing animations and starts it
  50059. * @param name Name of the animation
  50060. * @param node Node which contains the scene that begins the animations
  50061. * @param targetProperty Specifies which property to animate
  50062. * @param framePerSecond The frames per second of the animation
  50063. * @param totalFrame The total number of frames
  50064. * @param from The frame at the beginning of the animation
  50065. * @param to The frame at the end of the animation
  50066. * @param loopMode Specifies the loop mode of the animation
  50067. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50068. * @param onAnimationEnd Callback to run once the animation is complete
  50069. * @returns Nullable animation
  50070. */
  50071. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50072. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50073. if (!animation) {
  50074. return null;
  50075. }
  50076. node.animations.push(animation);
  50077. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50078. };
  50079. /**
  50080. * Transition property of an host to the target Value
  50081. * @param property The property to transition
  50082. * @param targetValue The target Value of the property
  50083. * @param host The object where the property to animate belongs
  50084. * @param scene Scene used to run the animation
  50085. * @param frameRate Framerate (in frame/s) to use
  50086. * @param transition The transition type we want to use
  50087. * @param duration The duration of the animation, in milliseconds
  50088. * @param onAnimationEnd Callback trigger at the end of the animation
  50089. * @returns Nullable animation
  50090. */
  50091. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50092. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50093. if (duration <= 0) {
  50094. host[property] = targetValue;
  50095. if (onAnimationEnd) {
  50096. onAnimationEnd();
  50097. }
  50098. return null;
  50099. }
  50100. var endFrame = frameRate * (duration / 1000);
  50101. transition.setKeys([{
  50102. frame: 0,
  50103. value: host[property].clone ? host[property].clone() : host[property]
  50104. },
  50105. {
  50106. frame: endFrame,
  50107. value: targetValue
  50108. }]);
  50109. if (!host.animations) {
  50110. host.animations = [];
  50111. }
  50112. host.animations.push(transition);
  50113. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50114. animation.onAnimationEnd = onAnimationEnd;
  50115. return animation;
  50116. };
  50117. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50118. /**
  50119. * Return the array of runtime animations currently using this animation
  50120. */
  50121. get: function () {
  50122. return this._runtimeAnimations;
  50123. },
  50124. enumerable: true,
  50125. configurable: true
  50126. });
  50127. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50128. /**
  50129. * Specifies if any of the runtime animations are currently running
  50130. */
  50131. get: function () {
  50132. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50133. var runtimeAnimation = _a[_i];
  50134. if (!runtimeAnimation.isStopped) {
  50135. return true;
  50136. }
  50137. }
  50138. return false;
  50139. },
  50140. enumerable: true,
  50141. configurable: true
  50142. });
  50143. // Methods
  50144. /**
  50145. * Converts the animation to a string
  50146. * @param fullDetails support for multiple levels of logging within scene loading
  50147. * @returns String form of the animation
  50148. */
  50149. Animation.prototype.toString = function (fullDetails) {
  50150. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50151. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50152. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50153. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50154. if (fullDetails) {
  50155. ret += ", Ranges: {";
  50156. var first = true;
  50157. for (var name in this._ranges) {
  50158. if (first) {
  50159. ret += ", ";
  50160. first = false;
  50161. }
  50162. ret += name;
  50163. }
  50164. ret += "}";
  50165. }
  50166. return ret;
  50167. };
  50168. /**
  50169. * Add an event to this animation
  50170. * @param event Event to add
  50171. */
  50172. Animation.prototype.addEvent = function (event) {
  50173. this._events.push(event);
  50174. };
  50175. /**
  50176. * Remove all events found at the given frame
  50177. * @param frame The frame to remove events from
  50178. */
  50179. Animation.prototype.removeEvents = function (frame) {
  50180. for (var index = 0; index < this._events.length; index++) {
  50181. if (this._events[index].frame === frame) {
  50182. this._events.splice(index, 1);
  50183. index--;
  50184. }
  50185. }
  50186. };
  50187. /**
  50188. * Retrieves all the events from the animation
  50189. * @returns Events from the animation
  50190. */
  50191. Animation.prototype.getEvents = function () {
  50192. return this._events;
  50193. };
  50194. /**
  50195. * Creates an animation range
  50196. * @param name Name of the animation range
  50197. * @param from Starting frame of the animation range
  50198. * @param to Ending frame of the animation
  50199. */
  50200. Animation.prototype.createRange = function (name, from, to) {
  50201. // check name not already in use; could happen for bones after serialized
  50202. if (!this._ranges[name]) {
  50203. this._ranges[name] = new AnimationRange(name, from, to);
  50204. }
  50205. };
  50206. /**
  50207. * Deletes an animation range by name
  50208. * @param name Name of the animation range to delete
  50209. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50210. */
  50211. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50212. if (deleteFrames === void 0) { deleteFrames = true; }
  50213. var range = this._ranges[name];
  50214. if (!range) {
  50215. return;
  50216. }
  50217. if (deleteFrames) {
  50218. var from = range.from;
  50219. var to = range.to;
  50220. // this loop MUST go high to low for multiple splices to work
  50221. for (var key = this._keys.length - 1; key >= 0; key--) {
  50222. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50223. this._keys.splice(key, 1);
  50224. }
  50225. }
  50226. }
  50227. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50228. };
  50229. /**
  50230. * Gets the animation range by name, or null if not defined
  50231. * @param name Name of the animation range
  50232. * @returns Nullable animation range
  50233. */
  50234. Animation.prototype.getRange = function (name) {
  50235. return this._ranges[name];
  50236. };
  50237. /**
  50238. * Gets the key frames from the animation
  50239. * @returns The key frames of the animation
  50240. */
  50241. Animation.prototype.getKeys = function () {
  50242. return this._keys;
  50243. };
  50244. /**
  50245. * Gets the highest frame rate of the animation
  50246. * @returns Highest frame rate of the animation
  50247. */
  50248. Animation.prototype.getHighestFrame = function () {
  50249. var ret = 0;
  50250. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50251. if (ret < this._keys[key].frame) {
  50252. ret = this._keys[key].frame;
  50253. }
  50254. }
  50255. return ret;
  50256. };
  50257. /**
  50258. * Gets the easing function of the animation
  50259. * @returns Easing function of the animation
  50260. */
  50261. Animation.prototype.getEasingFunction = function () {
  50262. return this._easingFunction;
  50263. };
  50264. /**
  50265. * Sets the easing function of the animation
  50266. * @param easingFunction A custom mathematical formula for animation
  50267. */
  50268. Animation.prototype.setEasingFunction = function (easingFunction) {
  50269. this._easingFunction = easingFunction;
  50270. };
  50271. /**
  50272. * Interpolates a scalar linearly
  50273. * @param startValue Start value of the animation curve
  50274. * @param endValue End value of the animation curve
  50275. * @param gradient Scalar amount to interpolate
  50276. * @returns Interpolated scalar value
  50277. */
  50278. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50279. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50280. };
  50281. /**
  50282. * Interpolates a scalar cubically
  50283. * @param startValue Start value of the animation curve
  50284. * @param outTangent End tangent of the animation
  50285. * @param endValue End value of the animation curve
  50286. * @param inTangent Start tangent of the animation curve
  50287. * @param gradient Scalar amount to interpolate
  50288. * @returns Interpolated scalar value
  50289. */
  50290. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50291. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50292. };
  50293. /**
  50294. * Interpolates a quaternion using a spherical linear interpolation
  50295. * @param startValue Start value of the animation curve
  50296. * @param endValue End value of the animation curve
  50297. * @param gradient Scalar amount to interpolate
  50298. * @returns Interpolated quaternion value
  50299. */
  50300. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50301. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50302. };
  50303. /**
  50304. * Interpolates a quaternion cubically
  50305. * @param startValue Start value of the animation curve
  50306. * @param outTangent End tangent of the animation curve
  50307. * @param endValue End value of the animation curve
  50308. * @param inTangent Start tangent of the animation curve
  50309. * @param gradient Scalar amount to interpolate
  50310. * @returns Interpolated quaternion value
  50311. */
  50312. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50313. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50314. };
  50315. /**
  50316. * Interpolates a Vector3 linearl
  50317. * @param startValue Start value of the animation curve
  50318. * @param endValue End value of the animation curve
  50319. * @param gradient Scalar amount to interpolate
  50320. * @returns Interpolated scalar value
  50321. */
  50322. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50323. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50324. };
  50325. /**
  50326. * Interpolates a Vector3 cubically
  50327. * @param startValue Start value of the animation curve
  50328. * @param outTangent End tangent of the animation
  50329. * @param endValue End value of the animation curve
  50330. * @param inTangent Start tangent of the animation curve
  50331. * @param gradient Scalar amount to interpolate
  50332. * @returns InterpolatedVector3 value
  50333. */
  50334. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50335. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50336. };
  50337. /**
  50338. * Interpolates a Vector2 linearly
  50339. * @param startValue Start value of the animation curve
  50340. * @param endValue End value of the animation curve
  50341. * @param gradient Scalar amount to interpolate
  50342. * @returns Interpolated Vector2 value
  50343. */
  50344. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50345. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50346. };
  50347. /**
  50348. * Interpolates a Vector2 cubically
  50349. * @param startValue Start value of the animation curve
  50350. * @param outTangent End tangent of the animation
  50351. * @param endValue End value of the animation curve
  50352. * @param inTangent Start tangent of the animation curve
  50353. * @param gradient Scalar amount to interpolate
  50354. * @returns Interpolated Vector2 value
  50355. */
  50356. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50357. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50358. };
  50359. /**
  50360. * Interpolates a size linearly
  50361. * @param startValue Start value of the animation curve
  50362. * @param endValue End value of the animation curve
  50363. * @param gradient Scalar amount to interpolate
  50364. * @returns Interpolated Size value
  50365. */
  50366. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50367. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50368. };
  50369. /**
  50370. * Interpolates a Color3 linearly
  50371. * @param startValue Start value of the animation curve
  50372. * @param endValue End value of the animation curve
  50373. * @param gradient Scalar amount to interpolate
  50374. * @returns Interpolated Color3 value
  50375. */
  50376. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50377. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50378. };
  50379. /**
  50380. * @hidden Internal use only
  50381. */
  50382. Animation.prototype._getKeyValue = function (value) {
  50383. if (typeof value === "function") {
  50384. return value();
  50385. }
  50386. return value;
  50387. };
  50388. /**
  50389. * @hidden Internal use only
  50390. */
  50391. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50392. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50393. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50394. }
  50395. var keys = this.getKeys();
  50396. // Try to get a hash to find the right key
  50397. 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));
  50398. if (keys[startKeyIndex].frame >= currentFrame) {
  50399. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50400. startKeyIndex--;
  50401. }
  50402. }
  50403. for (var key = startKeyIndex; key < keys.length; key++) {
  50404. var endKey = keys[key + 1];
  50405. if (endKey.frame >= currentFrame) {
  50406. var startKey = keys[key];
  50407. var startValue = this._getKeyValue(startKey.value);
  50408. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50409. return startValue;
  50410. }
  50411. var endValue = this._getKeyValue(endKey.value);
  50412. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50413. var frameDelta = endKey.frame - startKey.frame;
  50414. // gradient : percent of currentFrame between the frame inf and the frame sup
  50415. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50416. // check for easingFunction and correction of gradient
  50417. var easingFunction = this.getEasingFunction();
  50418. if (easingFunction != null) {
  50419. gradient = easingFunction.ease(gradient);
  50420. }
  50421. switch (this.dataType) {
  50422. // Float
  50423. case Animation.ANIMATIONTYPE_FLOAT:
  50424. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50425. switch (loopMode) {
  50426. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50427. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50428. return floatValue;
  50429. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50430. return offsetValue * repeatCount + floatValue;
  50431. }
  50432. break;
  50433. // Quaternion
  50434. case Animation.ANIMATIONTYPE_QUATERNION:
  50435. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50436. switch (loopMode) {
  50437. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50438. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50439. return quatValue;
  50440. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50441. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50442. }
  50443. return quatValue;
  50444. // Vector3
  50445. case Animation.ANIMATIONTYPE_VECTOR3:
  50446. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50447. switch (loopMode) {
  50448. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50449. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50450. return vec3Value;
  50451. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50452. return vec3Value.add(offsetValue.scale(repeatCount));
  50453. }
  50454. // Vector2
  50455. case Animation.ANIMATIONTYPE_VECTOR2:
  50456. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50457. switch (loopMode) {
  50458. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50459. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50460. return vec2Value;
  50461. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50462. return vec2Value.add(offsetValue.scale(repeatCount));
  50463. }
  50464. // Size
  50465. case Animation.ANIMATIONTYPE_SIZE:
  50466. switch (loopMode) {
  50467. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50468. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50469. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50470. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50471. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50472. }
  50473. // Color3
  50474. case Animation.ANIMATIONTYPE_COLOR3:
  50475. switch (loopMode) {
  50476. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50477. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50478. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50479. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50480. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50481. }
  50482. // Matrix
  50483. case Animation.ANIMATIONTYPE_MATRIX:
  50484. switch (loopMode) {
  50485. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50486. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50487. if (Animation.AllowMatricesInterpolation) {
  50488. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50489. }
  50490. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50491. return startValue;
  50492. }
  50493. default:
  50494. break;
  50495. }
  50496. break;
  50497. }
  50498. }
  50499. return this._getKeyValue(keys[keys.length - 1].value);
  50500. };
  50501. /**
  50502. * Defines the function to use to interpolate matrices
  50503. * @param startValue defines the start matrix
  50504. * @param endValue defines the end matrix
  50505. * @param gradient defines the gradient between both matrices
  50506. * @param result defines an optional target matrix where to store the interpolation
  50507. * @returns the interpolated matrix
  50508. */
  50509. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50510. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50511. if (result) {
  50512. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50513. return result;
  50514. }
  50515. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50516. }
  50517. if (result) {
  50518. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50519. return result;
  50520. }
  50521. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50522. };
  50523. /**
  50524. * Makes a copy of the animation
  50525. * @returns Cloned animation
  50526. */
  50527. Animation.prototype.clone = function () {
  50528. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50529. clone.enableBlending = this.enableBlending;
  50530. clone.blendingSpeed = this.blendingSpeed;
  50531. if (this._keys) {
  50532. clone.setKeys(this._keys);
  50533. }
  50534. if (this._ranges) {
  50535. clone._ranges = {};
  50536. for (var name in this._ranges) {
  50537. var range = this._ranges[name];
  50538. if (!range) {
  50539. continue;
  50540. }
  50541. clone._ranges[name] = range.clone();
  50542. }
  50543. }
  50544. return clone;
  50545. };
  50546. /**
  50547. * Sets the key frames of the animation
  50548. * @param values The animation key frames to set
  50549. */
  50550. Animation.prototype.setKeys = function (values) {
  50551. this._keys = values.slice(0);
  50552. };
  50553. /**
  50554. * Serializes the animation to an object
  50555. * @returns Serialized object
  50556. */
  50557. Animation.prototype.serialize = function () {
  50558. var serializationObject = {};
  50559. serializationObject.name = this.name;
  50560. serializationObject.property = this.targetProperty;
  50561. serializationObject.framePerSecond = this.framePerSecond;
  50562. serializationObject.dataType = this.dataType;
  50563. serializationObject.loopBehavior = this.loopMode;
  50564. serializationObject.enableBlending = this.enableBlending;
  50565. serializationObject.blendingSpeed = this.blendingSpeed;
  50566. var dataType = this.dataType;
  50567. serializationObject.keys = [];
  50568. var keys = this.getKeys();
  50569. for (var index = 0; index < keys.length; index++) {
  50570. var animationKey = keys[index];
  50571. var key = {};
  50572. key.frame = animationKey.frame;
  50573. switch (dataType) {
  50574. case Animation.ANIMATIONTYPE_FLOAT:
  50575. key.values = [animationKey.value];
  50576. break;
  50577. case Animation.ANIMATIONTYPE_QUATERNION:
  50578. case Animation.ANIMATIONTYPE_MATRIX:
  50579. case Animation.ANIMATIONTYPE_VECTOR3:
  50580. case Animation.ANIMATIONTYPE_COLOR3:
  50581. key.values = animationKey.value.asArray();
  50582. break;
  50583. }
  50584. serializationObject.keys.push(key);
  50585. }
  50586. serializationObject.ranges = [];
  50587. for (var name in this._ranges) {
  50588. var source = this._ranges[name];
  50589. if (!source) {
  50590. continue;
  50591. }
  50592. var range = {};
  50593. range.name = name;
  50594. range.from = source.from;
  50595. range.to = source.to;
  50596. serializationObject.ranges.push(range);
  50597. }
  50598. return serializationObject;
  50599. };
  50600. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50601. /**
  50602. * Get the float animation type
  50603. */
  50604. get: function () {
  50605. return Animation._ANIMATIONTYPE_FLOAT;
  50606. },
  50607. enumerable: true,
  50608. configurable: true
  50609. });
  50610. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50611. /**
  50612. * Get the Vector3 animation type
  50613. */
  50614. get: function () {
  50615. return Animation._ANIMATIONTYPE_VECTOR3;
  50616. },
  50617. enumerable: true,
  50618. configurable: true
  50619. });
  50620. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50621. /**
  50622. * Get the Vector2 animation type
  50623. */
  50624. get: function () {
  50625. return Animation._ANIMATIONTYPE_VECTOR2;
  50626. },
  50627. enumerable: true,
  50628. configurable: true
  50629. });
  50630. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50631. /**
  50632. * Get the Size animation type
  50633. */
  50634. get: function () {
  50635. return Animation._ANIMATIONTYPE_SIZE;
  50636. },
  50637. enumerable: true,
  50638. configurable: true
  50639. });
  50640. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50641. /**
  50642. * Get the Quaternion animation type
  50643. */
  50644. get: function () {
  50645. return Animation._ANIMATIONTYPE_QUATERNION;
  50646. },
  50647. enumerable: true,
  50648. configurable: true
  50649. });
  50650. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50651. /**
  50652. * Get the Matrix animation type
  50653. */
  50654. get: function () {
  50655. return Animation._ANIMATIONTYPE_MATRIX;
  50656. },
  50657. enumerable: true,
  50658. configurable: true
  50659. });
  50660. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50661. /**
  50662. * Get the Color3 animation type
  50663. */
  50664. get: function () {
  50665. return Animation._ANIMATIONTYPE_COLOR3;
  50666. },
  50667. enumerable: true,
  50668. configurable: true
  50669. });
  50670. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50671. /**
  50672. * Get the Relative Loop Mode
  50673. */
  50674. get: function () {
  50675. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50676. },
  50677. enumerable: true,
  50678. configurable: true
  50679. });
  50680. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50681. /**
  50682. * Get the Cycle Loop Mode
  50683. */
  50684. get: function () {
  50685. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50686. },
  50687. enumerable: true,
  50688. configurable: true
  50689. });
  50690. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50691. /**
  50692. * Get the Constant Loop Mode
  50693. */
  50694. get: function () {
  50695. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50696. },
  50697. enumerable: true,
  50698. configurable: true
  50699. });
  50700. /** @hidden */
  50701. Animation._UniversalLerp = function (left, right, amount) {
  50702. var constructor = left.constructor;
  50703. if (constructor.Lerp) { // Lerp supported
  50704. return constructor.Lerp(left, right, amount);
  50705. }
  50706. else if (constructor.Slerp) { // Slerp supported
  50707. return constructor.Slerp(left, right, amount);
  50708. }
  50709. else if (left.toFixed) { // Number
  50710. return left * (1.0 - amount) + amount * right;
  50711. }
  50712. else { // Blending not supported
  50713. return right;
  50714. }
  50715. };
  50716. /**
  50717. * Parses an animation object and creates an animation
  50718. * @param parsedAnimation Parsed animation object
  50719. * @returns Animation object
  50720. */
  50721. Animation.Parse = function (parsedAnimation) {
  50722. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50723. var dataType = parsedAnimation.dataType;
  50724. var keys = [];
  50725. var data;
  50726. var index;
  50727. if (parsedAnimation.enableBlending) {
  50728. animation.enableBlending = parsedAnimation.enableBlending;
  50729. }
  50730. if (parsedAnimation.blendingSpeed) {
  50731. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50732. }
  50733. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50734. var key = parsedAnimation.keys[index];
  50735. var inTangent;
  50736. var outTangent;
  50737. switch (dataType) {
  50738. case Animation.ANIMATIONTYPE_FLOAT:
  50739. data = key.values[0];
  50740. if (key.values.length >= 1) {
  50741. inTangent = key.values[1];
  50742. }
  50743. if (key.values.length >= 2) {
  50744. outTangent = key.values[2];
  50745. }
  50746. break;
  50747. case Animation.ANIMATIONTYPE_QUATERNION:
  50748. data = BABYLON.Quaternion.FromArray(key.values);
  50749. if (key.values.length >= 8) {
  50750. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50751. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50752. inTangent = _inTangent;
  50753. }
  50754. }
  50755. if (key.values.length >= 12) {
  50756. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50757. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50758. outTangent = _outTangent;
  50759. }
  50760. }
  50761. break;
  50762. case Animation.ANIMATIONTYPE_MATRIX:
  50763. data = BABYLON.Matrix.FromArray(key.values);
  50764. break;
  50765. case Animation.ANIMATIONTYPE_COLOR3:
  50766. data = BABYLON.Color3.FromArray(key.values);
  50767. break;
  50768. case Animation.ANIMATIONTYPE_VECTOR3:
  50769. default:
  50770. data = BABYLON.Vector3.FromArray(key.values);
  50771. break;
  50772. }
  50773. var keyData = {};
  50774. keyData.frame = key.frame;
  50775. keyData.value = data;
  50776. if (inTangent != undefined) {
  50777. keyData.inTangent = inTangent;
  50778. }
  50779. if (outTangent != undefined) {
  50780. keyData.outTangent = outTangent;
  50781. }
  50782. keys.push(keyData);
  50783. }
  50784. animation.setKeys(keys);
  50785. if (parsedAnimation.ranges) {
  50786. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50787. data = parsedAnimation.ranges[index];
  50788. animation.createRange(data.name, data.from, data.to);
  50789. }
  50790. }
  50791. return animation;
  50792. };
  50793. /**
  50794. * Appends the serialized animations from the source animations
  50795. * @param source Source containing the animations
  50796. * @param destination Target to store the animations
  50797. */
  50798. Animation.AppendSerializedAnimations = function (source, destination) {
  50799. if (source.animations) {
  50800. destination.animations = [];
  50801. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50802. var animation = source.animations[animationIndex];
  50803. destination.animations.push(animation.serialize());
  50804. }
  50805. }
  50806. };
  50807. /**
  50808. * Use matrix interpolation instead of using direct key value when animating matrices
  50809. */
  50810. Animation.AllowMatricesInterpolation = false;
  50811. /**
  50812. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50813. */
  50814. Animation.AllowMatrixDecomposeForInterpolation = true;
  50815. // Statics
  50816. /**
  50817. * Float animation type
  50818. */
  50819. Animation._ANIMATIONTYPE_FLOAT = 0;
  50820. /**
  50821. * Vector3 animation type
  50822. */
  50823. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50824. /**
  50825. * Quaternion animation type
  50826. */
  50827. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50828. /**
  50829. * Matrix animation type
  50830. */
  50831. Animation._ANIMATIONTYPE_MATRIX = 3;
  50832. /**
  50833. * Color3 animation type
  50834. */
  50835. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50836. /**
  50837. * Vector2 animation type
  50838. */
  50839. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50840. /**
  50841. * Size animation type
  50842. */
  50843. Animation._ANIMATIONTYPE_SIZE = 6;
  50844. /**
  50845. * Relative Loop Mode
  50846. */
  50847. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50848. /**
  50849. * Cycle Loop Mode
  50850. */
  50851. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50852. /**
  50853. * Constant Loop Mode
  50854. */
  50855. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50856. return Animation;
  50857. }());
  50858. BABYLON.Animation = Animation;
  50859. })(BABYLON || (BABYLON = {}));
  50860. //# sourceMappingURL=babylon.animation.js.map
  50861. var BABYLON;
  50862. (function (BABYLON) {
  50863. /**
  50864. * This class defines the direct association between an animation and a target
  50865. */
  50866. var TargetedAnimation = /** @class */ (function () {
  50867. function TargetedAnimation() {
  50868. }
  50869. return TargetedAnimation;
  50870. }());
  50871. BABYLON.TargetedAnimation = TargetedAnimation;
  50872. /**
  50873. * Use this class to create coordinated animations on multiple targets
  50874. */
  50875. var AnimationGroup = /** @class */ (function () {
  50876. function AnimationGroup(name, scene) {
  50877. if (scene === void 0) { scene = null; }
  50878. this.name = name;
  50879. this._targetedAnimations = new Array();
  50880. this._animatables = new Array();
  50881. this._from = Number.MAX_VALUE;
  50882. this._to = -Number.MAX_VALUE;
  50883. this._speedRatio = 1;
  50884. this.onAnimationEndObservable = new BABYLON.Observable();
  50885. /**
  50886. * This observable will notify when all animations have ended.
  50887. */
  50888. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50889. /**
  50890. * This observable will notify when all animations have paused.
  50891. */
  50892. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50893. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50894. this._scene.animationGroups.push(this);
  50895. }
  50896. Object.defineProperty(AnimationGroup.prototype, "from", {
  50897. /**
  50898. * Gets the first frame
  50899. */
  50900. get: function () {
  50901. return this._from;
  50902. },
  50903. enumerable: true,
  50904. configurable: true
  50905. });
  50906. Object.defineProperty(AnimationGroup.prototype, "to", {
  50907. /**
  50908. * Gets the last frame
  50909. */
  50910. get: function () {
  50911. return this._to;
  50912. },
  50913. enumerable: true,
  50914. configurable: true
  50915. });
  50916. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50917. /**
  50918. * Define if the animations are started
  50919. */
  50920. get: function () {
  50921. return this._isStarted;
  50922. },
  50923. enumerable: true,
  50924. configurable: true
  50925. });
  50926. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50927. /**
  50928. * Gets or sets the speed ratio to use for all animations
  50929. */
  50930. get: function () {
  50931. return this._speedRatio;
  50932. },
  50933. /**
  50934. * Gets or sets the speed ratio to use for all animations
  50935. */
  50936. set: function (value) {
  50937. if (this._speedRatio === value) {
  50938. return;
  50939. }
  50940. this._speedRatio = value;
  50941. for (var index = 0; index < this._animatables.length; index++) {
  50942. var animatable = this._animatables[index];
  50943. animatable.speedRatio = this._speedRatio;
  50944. }
  50945. },
  50946. enumerable: true,
  50947. configurable: true
  50948. });
  50949. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50950. /**
  50951. * Gets the targeted animations for this animation group
  50952. */
  50953. get: function () {
  50954. return this._targetedAnimations;
  50955. },
  50956. enumerable: true,
  50957. configurable: true
  50958. });
  50959. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50960. /**
  50961. * returning the list of animatables controlled by this animation group.
  50962. */
  50963. get: function () {
  50964. return this._animatables;
  50965. },
  50966. enumerable: true,
  50967. configurable: true
  50968. });
  50969. /**
  50970. * Add an animation (with its target) in the group
  50971. * @param animation defines the animation we want to add
  50972. * @param target defines the target of the animation
  50973. * @returns the {BABYLON.TargetedAnimation} object
  50974. */
  50975. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50976. var targetedAnimation = {
  50977. animation: animation,
  50978. target: target
  50979. };
  50980. var keys = animation.getKeys();
  50981. if (this._from > keys[0].frame) {
  50982. this._from = keys[0].frame;
  50983. }
  50984. if (this._to < keys[keys.length - 1].frame) {
  50985. this._to = keys[keys.length - 1].frame;
  50986. }
  50987. this._targetedAnimations.push(targetedAnimation);
  50988. return targetedAnimation;
  50989. };
  50990. /**
  50991. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50992. * It can add constant keys at begin or end
  50993. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50994. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50995. */
  50996. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50997. if (beginFrame === void 0) { beginFrame = null; }
  50998. if (endFrame === void 0) { endFrame = null; }
  50999. if (beginFrame == null)
  51000. beginFrame = this._from;
  51001. if (endFrame == null)
  51002. endFrame = this._to;
  51003. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51004. var targetedAnimation = this._targetedAnimations[index];
  51005. var keys = targetedAnimation.animation.getKeys();
  51006. var startKey = keys[0];
  51007. var endKey = keys[keys.length - 1];
  51008. if (startKey.frame > beginFrame) {
  51009. var newKey = {
  51010. frame: beginFrame,
  51011. value: startKey.value,
  51012. inTangent: startKey.inTangent,
  51013. outTangent: startKey.outTangent,
  51014. interpolation: startKey.interpolation
  51015. };
  51016. keys.splice(0, 0, newKey);
  51017. }
  51018. if (endKey.frame < endFrame) {
  51019. var newKey = {
  51020. frame: endFrame,
  51021. value: endKey.value,
  51022. inTangent: endKey.outTangent,
  51023. outTangent: endKey.outTangent,
  51024. interpolation: endKey.interpolation
  51025. };
  51026. keys.push(newKey);
  51027. }
  51028. }
  51029. this._from = beginFrame;
  51030. this._to = endFrame;
  51031. return this;
  51032. };
  51033. /**
  51034. * Start all animations on given targets
  51035. * @param loop defines if animations must loop
  51036. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51037. * @param from defines the from key (optional)
  51038. * @param to defines the to key (optional)
  51039. * @returns the current animation group
  51040. */
  51041. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51042. var _this = this;
  51043. if (loop === void 0) { loop = false; }
  51044. if (speedRatio === void 0) { speedRatio = 1; }
  51045. if (this._isStarted || this._targetedAnimations.length === 0) {
  51046. return this;
  51047. }
  51048. var _loop_1 = function (targetedAnimation) {
  51049. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51050. animatable.onAnimationEnd = function () {
  51051. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51052. _this._checkAnimationGroupEnded(animatable);
  51053. };
  51054. this_1._animatables.push(animatable);
  51055. };
  51056. var this_1 = this;
  51057. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51058. var targetedAnimation = _a[_i];
  51059. _loop_1(targetedAnimation);
  51060. }
  51061. this._speedRatio = speedRatio;
  51062. this._isStarted = true;
  51063. return this;
  51064. };
  51065. /**
  51066. * Pause all animations
  51067. */
  51068. AnimationGroup.prototype.pause = function () {
  51069. if (!this._isStarted) {
  51070. return this;
  51071. }
  51072. for (var index = 0; index < this._animatables.length; index++) {
  51073. var animatable = this._animatables[index];
  51074. animatable.pause();
  51075. }
  51076. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51077. return this;
  51078. };
  51079. /**
  51080. * Play all animations to initial state
  51081. * This function will start() the animations if they were not started or will restart() them if they were paused
  51082. * @param loop defines if animations must loop
  51083. */
  51084. AnimationGroup.prototype.play = function (loop) {
  51085. // only if all animatables are ready and exist
  51086. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51087. if (loop !== undefined) {
  51088. for (var index = 0; index < this._animatables.length; index++) {
  51089. var animatable = this._animatables[index];
  51090. animatable.loopAnimation = loop;
  51091. }
  51092. }
  51093. this.restart();
  51094. }
  51095. else {
  51096. this.stop();
  51097. this.start(loop, this._speedRatio);
  51098. }
  51099. return this;
  51100. };
  51101. /**
  51102. * Reset all animations to initial state
  51103. */
  51104. AnimationGroup.prototype.reset = function () {
  51105. if (!this._isStarted) {
  51106. return this;
  51107. }
  51108. for (var index = 0; index < this._animatables.length; index++) {
  51109. var animatable = this._animatables[index];
  51110. animatable.reset();
  51111. }
  51112. return this;
  51113. };
  51114. /**
  51115. * Restart animations from key 0
  51116. */
  51117. AnimationGroup.prototype.restart = function () {
  51118. if (!this._isStarted) {
  51119. return this;
  51120. }
  51121. for (var index = 0; index < this._animatables.length; index++) {
  51122. var animatable = this._animatables[index];
  51123. animatable.restart();
  51124. }
  51125. return this;
  51126. };
  51127. /**
  51128. * Stop all animations
  51129. */
  51130. AnimationGroup.prototype.stop = function () {
  51131. if (!this._isStarted) {
  51132. return this;
  51133. }
  51134. var list = this._animatables.slice();
  51135. for (var index = 0; index < list.length; index++) {
  51136. list[index].stop();
  51137. }
  51138. this._isStarted = false;
  51139. return this;
  51140. };
  51141. /**
  51142. * Set animation weight for all animatables
  51143. * @param weight defines the weight to use
  51144. * @return the animationGroup
  51145. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51146. */
  51147. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51148. for (var index = 0; index < this._animatables.length; index++) {
  51149. var animatable = this._animatables[index];
  51150. animatable.weight = weight;
  51151. }
  51152. return this;
  51153. };
  51154. /**
  51155. * Synchronize and normalize all animatables with a source animatable
  51156. * @param root defines the root animatable to synchronize with
  51157. * @return the animationGroup
  51158. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51159. */
  51160. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51161. for (var index = 0; index < this._animatables.length; index++) {
  51162. var animatable = this._animatables[index];
  51163. animatable.syncWith(root);
  51164. }
  51165. return this;
  51166. };
  51167. /**
  51168. * Goes to a specific frame in this animation group
  51169. * @param frame the frame number to go to
  51170. * @return the animationGroup
  51171. */
  51172. AnimationGroup.prototype.goToFrame = function (frame) {
  51173. if (!this._isStarted) {
  51174. return this;
  51175. }
  51176. for (var index = 0; index < this._animatables.length; index++) {
  51177. var animatable = this._animatables[index];
  51178. animatable.goToFrame(frame);
  51179. }
  51180. return this;
  51181. };
  51182. /**
  51183. * Dispose all associated resources
  51184. */
  51185. AnimationGroup.prototype.dispose = function () {
  51186. this._targetedAnimations = [];
  51187. this._animatables = [];
  51188. var index = this._scene.animationGroups.indexOf(this);
  51189. if (index > -1) {
  51190. this._scene.animationGroups.splice(index, 1);
  51191. }
  51192. };
  51193. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51194. // animatable should be taken out of the array
  51195. var idx = this._animatables.indexOf(animatable);
  51196. if (idx > -1) {
  51197. this._animatables.splice(idx, 1);
  51198. }
  51199. // all animatables were removed? animation group ended!
  51200. if (this._animatables.length === 0) {
  51201. this._isStarted = false;
  51202. this.onAnimationGroupEndObservable.notifyObservers(this);
  51203. }
  51204. };
  51205. return AnimationGroup;
  51206. }());
  51207. BABYLON.AnimationGroup = AnimationGroup;
  51208. })(BABYLON || (BABYLON = {}));
  51209. //# sourceMappingURL=babylon.animationGroup.js.map
  51210. var BABYLON;
  51211. (function (BABYLON) {
  51212. /**
  51213. * Defines a runtime animation
  51214. */
  51215. var RuntimeAnimation = /** @class */ (function () {
  51216. /**
  51217. * Create a new RuntimeAnimation object
  51218. * @param target defines the target of the animation
  51219. * @param animation defines the source animation object
  51220. * @param scene defines the hosting scene
  51221. * @param host defines the initiating Animatable
  51222. */
  51223. function RuntimeAnimation(target, animation, scene, host) {
  51224. var _this = this;
  51225. this._events = new Array();
  51226. /**
  51227. * The current frame of the runtime animation
  51228. */
  51229. this._currentFrame = 0;
  51230. /**
  51231. * The original value of the runtime animation
  51232. */
  51233. this._originalValue = new Array();
  51234. /**
  51235. * The offsets cache of the runtime animation
  51236. */
  51237. this._offsetsCache = {};
  51238. /**
  51239. * The high limits cache of the runtime animation
  51240. */
  51241. this._highLimitsCache = {};
  51242. /**
  51243. * Specifies if the runtime animation has been stopped
  51244. */
  51245. this._stopped = false;
  51246. /**
  51247. * The blending factor of the runtime animation
  51248. */
  51249. this._blendingFactor = 0;
  51250. /**
  51251. * The target path of the runtime animation
  51252. */
  51253. this._targetPath = "";
  51254. /**
  51255. * The weight of the runtime animation
  51256. */
  51257. this._weight = 1.0;
  51258. /**
  51259. * The ratio offset of the runtime animation
  51260. */
  51261. this._ratioOffset = 0;
  51262. /**
  51263. * The previous delay of the runtime animation
  51264. */
  51265. this._previousDelay = 0;
  51266. /**
  51267. * The previous ratio of the runtime animation
  51268. */
  51269. this._previousRatio = 0;
  51270. this._animation = animation;
  51271. this._target = target;
  51272. this._scene = scene;
  51273. this._host = host;
  51274. animation._runtimeAnimations.push(this);
  51275. // Cloning events locally
  51276. var events = animation.getEvents();
  51277. if (events && events.length > 0) {
  51278. events.forEach(function (e) {
  51279. _this._events.push(e._clone());
  51280. });
  51281. }
  51282. }
  51283. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51284. /**
  51285. * Gets the current frame of the runtime animation
  51286. */
  51287. get: function () {
  51288. return this._currentFrame;
  51289. },
  51290. enumerable: true,
  51291. configurable: true
  51292. });
  51293. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51294. /**
  51295. * Gets the weight of the runtime animation
  51296. */
  51297. get: function () {
  51298. return this._weight;
  51299. },
  51300. enumerable: true,
  51301. configurable: true
  51302. });
  51303. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51304. /**
  51305. * Gets the current value of the runtime animation
  51306. */
  51307. get: function () {
  51308. return this._currentValue;
  51309. },
  51310. enumerable: true,
  51311. configurable: true
  51312. });
  51313. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51314. /**
  51315. * Gets the target path of the runtime animation
  51316. */
  51317. get: function () {
  51318. return this._targetPath;
  51319. },
  51320. enumerable: true,
  51321. configurable: true
  51322. });
  51323. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51324. /**
  51325. * Gets the actual target of the runtime animation
  51326. */
  51327. get: function () {
  51328. return this._activeTarget;
  51329. },
  51330. enumerable: true,
  51331. configurable: true
  51332. });
  51333. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51334. /**
  51335. * Gets the animation from the runtime animation
  51336. */
  51337. get: function () {
  51338. return this._animation;
  51339. },
  51340. enumerable: true,
  51341. configurable: true
  51342. });
  51343. /**
  51344. * Resets the runtime animation to the beginning
  51345. * @param restoreOriginal defines whether to restore the target property to the original value
  51346. */
  51347. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51348. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51349. if (restoreOriginal) {
  51350. if (this._target instanceof Array) {
  51351. var index = 0;
  51352. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51353. var target = _a[_i];
  51354. if (this._originalValue[index] !== undefined) {
  51355. this._setValue(target, this._originalValue[index], -1);
  51356. }
  51357. index++;
  51358. }
  51359. }
  51360. else {
  51361. if (this._originalValue[0] !== undefined) {
  51362. this._setValue(this._target, this._originalValue[0], -1);
  51363. }
  51364. }
  51365. }
  51366. this._offsetsCache = {};
  51367. this._highLimitsCache = {};
  51368. this._currentFrame = 0;
  51369. this._blendingFactor = 0;
  51370. this._originalValue = new Array();
  51371. // Events
  51372. for (var index = 0; index < this._events.length; index++) {
  51373. this._events[index].isDone = false;
  51374. }
  51375. };
  51376. /**
  51377. * Specifies if the runtime animation is stopped
  51378. * @returns Boolean specifying if the runtime animation is stopped
  51379. */
  51380. RuntimeAnimation.prototype.isStopped = function () {
  51381. return this._stopped;
  51382. };
  51383. /**
  51384. * Disposes of the runtime animation
  51385. */
  51386. RuntimeAnimation.prototype.dispose = function () {
  51387. var index = this._animation.runtimeAnimations.indexOf(this);
  51388. if (index > -1) {
  51389. this._animation.runtimeAnimations.splice(index, 1);
  51390. }
  51391. };
  51392. /**
  51393. * Interpolates the animation from the current frame
  51394. * @param currentFrame The frame to interpolate the animation to
  51395. * @param repeatCount The number of times that the animation should loop
  51396. * @param loopMode The type of looping mode to use
  51397. * @param offsetValue Animation offset value
  51398. * @param highLimitValue The high limit value
  51399. * @returns The interpolated value
  51400. */
  51401. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51402. this._currentFrame = currentFrame;
  51403. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51404. this._workValue = BABYLON.Matrix.Zero();
  51405. }
  51406. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51407. };
  51408. /**
  51409. * Apply the interpolated value to the target
  51410. * @param currentValue defines the value computed by the animation
  51411. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51412. */
  51413. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51414. if (weight === void 0) { weight = 1.0; }
  51415. if (this._target instanceof Array) {
  51416. var index = 0;
  51417. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51418. var target = _a[_i];
  51419. this._setValue(target, currentValue, weight, index);
  51420. index++;
  51421. }
  51422. }
  51423. else {
  51424. this._setValue(this._target, currentValue, weight);
  51425. }
  51426. };
  51427. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51428. if (targetIndex === void 0) { targetIndex = 0; }
  51429. // Set value
  51430. var path;
  51431. var destination;
  51432. var targetPropertyPath = this._animation.targetPropertyPath;
  51433. if (targetPropertyPath.length > 1) {
  51434. var property = target[targetPropertyPath[0]];
  51435. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51436. property = property[targetPropertyPath[index]];
  51437. }
  51438. path = targetPropertyPath[targetPropertyPath.length - 1];
  51439. destination = property;
  51440. }
  51441. else {
  51442. path = targetPropertyPath[0];
  51443. destination = target;
  51444. }
  51445. this._targetPath = path;
  51446. this._activeTarget = destination;
  51447. this._weight = weight;
  51448. if (this._originalValue[targetIndex] === undefined) {
  51449. var originalValue = void 0;
  51450. if (destination.getRestPose && path === "_matrix") { // For bones
  51451. originalValue = destination.getRestPose();
  51452. }
  51453. else {
  51454. originalValue = destination[path];
  51455. }
  51456. if (originalValue && originalValue.clone) {
  51457. this._originalValue[targetIndex] = originalValue.clone();
  51458. }
  51459. else {
  51460. this._originalValue[targetIndex] = originalValue;
  51461. }
  51462. }
  51463. // Blending
  51464. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51465. if (enableBlending && this._blendingFactor <= 1.0) {
  51466. if (!this._originalBlendValue) {
  51467. var originalValue = destination[path];
  51468. if (originalValue.clone) {
  51469. this._originalBlendValue = originalValue.clone();
  51470. }
  51471. else {
  51472. this._originalBlendValue = originalValue;
  51473. }
  51474. }
  51475. if (this._originalBlendValue.m) { // Matrix
  51476. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51477. if (this._currentValue) {
  51478. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51479. }
  51480. else {
  51481. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51482. }
  51483. }
  51484. else {
  51485. if (this._currentValue) {
  51486. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51487. }
  51488. else {
  51489. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51490. }
  51491. }
  51492. }
  51493. else {
  51494. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51495. }
  51496. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51497. this._blendingFactor += blendingSpeed;
  51498. }
  51499. else {
  51500. this._currentValue = currentValue;
  51501. }
  51502. if (weight !== -1.0) {
  51503. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51504. }
  51505. else {
  51506. destination[path] = this._currentValue;
  51507. }
  51508. if (target.markAsDirty) {
  51509. target.markAsDirty(this._animation.targetProperty);
  51510. }
  51511. };
  51512. /**
  51513. * Gets the loop pmode of the runtime animation
  51514. * @returns Loop Mode
  51515. */
  51516. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51517. if (this._target && this._target.animationPropertiesOverride) {
  51518. return this._target.animationPropertiesOverride.loopMode;
  51519. }
  51520. return this._animation.loopMode;
  51521. };
  51522. /**
  51523. * Move the current animation to a given frame
  51524. * @param frame defines the frame to move to
  51525. */
  51526. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51527. var keys = this._animation.getKeys();
  51528. if (frame < keys[0].frame) {
  51529. frame = keys[0].frame;
  51530. }
  51531. else if (frame > keys[keys.length - 1].frame) {
  51532. frame = keys[keys.length - 1].frame;
  51533. }
  51534. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51535. this.setValue(currentValue, -1);
  51536. };
  51537. /**
  51538. * @hidden Internal use only
  51539. */
  51540. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51541. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51542. this._ratioOffset = this._previousRatio - newRatio;
  51543. };
  51544. /**
  51545. * Execute the current animation
  51546. * @param delay defines the delay to add to the current frame
  51547. * @param from defines the lower bound of the animation range
  51548. * @param to defines the upper bound of the animation range
  51549. * @param loop defines if the current animation must loop
  51550. * @param speedRatio defines the current speed ratio
  51551. * @param weight defines the weight of the animation (default is -1 so no weight)
  51552. * @returns a boolean indicating if the animation is running
  51553. */
  51554. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51555. if (weight === void 0) { weight = -1.0; }
  51556. var targetPropertyPath = this._animation.targetPropertyPath;
  51557. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51558. this._stopped = true;
  51559. return false;
  51560. }
  51561. var returnValue = true;
  51562. var keys = this._animation.getKeys();
  51563. // Adding a start key at frame 0 if missing
  51564. if (keys[0].frame !== 0) {
  51565. var newKey = { frame: 0, value: keys[0].value };
  51566. keys.splice(0, 0, newKey);
  51567. }
  51568. // Adding a duplicate key when there is only one key at frame zero
  51569. else if (keys.length === 1) {
  51570. var newKey = { frame: 0.001, value: keys[0].value };
  51571. keys.push(newKey);
  51572. }
  51573. // Check limits
  51574. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51575. from = keys[0].frame;
  51576. }
  51577. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51578. to = keys[keys.length - 1].frame;
  51579. }
  51580. //to and from cannot be the same key
  51581. if (from === to) {
  51582. if (from > keys[0].frame) {
  51583. from--;
  51584. }
  51585. else if (to < keys[keys.length - 1].frame) {
  51586. to++;
  51587. }
  51588. }
  51589. // Compute ratio
  51590. var range = to - from;
  51591. var offsetValue;
  51592. // ratio represents the frame delta between from and to
  51593. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51594. var highLimitValue = 0;
  51595. this._previousDelay = delay;
  51596. this._previousRatio = ratio;
  51597. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51598. returnValue = false;
  51599. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51600. }
  51601. else {
  51602. // Get max value if required
  51603. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51604. var keyOffset = to.toString() + from.toString();
  51605. if (!this._offsetsCache[keyOffset]) {
  51606. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51607. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51608. switch (this._animation.dataType) {
  51609. // Float
  51610. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51611. this._offsetsCache[keyOffset] = toValue - fromValue;
  51612. break;
  51613. // Quaternion
  51614. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51615. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51616. break;
  51617. // Vector3
  51618. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51619. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51620. // Vector2
  51621. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51622. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51623. // Size
  51624. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51625. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51626. // Color3
  51627. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51628. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51629. default:
  51630. break;
  51631. }
  51632. this._highLimitsCache[keyOffset] = toValue;
  51633. }
  51634. highLimitValue = this._highLimitsCache[keyOffset];
  51635. offsetValue = this._offsetsCache[keyOffset];
  51636. }
  51637. }
  51638. if (offsetValue === undefined) {
  51639. switch (this._animation.dataType) {
  51640. // Float
  51641. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51642. offsetValue = 0;
  51643. break;
  51644. // Quaternion
  51645. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51646. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51647. break;
  51648. // Vector3
  51649. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51650. offsetValue = BABYLON.Vector3.Zero();
  51651. break;
  51652. // Vector2
  51653. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51654. offsetValue = BABYLON.Vector2.Zero();
  51655. break;
  51656. // Size
  51657. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51658. offsetValue = BABYLON.Size.Zero();
  51659. break;
  51660. // Color3
  51661. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51662. offsetValue = BABYLON.Color3.Black();
  51663. }
  51664. }
  51665. // Compute value
  51666. var repeatCount = (ratio / range) >> 0;
  51667. var currentFrame = returnValue ? from + ratio % range : to;
  51668. // Need to normalize?
  51669. if (this._host && this._host.syncRoot) {
  51670. var syncRoot = this._host.syncRoot;
  51671. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51672. currentFrame = from + (to - from) * hostNormalizedFrame;
  51673. }
  51674. // Reset events if looping
  51675. var events = this._events;
  51676. if (range > 0 && this.currentFrame > currentFrame ||
  51677. range < 0 && this.currentFrame < currentFrame) {
  51678. // Need to reset animation events
  51679. for (var index = 0; index < events.length; index++) {
  51680. if (!events[index].onlyOnce) {
  51681. // reset event, the animation is looping
  51682. events[index].isDone = false;
  51683. }
  51684. }
  51685. }
  51686. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51687. // Set value
  51688. this.setValue(currentValue, weight);
  51689. // Check events
  51690. for (var index = 0; index < events.length; index++) {
  51691. // Make sure current frame has passed event frame and that event frame is within the current range
  51692. // Also, handle both forward and reverse animations
  51693. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51694. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51695. var event = events[index];
  51696. if (!event.isDone) {
  51697. // If event should be done only once, remove it.
  51698. if (event.onlyOnce) {
  51699. events.splice(index, 1);
  51700. index--;
  51701. }
  51702. event.isDone = true;
  51703. event.action(currentFrame);
  51704. } // Don't do anything if the event has already be done.
  51705. }
  51706. }
  51707. if (!returnValue) {
  51708. this._stopped = true;
  51709. }
  51710. return returnValue;
  51711. };
  51712. return RuntimeAnimation;
  51713. }());
  51714. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51715. })(BABYLON || (BABYLON = {}));
  51716. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51717. var BABYLON;
  51718. (function (BABYLON) {
  51719. /**
  51720. * Class used to store an actual running animation
  51721. */
  51722. var Animatable = /** @class */ (function () {
  51723. /**
  51724. * Creates a new Animatable
  51725. * @param scene defines the hosting scene
  51726. * @param target defines the target object
  51727. * @param fromFrame defines the starting frame number (default is 0)
  51728. * @param toFrame defines the ending frame number (default is 100)
  51729. * @param loopAnimation defines if the animation must loop (default is false)
  51730. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51731. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51732. * @param animations defines a group of animation to add to the new Animatable
  51733. */
  51734. function Animatable(scene,
  51735. /** defines the target object */
  51736. target,
  51737. /** defines the starting frame number (default is 0) */
  51738. fromFrame,
  51739. /** defines the ending frame number (default is 100) */
  51740. toFrame,
  51741. /** defines if the animation must loop (default is false) */
  51742. loopAnimation, speedRatio,
  51743. /** defines a callback to call when animation ends if it is not looping */
  51744. onAnimationEnd, animations) {
  51745. if (fromFrame === void 0) { fromFrame = 0; }
  51746. if (toFrame === void 0) { toFrame = 100; }
  51747. if (loopAnimation === void 0) { loopAnimation = false; }
  51748. if (speedRatio === void 0) { speedRatio = 1.0; }
  51749. this.target = target;
  51750. this.fromFrame = fromFrame;
  51751. this.toFrame = toFrame;
  51752. this.loopAnimation = loopAnimation;
  51753. this.onAnimationEnd = onAnimationEnd;
  51754. this._localDelayOffset = null;
  51755. this._pausedDelay = null;
  51756. this._runtimeAnimations = new Array();
  51757. this._paused = false;
  51758. this._speedRatio = 1;
  51759. this._weight = -1.0;
  51760. /**
  51761. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51762. * This will only apply for non looping animation (default is true)
  51763. */
  51764. this.disposeOnEnd = true;
  51765. /**
  51766. * Gets a boolean indicating if the animation has started
  51767. */
  51768. this.animationStarted = false;
  51769. /**
  51770. * Observer raised when the animation ends
  51771. */
  51772. this.onAnimationEndObservable = new BABYLON.Observable();
  51773. this._scene = scene;
  51774. if (animations) {
  51775. this.appendAnimations(target, animations);
  51776. }
  51777. this._speedRatio = speedRatio;
  51778. scene._activeAnimatables.push(this);
  51779. }
  51780. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51781. /**
  51782. * Gets the root Animatable used to synchronize and normalize animations
  51783. */
  51784. get: function () {
  51785. return this._syncRoot;
  51786. },
  51787. enumerable: true,
  51788. configurable: true
  51789. });
  51790. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51791. /**
  51792. * Gets the current frame of the first RuntimeAnimation
  51793. * Used to synchronize Animatables
  51794. */
  51795. get: function () {
  51796. if (this._runtimeAnimations.length === 0) {
  51797. return 0;
  51798. }
  51799. return this._runtimeAnimations[0].currentFrame;
  51800. },
  51801. enumerable: true,
  51802. configurable: true
  51803. });
  51804. Object.defineProperty(Animatable.prototype, "weight", {
  51805. /**
  51806. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51807. */
  51808. get: function () {
  51809. return this._weight;
  51810. },
  51811. set: function (value) {
  51812. if (value === -1) { // -1 is ok and means no weight
  51813. this._weight = -1;
  51814. return;
  51815. }
  51816. // Else weight must be in [0, 1] range
  51817. this._weight = Math.min(Math.max(value, 0), 1.0);
  51818. },
  51819. enumerable: true,
  51820. configurable: true
  51821. });
  51822. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51823. /**
  51824. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51825. */
  51826. get: function () {
  51827. return this._speedRatio;
  51828. },
  51829. set: function (value) {
  51830. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51831. var animation = this._runtimeAnimations[index];
  51832. animation._prepareForSpeedRatioChange(value);
  51833. }
  51834. this._speedRatio = value;
  51835. },
  51836. enumerable: true,
  51837. configurable: true
  51838. });
  51839. // Methods
  51840. /**
  51841. * Synchronize and normalize current Animatable with a source Animatable
  51842. * This is useful when using animation weights and when animations are not of the same length
  51843. * @param root defines the root Animatable to synchronize with
  51844. * @returns the current Animatable
  51845. */
  51846. Animatable.prototype.syncWith = function (root) {
  51847. this._syncRoot = root;
  51848. if (root) {
  51849. // Make sure this animatable will animate after the root
  51850. var index = this._scene._activeAnimatables.indexOf(this);
  51851. if (index > -1) {
  51852. this._scene._activeAnimatables.splice(index, 1);
  51853. this._scene._activeAnimatables.push(this);
  51854. }
  51855. }
  51856. return this;
  51857. };
  51858. /**
  51859. * Gets the list of runtime animations
  51860. * @returns an array of RuntimeAnimation
  51861. */
  51862. Animatable.prototype.getAnimations = function () {
  51863. return this._runtimeAnimations;
  51864. };
  51865. /**
  51866. * Adds more animations to the current animatable
  51867. * @param target defines the target of the animations
  51868. * @param animations defines the new animations to add
  51869. */
  51870. Animatable.prototype.appendAnimations = function (target, animations) {
  51871. for (var index = 0; index < animations.length; index++) {
  51872. var animation = animations[index];
  51873. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51874. }
  51875. };
  51876. /**
  51877. * Gets the source animation for a specific property
  51878. * @param property defines the propertyu to look for
  51879. * @returns null or the source animation for the given property
  51880. */
  51881. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51882. var runtimeAnimations = this._runtimeAnimations;
  51883. for (var index = 0; index < runtimeAnimations.length; index++) {
  51884. if (runtimeAnimations[index].animation.targetProperty === property) {
  51885. return runtimeAnimations[index].animation;
  51886. }
  51887. }
  51888. return null;
  51889. };
  51890. /**
  51891. * Gets the runtime animation for a specific property
  51892. * @param property defines the propertyu to look for
  51893. * @returns null or the runtime animation for the given property
  51894. */
  51895. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51896. var runtimeAnimations = this._runtimeAnimations;
  51897. for (var index = 0; index < runtimeAnimations.length; index++) {
  51898. if (runtimeAnimations[index].animation.targetProperty === property) {
  51899. return runtimeAnimations[index];
  51900. }
  51901. }
  51902. return null;
  51903. };
  51904. /**
  51905. * Resets the animatable to its original state
  51906. */
  51907. Animatable.prototype.reset = function () {
  51908. var runtimeAnimations = this._runtimeAnimations;
  51909. for (var index = 0; index < runtimeAnimations.length; index++) {
  51910. runtimeAnimations[index].reset(true);
  51911. }
  51912. this._localDelayOffset = null;
  51913. this._pausedDelay = null;
  51914. };
  51915. /**
  51916. * Allows the animatable to blend with current running animations
  51917. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51918. * @param blendingSpeed defines the blending speed to use
  51919. */
  51920. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51921. var runtimeAnimations = this._runtimeAnimations;
  51922. for (var index = 0; index < runtimeAnimations.length; index++) {
  51923. runtimeAnimations[index].animation.enableBlending = true;
  51924. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51925. }
  51926. };
  51927. /**
  51928. * Disable animation blending
  51929. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51930. */
  51931. Animatable.prototype.disableBlending = function () {
  51932. var runtimeAnimations = this._runtimeAnimations;
  51933. for (var index = 0; index < runtimeAnimations.length; index++) {
  51934. runtimeAnimations[index].animation.enableBlending = false;
  51935. }
  51936. };
  51937. /**
  51938. * Jump directly to a given frame
  51939. * @param frame defines the frame to jump to
  51940. */
  51941. Animatable.prototype.goToFrame = function (frame) {
  51942. var runtimeAnimations = this._runtimeAnimations;
  51943. if (runtimeAnimations[0]) {
  51944. var fps = runtimeAnimations[0].animation.framePerSecond;
  51945. var currentFrame = runtimeAnimations[0].currentFrame;
  51946. var adjustTime = frame - currentFrame;
  51947. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51948. if (this._localDelayOffset === null) {
  51949. this._localDelayOffset = 0;
  51950. }
  51951. this._localDelayOffset -= delay;
  51952. }
  51953. for (var index = 0; index < runtimeAnimations.length; index++) {
  51954. runtimeAnimations[index].goToFrame(frame);
  51955. }
  51956. };
  51957. /**
  51958. * Pause the animation
  51959. */
  51960. Animatable.prototype.pause = function () {
  51961. if (this._paused) {
  51962. return;
  51963. }
  51964. this._paused = true;
  51965. };
  51966. /**
  51967. * Restart the animation
  51968. */
  51969. Animatable.prototype.restart = function () {
  51970. this._paused = false;
  51971. };
  51972. Animatable.prototype._raiseOnAnimationEnd = function () {
  51973. if (this.onAnimationEnd) {
  51974. this.onAnimationEnd();
  51975. }
  51976. this.onAnimationEndObservable.notifyObservers(this);
  51977. };
  51978. /**
  51979. * Stop and delete the current animation
  51980. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51981. * @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)
  51982. */
  51983. Animatable.prototype.stop = function (animationName, targetMask) {
  51984. if (animationName || targetMask) {
  51985. var idx = this._scene._activeAnimatables.indexOf(this);
  51986. if (idx > -1) {
  51987. var runtimeAnimations = this._runtimeAnimations;
  51988. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51989. var runtimeAnimation = runtimeAnimations[index];
  51990. if (animationName && runtimeAnimation.animation.name != animationName) {
  51991. continue;
  51992. }
  51993. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51994. continue;
  51995. }
  51996. runtimeAnimation.dispose();
  51997. runtimeAnimations.splice(index, 1);
  51998. }
  51999. if (runtimeAnimations.length == 0) {
  52000. this._scene._activeAnimatables.splice(idx, 1);
  52001. this._raiseOnAnimationEnd();
  52002. }
  52003. }
  52004. }
  52005. else {
  52006. var index = this._scene._activeAnimatables.indexOf(this);
  52007. if (index > -1) {
  52008. this._scene._activeAnimatables.splice(index, 1);
  52009. var runtimeAnimations = this._runtimeAnimations;
  52010. for (var index = 0; index < runtimeAnimations.length; index++) {
  52011. runtimeAnimations[index].dispose();
  52012. }
  52013. this._raiseOnAnimationEnd();
  52014. }
  52015. }
  52016. };
  52017. /**
  52018. * Wait asynchronously for the animation to end
  52019. * @returns a promise which will be fullfilled when the animation ends
  52020. */
  52021. Animatable.prototype.waitAsync = function () {
  52022. var _this = this;
  52023. return new Promise(function (resolve, reject) {
  52024. _this.onAnimationEndObservable.add(function () {
  52025. resolve(_this);
  52026. }, undefined, undefined, _this, true);
  52027. });
  52028. };
  52029. /** @hidden */
  52030. Animatable.prototype._animate = function (delay) {
  52031. if (this._paused) {
  52032. this.animationStarted = false;
  52033. if (this._pausedDelay === null) {
  52034. this._pausedDelay = delay;
  52035. }
  52036. return true;
  52037. }
  52038. if (this._localDelayOffset === null) {
  52039. this._localDelayOffset = delay;
  52040. this._pausedDelay = null;
  52041. }
  52042. else if (this._pausedDelay !== null) {
  52043. this._localDelayOffset += delay - this._pausedDelay;
  52044. this._pausedDelay = null;
  52045. }
  52046. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52047. return true;
  52048. }
  52049. // Animating
  52050. var running = false;
  52051. var runtimeAnimations = this._runtimeAnimations;
  52052. var index;
  52053. for (index = 0; index < runtimeAnimations.length; index++) {
  52054. var animation = runtimeAnimations[index];
  52055. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52056. running = running || isRunning;
  52057. }
  52058. this.animationStarted = running;
  52059. if (!running) {
  52060. if (this.disposeOnEnd) {
  52061. // Remove from active animatables
  52062. index = this._scene._activeAnimatables.indexOf(this);
  52063. this._scene._activeAnimatables.splice(index, 1);
  52064. // Dispose all runtime animations
  52065. for (index = 0; index < runtimeAnimations.length; index++) {
  52066. runtimeAnimations[index].dispose();
  52067. }
  52068. }
  52069. this._raiseOnAnimationEnd();
  52070. if (this.disposeOnEnd) {
  52071. this.onAnimationEnd = null;
  52072. this.onAnimationEndObservable.clear();
  52073. }
  52074. }
  52075. return running;
  52076. };
  52077. return Animatable;
  52078. }());
  52079. BABYLON.Animatable = Animatable;
  52080. })(BABYLON || (BABYLON = {}));
  52081. //# sourceMappingURL=babylon.animatable.js.map
  52082. var BABYLON;
  52083. (function (BABYLON) {
  52084. var EasingFunction = /** @class */ (function () {
  52085. function EasingFunction() {
  52086. // Properties
  52087. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52088. }
  52089. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52090. get: function () {
  52091. return EasingFunction._EASINGMODE_EASEIN;
  52092. },
  52093. enumerable: true,
  52094. configurable: true
  52095. });
  52096. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52097. get: function () {
  52098. return EasingFunction._EASINGMODE_EASEOUT;
  52099. },
  52100. enumerable: true,
  52101. configurable: true
  52102. });
  52103. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52104. get: function () {
  52105. return EasingFunction._EASINGMODE_EASEINOUT;
  52106. },
  52107. enumerable: true,
  52108. configurable: true
  52109. });
  52110. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52111. var n = Math.min(Math.max(easingMode, 0), 2);
  52112. this._easingMode = n;
  52113. };
  52114. EasingFunction.prototype.getEasingMode = function () {
  52115. return this._easingMode;
  52116. };
  52117. EasingFunction.prototype.easeInCore = function (gradient) {
  52118. throw new Error('You must implement this method');
  52119. };
  52120. EasingFunction.prototype.ease = function (gradient) {
  52121. switch (this._easingMode) {
  52122. case EasingFunction.EASINGMODE_EASEIN:
  52123. return this.easeInCore(gradient);
  52124. case EasingFunction.EASINGMODE_EASEOUT:
  52125. return (1 - this.easeInCore(1 - gradient));
  52126. }
  52127. if (gradient >= 0.5) {
  52128. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52129. }
  52130. return (this.easeInCore(gradient * 2) * 0.5);
  52131. };
  52132. //Statics
  52133. EasingFunction._EASINGMODE_EASEIN = 0;
  52134. EasingFunction._EASINGMODE_EASEOUT = 1;
  52135. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52136. return EasingFunction;
  52137. }());
  52138. BABYLON.EasingFunction = EasingFunction;
  52139. var CircleEase = /** @class */ (function (_super) {
  52140. __extends(CircleEase, _super);
  52141. function CircleEase() {
  52142. return _super !== null && _super.apply(this, arguments) || this;
  52143. }
  52144. CircleEase.prototype.easeInCore = function (gradient) {
  52145. gradient = Math.max(0, Math.min(1, gradient));
  52146. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52147. };
  52148. return CircleEase;
  52149. }(EasingFunction));
  52150. BABYLON.CircleEase = CircleEase;
  52151. var BackEase = /** @class */ (function (_super) {
  52152. __extends(BackEase, _super);
  52153. function BackEase(amplitude) {
  52154. if (amplitude === void 0) { amplitude = 1; }
  52155. var _this = _super.call(this) || this;
  52156. _this.amplitude = amplitude;
  52157. return _this;
  52158. }
  52159. BackEase.prototype.easeInCore = function (gradient) {
  52160. var num = Math.max(0, this.amplitude);
  52161. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52162. };
  52163. return BackEase;
  52164. }(EasingFunction));
  52165. BABYLON.BackEase = BackEase;
  52166. var BounceEase = /** @class */ (function (_super) {
  52167. __extends(BounceEase, _super);
  52168. function BounceEase(bounces, bounciness) {
  52169. if (bounces === void 0) { bounces = 3; }
  52170. if (bounciness === void 0) { bounciness = 2; }
  52171. var _this = _super.call(this) || this;
  52172. _this.bounces = bounces;
  52173. _this.bounciness = bounciness;
  52174. return _this;
  52175. }
  52176. BounceEase.prototype.easeInCore = function (gradient) {
  52177. var y = Math.max(0.0, this.bounces);
  52178. var bounciness = this.bounciness;
  52179. if (bounciness <= 1.0) {
  52180. bounciness = 1.001;
  52181. }
  52182. var num9 = Math.pow(bounciness, y);
  52183. var num5 = 1.0 - bounciness;
  52184. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52185. var num15 = gradient * num4;
  52186. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52187. var num3 = Math.floor(num65);
  52188. var num13 = num3 + 1.0;
  52189. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52190. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52191. var num7 = (num8 + num12) * 0.5;
  52192. var num6 = gradient - num7;
  52193. var num2 = num7 - num8;
  52194. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52195. };
  52196. return BounceEase;
  52197. }(EasingFunction));
  52198. BABYLON.BounceEase = BounceEase;
  52199. var CubicEase = /** @class */ (function (_super) {
  52200. __extends(CubicEase, _super);
  52201. function CubicEase() {
  52202. return _super !== null && _super.apply(this, arguments) || this;
  52203. }
  52204. CubicEase.prototype.easeInCore = function (gradient) {
  52205. return (gradient * gradient * gradient);
  52206. };
  52207. return CubicEase;
  52208. }(EasingFunction));
  52209. BABYLON.CubicEase = CubicEase;
  52210. var ElasticEase = /** @class */ (function (_super) {
  52211. __extends(ElasticEase, _super);
  52212. function ElasticEase(oscillations, springiness) {
  52213. if (oscillations === void 0) { oscillations = 3; }
  52214. if (springiness === void 0) { springiness = 3; }
  52215. var _this = _super.call(this) || this;
  52216. _this.oscillations = oscillations;
  52217. _this.springiness = springiness;
  52218. return _this;
  52219. }
  52220. ElasticEase.prototype.easeInCore = function (gradient) {
  52221. var num2;
  52222. var num3 = Math.max(0.0, this.oscillations);
  52223. var num = Math.max(0.0, this.springiness);
  52224. if (num == 0) {
  52225. num2 = gradient;
  52226. }
  52227. else {
  52228. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52229. }
  52230. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52231. };
  52232. return ElasticEase;
  52233. }(EasingFunction));
  52234. BABYLON.ElasticEase = ElasticEase;
  52235. var ExponentialEase = /** @class */ (function (_super) {
  52236. __extends(ExponentialEase, _super);
  52237. function ExponentialEase(exponent) {
  52238. if (exponent === void 0) { exponent = 2; }
  52239. var _this = _super.call(this) || this;
  52240. _this.exponent = exponent;
  52241. return _this;
  52242. }
  52243. ExponentialEase.prototype.easeInCore = function (gradient) {
  52244. if (this.exponent <= 0) {
  52245. return gradient;
  52246. }
  52247. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52248. };
  52249. return ExponentialEase;
  52250. }(EasingFunction));
  52251. BABYLON.ExponentialEase = ExponentialEase;
  52252. var PowerEase = /** @class */ (function (_super) {
  52253. __extends(PowerEase, _super);
  52254. function PowerEase(power) {
  52255. if (power === void 0) { power = 2; }
  52256. var _this = _super.call(this) || this;
  52257. _this.power = power;
  52258. return _this;
  52259. }
  52260. PowerEase.prototype.easeInCore = function (gradient) {
  52261. var y = Math.max(0.0, this.power);
  52262. return Math.pow(gradient, y);
  52263. };
  52264. return PowerEase;
  52265. }(EasingFunction));
  52266. BABYLON.PowerEase = PowerEase;
  52267. var QuadraticEase = /** @class */ (function (_super) {
  52268. __extends(QuadraticEase, _super);
  52269. function QuadraticEase() {
  52270. return _super !== null && _super.apply(this, arguments) || this;
  52271. }
  52272. QuadraticEase.prototype.easeInCore = function (gradient) {
  52273. return (gradient * gradient);
  52274. };
  52275. return QuadraticEase;
  52276. }(EasingFunction));
  52277. BABYLON.QuadraticEase = QuadraticEase;
  52278. var QuarticEase = /** @class */ (function (_super) {
  52279. __extends(QuarticEase, _super);
  52280. function QuarticEase() {
  52281. return _super !== null && _super.apply(this, arguments) || this;
  52282. }
  52283. QuarticEase.prototype.easeInCore = function (gradient) {
  52284. return (gradient * gradient * gradient * gradient);
  52285. };
  52286. return QuarticEase;
  52287. }(EasingFunction));
  52288. BABYLON.QuarticEase = QuarticEase;
  52289. var QuinticEase = /** @class */ (function (_super) {
  52290. __extends(QuinticEase, _super);
  52291. function QuinticEase() {
  52292. return _super !== null && _super.apply(this, arguments) || this;
  52293. }
  52294. QuinticEase.prototype.easeInCore = function (gradient) {
  52295. return (gradient * gradient * gradient * gradient * gradient);
  52296. };
  52297. return QuinticEase;
  52298. }(EasingFunction));
  52299. BABYLON.QuinticEase = QuinticEase;
  52300. var SineEase = /** @class */ (function (_super) {
  52301. __extends(SineEase, _super);
  52302. function SineEase() {
  52303. return _super !== null && _super.apply(this, arguments) || this;
  52304. }
  52305. SineEase.prototype.easeInCore = function (gradient) {
  52306. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52307. };
  52308. return SineEase;
  52309. }(EasingFunction));
  52310. BABYLON.SineEase = SineEase;
  52311. var BezierCurveEase = /** @class */ (function (_super) {
  52312. __extends(BezierCurveEase, _super);
  52313. function BezierCurveEase(x1, y1, x2, y2) {
  52314. if (x1 === void 0) { x1 = 0; }
  52315. if (y1 === void 0) { y1 = 0; }
  52316. if (x2 === void 0) { x2 = 1; }
  52317. if (y2 === void 0) { y2 = 1; }
  52318. var _this = _super.call(this) || this;
  52319. _this.x1 = x1;
  52320. _this.y1 = y1;
  52321. _this.x2 = x2;
  52322. _this.y2 = y2;
  52323. return _this;
  52324. }
  52325. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52326. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52327. };
  52328. return BezierCurveEase;
  52329. }(EasingFunction));
  52330. BABYLON.BezierCurveEase = BezierCurveEase;
  52331. })(BABYLON || (BABYLON = {}));
  52332. //# sourceMappingURL=babylon.easing.js.map
  52333. var BABYLON;
  52334. (function (BABYLON) {
  52335. /**
  52336. * A Condition applied to an Action
  52337. */
  52338. var Condition = /** @class */ (function () {
  52339. /**
  52340. * Creates a new Condition
  52341. * @param actionManager the manager of the action the condition is applied to
  52342. */
  52343. function Condition(actionManager) {
  52344. this._actionManager = actionManager;
  52345. }
  52346. /**
  52347. * Check if the current condition is valid
  52348. * @returns a boolean
  52349. */
  52350. Condition.prototype.isValid = function () {
  52351. return true;
  52352. };
  52353. /**
  52354. * Internal only
  52355. * @hidden
  52356. */
  52357. Condition.prototype._getProperty = function (propertyPath) {
  52358. return this._actionManager._getProperty(propertyPath);
  52359. };
  52360. /**
  52361. * Internal only
  52362. * @hidden
  52363. */
  52364. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52365. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52366. };
  52367. /**
  52368. * Serialize placeholder for child classes
  52369. * @returns the serialized object
  52370. */
  52371. Condition.prototype.serialize = function () {
  52372. };
  52373. /**
  52374. * Internal only
  52375. * @hidden
  52376. */
  52377. Condition.prototype._serialize = function (serializedCondition) {
  52378. return {
  52379. type: 2,
  52380. children: [],
  52381. name: serializedCondition.name,
  52382. properties: serializedCondition.properties
  52383. };
  52384. };
  52385. return Condition;
  52386. }());
  52387. BABYLON.Condition = Condition;
  52388. /**
  52389. * Defines specific conditional operators as extensions of Condition
  52390. */
  52391. var ValueCondition = /** @class */ (function (_super) {
  52392. __extends(ValueCondition, _super);
  52393. /**
  52394. * Creates a new ValueCondition
  52395. * @param actionManager manager for the action the condition applies to
  52396. * @param target for the action
  52397. * @param propertyPath path to specify the property of the target the conditional operator uses
  52398. * @param value the value compared by the conditional operator against the current value of the property
  52399. * @param operator the conditional operator, default ValueCondition.IsEqual
  52400. */
  52401. function ValueCondition(actionManager, target,
  52402. /** path to specify the property of the target the conditional operator uses */
  52403. propertyPath,
  52404. /** the value compared by the conditional operator against the current value of the property */
  52405. value,
  52406. /** the conditional operator, default ValueCondition.IsEqual */
  52407. operator) {
  52408. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52409. var _this = _super.call(this, actionManager) || this;
  52410. _this.propertyPath = propertyPath;
  52411. _this.value = value;
  52412. _this.operator = operator;
  52413. _this._target = target;
  52414. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52415. _this._property = _this._getProperty(_this.propertyPath);
  52416. return _this;
  52417. }
  52418. Object.defineProperty(ValueCondition, "IsEqual", {
  52419. /**
  52420. * returns the number for IsEqual
  52421. */
  52422. get: function () {
  52423. return ValueCondition._IsEqual;
  52424. },
  52425. enumerable: true,
  52426. configurable: true
  52427. });
  52428. Object.defineProperty(ValueCondition, "IsDifferent", {
  52429. /**
  52430. * Returns the number for IsDifferent
  52431. */
  52432. get: function () {
  52433. return ValueCondition._IsDifferent;
  52434. },
  52435. enumerable: true,
  52436. configurable: true
  52437. });
  52438. Object.defineProperty(ValueCondition, "IsGreater", {
  52439. /**
  52440. * Returns the number for IsGreater
  52441. */
  52442. get: function () {
  52443. return ValueCondition._IsGreater;
  52444. },
  52445. enumerable: true,
  52446. configurable: true
  52447. });
  52448. Object.defineProperty(ValueCondition, "IsLesser", {
  52449. /**
  52450. * Returns the number for IsLesser
  52451. */
  52452. get: function () {
  52453. return ValueCondition._IsLesser;
  52454. },
  52455. enumerable: true,
  52456. configurable: true
  52457. });
  52458. /**
  52459. * Compares the given value with the property value for the specified conditional operator
  52460. * @returns the result of the comparison
  52461. */
  52462. ValueCondition.prototype.isValid = function () {
  52463. switch (this.operator) {
  52464. case ValueCondition.IsGreater:
  52465. return this._effectiveTarget[this._property] > this.value;
  52466. case ValueCondition.IsLesser:
  52467. return this._effectiveTarget[this._property] < this.value;
  52468. case ValueCondition.IsEqual:
  52469. case ValueCondition.IsDifferent:
  52470. var check;
  52471. if (this.value.equals) {
  52472. check = this.value.equals(this._effectiveTarget[this._property]);
  52473. }
  52474. else {
  52475. check = this.value === this._effectiveTarget[this._property];
  52476. }
  52477. return this.operator === ValueCondition.IsEqual ? check : !check;
  52478. }
  52479. return false;
  52480. };
  52481. /**
  52482. * Serialize the ValueCondition into a JSON compatible object
  52483. * @returns serialization object
  52484. */
  52485. ValueCondition.prototype.serialize = function () {
  52486. return this._serialize({
  52487. name: "ValueCondition",
  52488. properties: [
  52489. BABYLON.Action._GetTargetProperty(this._target),
  52490. { name: "propertyPath", value: this.propertyPath },
  52491. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52492. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52493. ]
  52494. });
  52495. };
  52496. /**
  52497. * Gets the name of the conditional operator for the ValueCondition
  52498. * @param operator the conditional operator
  52499. * @returns the name
  52500. */
  52501. ValueCondition.GetOperatorName = function (operator) {
  52502. switch (operator) {
  52503. case ValueCondition._IsEqual: return "IsEqual";
  52504. case ValueCondition._IsDifferent: return "IsDifferent";
  52505. case ValueCondition._IsGreater: return "IsGreater";
  52506. case ValueCondition._IsLesser: return "IsLesser";
  52507. default: return "";
  52508. }
  52509. };
  52510. /**
  52511. * Internal only
  52512. * @hidden
  52513. */
  52514. ValueCondition._IsEqual = 0;
  52515. /**
  52516. * Internal only
  52517. * @hidden
  52518. */
  52519. ValueCondition._IsDifferent = 1;
  52520. /**
  52521. * Internal only
  52522. * @hidden
  52523. */
  52524. ValueCondition._IsGreater = 2;
  52525. /**
  52526. * Internal only
  52527. * @hidden
  52528. */
  52529. ValueCondition._IsLesser = 3;
  52530. return ValueCondition;
  52531. }(Condition));
  52532. BABYLON.ValueCondition = ValueCondition;
  52533. /**
  52534. * Defines a predicate condition as an extension of Condition
  52535. */
  52536. var PredicateCondition = /** @class */ (function (_super) {
  52537. __extends(PredicateCondition, _super);
  52538. /**
  52539. * Creates a new PredicateCondition
  52540. * @param actionManager manager for the action the condition applies to
  52541. * @param predicate defines the predicate function used to validate the condition
  52542. */
  52543. function PredicateCondition(actionManager,
  52544. /** defines the predicate function used to validate the condition */
  52545. predicate) {
  52546. var _this = _super.call(this, actionManager) || this;
  52547. _this.predicate = predicate;
  52548. return _this;
  52549. }
  52550. /**
  52551. * @returns the validity of the predicate condition
  52552. */
  52553. PredicateCondition.prototype.isValid = function () {
  52554. return this.predicate();
  52555. };
  52556. return PredicateCondition;
  52557. }(Condition));
  52558. BABYLON.PredicateCondition = PredicateCondition;
  52559. /**
  52560. * Defines a state condition as an extension of Condition
  52561. */
  52562. var StateCondition = /** @class */ (function (_super) {
  52563. __extends(StateCondition, _super);
  52564. /**
  52565. * Creates a new StateCondition
  52566. * @param actionManager manager for the action the condition applies to
  52567. * @param target of the condition
  52568. * @param value to compare with target state
  52569. */
  52570. function StateCondition(actionManager, target, value) {
  52571. var _this = _super.call(this, actionManager) || this;
  52572. _this.value = value;
  52573. _this._target = target;
  52574. return _this;
  52575. }
  52576. /**
  52577. * @returns the validity of the state
  52578. */
  52579. StateCondition.prototype.isValid = function () {
  52580. return this._target.state === this.value;
  52581. };
  52582. /**
  52583. * Serialize the StateCondition into a JSON compatible object
  52584. * @returns serialization object
  52585. */
  52586. StateCondition.prototype.serialize = function () {
  52587. return this._serialize({
  52588. name: "StateCondition",
  52589. properties: [
  52590. BABYLON.Action._GetTargetProperty(this._target),
  52591. { name: "value", value: this.value }
  52592. ]
  52593. });
  52594. };
  52595. return StateCondition;
  52596. }(Condition));
  52597. BABYLON.StateCondition = StateCondition;
  52598. })(BABYLON || (BABYLON = {}));
  52599. //# sourceMappingURL=babylon.condition.js.map
  52600. var BABYLON;
  52601. (function (BABYLON) {
  52602. /**
  52603. * The action to be carried out following a trigger
  52604. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52605. */
  52606. var Action = /** @class */ (function () {
  52607. /**
  52608. * Creates a new Action
  52609. * @param triggerOptions the trigger, with or without parameters, for the action
  52610. * @param condition an optional determinant of action
  52611. */
  52612. function Action(
  52613. /** the trigger, with or without parameters, for the action */
  52614. triggerOptions, condition) {
  52615. this.triggerOptions = triggerOptions;
  52616. /**
  52617. * An event triggered prior to action being executed.
  52618. */
  52619. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52620. if (triggerOptions.parameter) {
  52621. this.trigger = triggerOptions.trigger;
  52622. this._triggerParameter = triggerOptions.parameter;
  52623. }
  52624. else {
  52625. this.trigger = triggerOptions;
  52626. }
  52627. this._nextActiveAction = this;
  52628. this._condition = condition;
  52629. }
  52630. /**
  52631. * Internal only
  52632. * @hidden
  52633. */
  52634. Action.prototype._prepare = function () {
  52635. };
  52636. /**
  52637. * Gets the trigger parameters
  52638. * @returns the trigger parameters
  52639. */
  52640. Action.prototype.getTriggerParameter = function () {
  52641. return this._triggerParameter;
  52642. };
  52643. /**
  52644. * Internal only - executes current action event
  52645. * @hidden
  52646. */
  52647. Action.prototype._executeCurrent = function (evt) {
  52648. if (this._nextActiveAction._condition) {
  52649. var condition = this._nextActiveAction._condition;
  52650. var currentRenderId = this._actionManager.getScene().getRenderId();
  52651. // We cache the current evaluation for the current frame
  52652. if (condition._evaluationId === currentRenderId) {
  52653. if (!condition._currentResult) {
  52654. return;
  52655. }
  52656. }
  52657. else {
  52658. condition._evaluationId = currentRenderId;
  52659. if (!condition.isValid()) {
  52660. condition._currentResult = false;
  52661. return;
  52662. }
  52663. condition._currentResult = true;
  52664. }
  52665. }
  52666. this.onBeforeExecuteObservable.notifyObservers(this);
  52667. this._nextActiveAction.execute(evt);
  52668. this.skipToNextActiveAction();
  52669. };
  52670. /**
  52671. * Execute placeholder for child classes
  52672. * @param evt optional action event
  52673. */
  52674. Action.prototype.execute = function (evt) {
  52675. };
  52676. /**
  52677. * Skips to next active action
  52678. */
  52679. Action.prototype.skipToNextActiveAction = function () {
  52680. if (this._nextActiveAction._child) {
  52681. if (!this._nextActiveAction._child._actionManager) {
  52682. this._nextActiveAction._child._actionManager = this._actionManager;
  52683. }
  52684. this._nextActiveAction = this._nextActiveAction._child;
  52685. }
  52686. else {
  52687. this._nextActiveAction = this;
  52688. }
  52689. };
  52690. /**
  52691. * Adds action to chain of actions, may be a DoNothingAction
  52692. * @param action defines the next action to execute
  52693. * @returns The action passed in
  52694. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52695. */
  52696. Action.prototype.then = function (action) {
  52697. this._child = action;
  52698. action._actionManager = this._actionManager;
  52699. action._prepare();
  52700. return action;
  52701. };
  52702. /**
  52703. * Internal only
  52704. * @hidden
  52705. */
  52706. Action.prototype._getProperty = function (propertyPath) {
  52707. return this._actionManager._getProperty(propertyPath);
  52708. };
  52709. /**
  52710. * Internal only
  52711. * @hidden
  52712. */
  52713. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52714. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52715. };
  52716. /**
  52717. * Serialize placeholder for child classes
  52718. * @param parent of child
  52719. * @returns the serialized object
  52720. */
  52721. Action.prototype.serialize = function (parent) {
  52722. };
  52723. /**
  52724. * Internal only called by serialize
  52725. * @hidden
  52726. */
  52727. Action.prototype._serialize = function (serializedAction, parent) {
  52728. var serializationObject = {
  52729. type: 1,
  52730. children: [],
  52731. name: serializedAction.name,
  52732. properties: serializedAction.properties || []
  52733. };
  52734. // Serialize child
  52735. if (this._child) {
  52736. this._child.serialize(serializationObject);
  52737. }
  52738. // Check if "this" has a condition
  52739. if (this._condition) {
  52740. var serializedCondition = this._condition.serialize();
  52741. serializedCondition.children.push(serializationObject);
  52742. if (parent) {
  52743. parent.children.push(serializedCondition);
  52744. }
  52745. return serializedCondition;
  52746. }
  52747. if (parent) {
  52748. parent.children.push(serializationObject);
  52749. }
  52750. return serializationObject;
  52751. };
  52752. /**
  52753. * Internal only
  52754. * @hidden
  52755. */
  52756. Action._SerializeValueAsString = function (value) {
  52757. if (typeof value === "number") {
  52758. return value.toString();
  52759. }
  52760. if (typeof value === "boolean") {
  52761. return value ? "true" : "false";
  52762. }
  52763. if (value instanceof BABYLON.Vector2) {
  52764. return value.x + ", " + value.y;
  52765. }
  52766. if (value instanceof BABYLON.Vector3) {
  52767. return value.x + ", " + value.y + ", " + value.z;
  52768. }
  52769. if (value instanceof BABYLON.Color3) {
  52770. return value.r + ", " + value.g + ", " + value.b;
  52771. }
  52772. if (value instanceof BABYLON.Color4) {
  52773. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52774. }
  52775. return value; // string
  52776. };
  52777. /**
  52778. * Internal only
  52779. * @hidden
  52780. */
  52781. Action._GetTargetProperty = function (target) {
  52782. return {
  52783. name: "target",
  52784. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52785. : target instanceof BABYLON.Light ? "LightProperties"
  52786. : target instanceof BABYLON.Camera ? "CameraProperties"
  52787. : "SceneProperties",
  52788. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52789. };
  52790. };
  52791. return Action;
  52792. }());
  52793. BABYLON.Action = Action;
  52794. })(BABYLON || (BABYLON = {}));
  52795. //# sourceMappingURL=babylon.action.js.map
  52796. var BABYLON;
  52797. (function (BABYLON) {
  52798. /**
  52799. * ActionEvent is the event being sent when an action is triggered.
  52800. */
  52801. var ActionEvent = /** @class */ (function () {
  52802. /**
  52803. * Creates a new ActionEvent
  52804. * @param source The mesh or sprite that triggered the action
  52805. * @param pointerX The X mouse cursor position at the time of the event
  52806. * @param pointerY The Y mouse cursor position at the time of the event
  52807. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52808. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52809. * @param additionalData additional data for the event
  52810. */
  52811. function ActionEvent(
  52812. /** The mesh or sprite that triggered the action */
  52813. source,
  52814. /** The X mouse cursor position at the time of the event */
  52815. pointerX,
  52816. /** The Y mouse cursor position at the time of the event */
  52817. pointerY,
  52818. /** The mesh that is currently pointed at (can be null) */
  52819. meshUnderPointer,
  52820. /** the original (browser) event that triggered the ActionEvent */
  52821. sourceEvent,
  52822. /** additional data for the event */
  52823. additionalData) {
  52824. this.source = source;
  52825. this.pointerX = pointerX;
  52826. this.pointerY = pointerY;
  52827. this.meshUnderPointer = meshUnderPointer;
  52828. this.sourceEvent = sourceEvent;
  52829. this.additionalData = additionalData;
  52830. }
  52831. /**
  52832. * Helper function to auto-create an ActionEvent from a source mesh.
  52833. * @param source The source mesh that triggered the event
  52834. * @param evt The original (browser) event
  52835. * @param additionalData additional data for the event
  52836. * @returns the new ActionEvent
  52837. */
  52838. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52839. var scene = source.getScene();
  52840. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52841. };
  52842. /**
  52843. * Helper function to auto-create an ActionEvent from a source sprite
  52844. * @param source The source sprite that triggered the event
  52845. * @param scene Scene associated with the sprite
  52846. * @param evt The original (browser) event
  52847. * @param additionalData additional data for the event
  52848. * @returns the new ActionEvent
  52849. */
  52850. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52851. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52852. };
  52853. /**
  52854. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52855. * @param scene the scene where the event occurred
  52856. * @param evt The original (browser) event
  52857. * @returns the new ActionEvent
  52858. */
  52859. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52860. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52861. };
  52862. /**
  52863. * Helper function to auto-create an ActionEvent from a primitive
  52864. * @param prim defines the target primitive
  52865. * @param pointerPos defines the pointer position
  52866. * @param evt The original (browser) event
  52867. * @param additionalData additional data for the event
  52868. * @returns the new ActionEvent
  52869. */
  52870. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52871. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52872. };
  52873. return ActionEvent;
  52874. }());
  52875. BABYLON.ActionEvent = ActionEvent;
  52876. /**
  52877. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52878. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52879. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52880. */
  52881. var ActionManager = /** @class */ (function () {
  52882. /**
  52883. * Creates a new action manager
  52884. * @param scene defines the hosting scene
  52885. */
  52886. function ActionManager(scene) {
  52887. // Members
  52888. /** Gets the list of actions */
  52889. this.actions = new Array();
  52890. /** Gets the cursor to use when hovering items */
  52891. this.hoverCursor = '';
  52892. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52893. scene.actionManagers.push(this);
  52894. }
  52895. Object.defineProperty(ActionManager, "NothingTrigger", {
  52896. /**
  52897. * Nothing
  52898. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52899. */
  52900. get: function () {
  52901. return ActionManager._NothingTrigger;
  52902. },
  52903. enumerable: true,
  52904. configurable: true
  52905. });
  52906. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52907. /**
  52908. * On pick
  52909. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52910. */
  52911. get: function () {
  52912. return ActionManager._OnPickTrigger;
  52913. },
  52914. enumerable: true,
  52915. configurable: true
  52916. });
  52917. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52918. /**
  52919. * On left pick
  52920. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52921. */
  52922. get: function () {
  52923. return ActionManager._OnLeftPickTrigger;
  52924. },
  52925. enumerable: true,
  52926. configurable: true
  52927. });
  52928. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52929. /**
  52930. * On right pick
  52931. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52932. */
  52933. get: function () {
  52934. return ActionManager._OnRightPickTrigger;
  52935. },
  52936. enumerable: true,
  52937. configurable: true
  52938. });
  52939. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52940. /**
  52941. * On center pick
  52942. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52943. */
  52944. get: function () {
  52945. return ActionManager._OnCenterPickTrigger;
  52946. },
  52947. enumerable: true,
  52948. configurable: true
  52949. });
  52950. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52951. /**
  52952. * On pick down
  52953. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52954. */
  52955. get: function () {
  52956. return ActionManager._OnPickDownTrigger;
  52957. },
  52958. enumerable: true,
  52959. configurable: true
  52960. });
  52961. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52962. /**
  52963. * On double pick
  52964. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52965. */
  52966. get: function () {
  52967. return ActionManager._OnDoublePickTrigger;
  52968. },
  52969. enumerable: true,
  52970. configurable: true
  52971. });
  52972. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52973. /**
  52974. * On pick up
  52975. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52976. */
  52977. get: function () {
  52978. return ActionManager._OnPickUpTrigger;
  52979. },
  52980. enumerable: true,
  52981. configurable: true
  52982. });
  52983. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52984. /**
  52985. * On pick out.
  52986. * This trigger will only be raised if you also declared a OnPickDown
  52987. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52988. */
  52989. get: function () {
  52990. return ActionManager._OnPickOutTrigger;
  52991. },
  52992. enumerable: true,
  52993. configurable: true
  52994. });
  52995. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52996. /**
  52997. * On long press
  52998. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52999. */
  53000. get: function () {
  53001. return ActionManager._OnLongPressTrigger;
  53002. },
  53003. enumerable: true,
  53004. configurable: true
  53005. });
  53006. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53007. /**
  53008. * On pointer over
  53009. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53010. */
  53011. get: function () {
  53012. return ActionManager._OnPointerOverTrigger;
  53013. },
  53014. enumerable: true,
  53015. configurable: true
  53016. });
  53017. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53018. /**
  53019. * On pointer out
  53020. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53021. */
  53022. get: function () {
  53023. return ActionManager._OnPointerOutTrigger;
  53024. },
  53025. enumerable: true,
  53026. configurable: true
  53027. });
  53028. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53029. /**
  53030. * On every frame
  53031. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53032. */
  53033. get: function () {
  53034. return ActionManager._OnEveryFrameTrigger;
  53035. },
  53036. enumerable: true,
  53037. configurable: true
  53038. });
  53039. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53040. /**
  53041. * On intersection enter
  53042. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53043. */
  53044. get: function () {
  53045. return ActionManager._OnIntersectionEnterTrigger;
  53046. },
  53047. enumerable: true,
  53048. configurable: true
  53049. });
  53050. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53051. /**
  53052. * On intersection exit
  53053. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53054. */
  53055. get: function () {
  53056. return ActionManager._OnIntersectionExitTrigger;
  53057. },
  53058. enumerable: true,
  53059. configurable: true
  53060. });
  53061. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53062. /**
  53063. * On key down
  53064. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53065. */
  53066. get: function () {
  53067. return ActionManager._OnKeyDownTrigger;
  53068. },
  53069. enumerable: true,
  53070. configurable: true
  53071. });
  53072. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53073. /**
  53074. * On key up
  53075. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53076. */
  53077. get: function () {
  53078. return ActionManager._OnKeyUpTrigger;
  53079. },
  53080. enumerable: true,
  53081. configurable: true
  53082. });
  53083. // Methods
  53084. /**
  53085. * Releases all associated resources
  53086. */
  53087. ActionManager.prototype.dispose = function () {
  53088. var index = this._scene.actionManagers.indexOf(this);
  53089. for (var i = 0; i < this.actions.length; i++) {
  53090. var action = this.actions[i];
  53091. ActionManager.Triggers[action.trigger]--;
  53092. if (ActionManager.Triggers[action.trigger] === 0) {
  53093. delete ActionManager.Triggers[action.trigger];
  53094. }
  53095. }
  53096. if (index > -1) {
  53097. this._scene.actionManagers.splice(index, 1);
  53098. }
  53099. };
  53100. /**
  53101. * Gets hosting scene
  53102. * @returns the hosting scene
  53103. */
  53104. ActionManager.prototype.getScene = function () {
  53105. return this._scene;
  53106. };
  53107. /**
  53108. * Does this action manager handles actions of any of the given triggers
  53109. * @param triggers defines the triggers to be tested
  53110. * @return a boolean indicating whether one (or more) of the triggers is handled
  53111. */
  53112. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53113. for (var index = 0; index < this.actions.length; index++) {
  53114. var action = this.actions[index];
  53115. if (triggers.indexOf(action.trigger) > -1) {
  53116. return true;
  53117. }
  53118. }
  53119. return false;
  53120. };
  53121. /**
  53122. * Does this action manager handles actions of a given trigger
  53123. * @param trigger defines the trigger to be tested
  53124. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53125. * @return whether the trigger is handled
  53126. */
  53127. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53128. for (var index = 0; index < this.actions.length; index++) {
  53129. var action = this.actions[index];
  53130. if (action.trigger === trigger) {
  53131. if (parameterPredicate) {
  53132. if (parameterPredicate(action.getTriggerParameter())) {
  53133. return true;
  53134. }
  53135. }
  53136. else {
  53137. return true;
  53138. }
  53139. }
  53140. }
  53141. return false;
  53142. };
  53143. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53144. /**
  53145. * Does this action manager has pointer triggers
  53146. */
  53147. get: function () {
  53148. for (var index = 0; index < this.actions.length; index++) {
  53149. var action = this.actions[index];
  53150. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53151. return true;
  53152. }
  53153. }
  53154. return false;
  53155. },
  53156. enumerable: true,
  53157. configurable: true
  53158. });
  53159. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53160. /**
  53161. * Does this action manager has pick triggers
  53162. */
  53163. get: function () {
  53164. for (var index = 0; index < this.actions.length; index++) {
  53165. var action = this.actions[index];
  53166. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53167. return true;
  53168. }
  53169. }
  53170. return false;
  53171. },
  53172. enumerable: true,
  53173. configurable: true
  53174. });
  53175. Object.defineProperty(ActionManager, "HasTriggers", {
  53176. /**
  53177. * Does exist one action manager with at least one trigger
  53178. **/
  53179. get: function () {
  53180. for (var t in ActionManager.Triggers) {
  53181. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53182. return true;
  53183. }
  53184. }
  53185. return false;
  53186. },
  53187. enumerable: true,
  53188. configurable: true
  53189. });
  53190. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53191. /**
  53192. * Does exist one action manager with at least one pick trigger
  53193. **/
  53194. get: function () {
  53195. for (var t in ActionManager.Triggers) {
  53196. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53197. var t_int = parseInt(t);
  53198. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53199. return true;
  53200. }
  53201. }
  53202. }
  53203. return false;
  53204. },
  53205. enumerable: true,
  53206. configurable: true
  53207. });
  53208. /**
  53209. * Does exist one action manager that handles actions of a given trigger
  53210. * @param trigger defines the trigger to be tested
  53211. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53212. **/
  53213. ActionManager.HasSpecificTrigger = function (trigger) {
  53214. for (var t in ActionManager.Triggers) {
  53215. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53216. var t_int = parseInt(t);
  53217. if (t_int === trigger) {
  53218. return true;
  53219. }
  53220. }
  53221. }
  53222. return false;
  53223. };
  53224. /**
  53225. * Registers an action to this action manager
  53226. * @param action defines the action to be registered
  53227. * @return the action amended (prepared) after registration
  53228. */
  53229. ActionManager.prototype.registerAction = function (action) {
  53230. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53231. if (this.getScene().actionManager !== this) {
  53232. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53233. return null;
  53234. }
  53235. }
  53236. this.actions.push(action);
  53237. if (ActionManager.Triggers[action.trigger]) {
  53238. ActionManager.Triggers[action.trigger]++;
  53239. }
  53240. else {
  53241. ActionManager.Triggers[action.trigger] = 1;
  53242. }
  53243. action._actionManager = this;
  53244. action._prepare();
  53245. return action;
  53246. };
  53247. /**
  53248. * Unregisters an action to this action manager
  53249. * @param action defines the action to be unregistered
  53250. * @return a boolean indicating whether the action has been unregistered
  53251. */
  53252. ActionManager.prototype.unregisterAction = function (action) {
  53253. var index = this.actions.indexOf(action);
  53254. if (index !== -1) {
  53255. this.actions.splice(index, 1);
  53256. ActionManager.Triggers[action.trigger] -= 1;
  53257. if (ActionManager.Triggers[action.trigger] === 0) {
  53258. delete ActionManager.Triggers[action.trigger];
  53259. }
  53260. delete action._actionManager;
  53261. return true;
  53262. }
  53263. return false;
  53264. };
  53265. /**
  53266. * Process a specific trigger
  53267. * @param trigger defines the trigger to process
  53268. * @param evt defines the event details to be processed
  53269. */
  53270. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53271. for (var index = 0; index < this.actions.length; index++) {
  53272. var action = this.actions[index];
  53273. if (action.trigger === trigger) {
  53274. if (evt) {
  53275. if (trigger === ActionManager.OnKeyUpTrigger
  53276. || trigger === ActionManager.OnKeyDownTrigger) {
  53277. var parameter = action.getTriggerParameter();
  53278. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53279. if (!parameter.toLowerCase) {
  53280. continue;
  53281. }
  53282. var lowerCase = parameter.toLowerCase();
  53283. if (lowerCase !== evt.sourceEvent.key) {
  53284. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53285. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53286. if (actualkey !== lowerCase) {
  53287. continue;
  53288. }
  53289. }
  53290. }
  53291. }
  53292. }
  53293. action._executeCurrent(evt);
  53294. }
  53295. }
  53296. };
  53297. /** @hidden */
  53298. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53299. var properties = propertyPath.split(".");
  53300. for (var index = 0; index < properties.length - 1; index++) {
  53301. target = target[properties[index]];
  53302. }
  53303. return target;
  53304. };
  53305. /** @hidden */
  53306. ActionManager.prototype._getProperty = function (propertyPath) {
  53307. var properties = propertyPath.split(".");
  53308. return properties[properties.length - 1];
  53309. };
  53310. /**
  53311. * Serialize this manager to a JSON object
  53312. * @param name defines the property name to store this manager
  53313. * @returns a JSON representation of this manager
  53314. */
  53315. ActionManager.prototype.serialize = function (name) {
  53316. var root = {
  53317. children: new Array(),
  53318. name: name,
  53319. type: 3,
  53320. properties: new Array() // Empty for root but required
  53321. };
  53322. for (var i = 0; i < this.actions.length; i++) {
  53323. var triggerObject = {
  53324. type: 0,
  53325. children: new Array(),
  53326. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53327. properties: new Array()
  53328. };
  53329. var triggerOptions = this.actions[i].triggerOptions;
  53330. if (triggerOptions && typeof triggerOptions !== "number") {
  53331. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53332. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53333. }
  53334. else {
  53335. var parameter = {};
  53336. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53337. if (triggerOptions.parameter.mesh) {
  53338. parameter._meshId = triggerOptions.parameter.mesh.id;
  53339. }
  53340. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53341. }
  53342. }
  53343. // Serialize child action, recursively
  53344. this.actions[i].serialize(triggerObject);
  53345. // Add serialized trigger
  53346. root.children.push(triggerObject);
  53347. }
  53348. return root;
  53349. };
  53350. /**
  53351. * Creates a new ActionManager from a JSON data
  53352. * @param parsedActions defines the JSON data to read from
  53353. * @param object defines the hosting mesh
  53354. * @param scene defines the hosting scene
  53355. */
  53356. ActionManager.Parse = function (parsedActions, object, scene) {
  53357. var actionManager = new ActionManager(scene);
  53358. if (object === null)
  53359. scene.actionManager = actionManager;
  53360. else
  53361. object.actionManager = actionManager;
  53362. // instanciate a new object
  53363. var instanciate = function (name, params) {
  53364. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53365. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53366. newInstance.constructor.apply(newInstance, params);
  53367. return newInstance;
  53368. };
  53369. var parseParameter = function (name, value, target, propertyPath) {
  53370. if (propertyPath === null) {
  53371. // String, boolean or float
  53372. var floatValue = parseFloat(value);
  53373. if (value === "true" || value === "false")
  53374. return value === "true";
  53375. else
  53376. return isNaN(floatValue) ? value : floatValue;
  53377. }
  53378. var effectiveTarget = propertyPath.split(".");
  53379. var values = value.split(",");
  53380. // Get effective Target
  53381. for (var i = 0; i < effectiveTarget.length; i++) {
  53382. target = target[effectiveTarget[i]];
  53383. }
  53384. // Return appropriate value with its type
  53385. if (typeof (target) === "boolean")
  53386. return values[0] === "true";
  53387. if (typeof (target) === "string")
  53388. return values[0];
  53389. // Parameters with multiple values such as Vector3 etc.
  53390. var split = new Array();
  53391. for (var i = 0; i < values.length; i++)
  53392. split.push(parseFloat(values[i]));
  53393. if (target instanceof BABYLON.Vector3)
  53394. return BABYLON.Vector3.FromArray(split);
  53395. if (target instanceof BABYLON.Vector4)
  53396. return BABYLON.Vector4.FromArray(split);
  53397. if (target instanceof BABYLON.Color3)
  53398. return BABYLON.Color3.FromArray(split);
  53399. if (target instanceof BABYLON.Color4)
  53400. return BABYLON.Color4.FromArray(split);
  53401. return parseFloat(values[0]);
  53402. };
  53403. // traverse graph per trigger
  53404. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53405. if (combineArray === void 0) { combineArray = null; }
  53406. if (parsedAction.detached)
  53407. return;
  53408. var parameters = new Array();
  53409. var target = null;
  53410. var propertyPath = null;
  53411. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53412. // Parameters
  53413. if (parsedAction.type === 2)
  53414. parameters.push(actionManager);
  53415. else
  53416. parameters.push(trigger);
  53417. if (combine) {
  53418. var actions = new Array();
  53419. for (var j = 0; j < parsedAction.combine.length; j++) {
  53420. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53421. }
  53422. parameters.push(actions);
  53423. }
  53424. else {
  53425. for (var i = 0; i < parsedAction.properties.length; i++) {
  53426. var value = parsedAction.properties[i].value;
  53427. var name = parsedAction.properties[i].name;
  53428. var targetType = parsedAction.properties[i].targetType;
  53429. if (name === "target")
  53430. if (targetType !== null && targetType === "SceneProperties")
  53431. value = target = scene;
  53432. else
  53433. value = target = scene.getNodeByName(value);
  53434. else if (name === "parent")
  53435. value = scene.getNodeByName(value);
  53436. else if (name === "sound")
  53437. value = scene.getSoundByName(value);
  53438. else if (name !== "propertyPath") {
  53439. if (parsedAction.type === 2 && name === "operator")
  53440. value = BABYLON.ValueCondition[value];
  53441. else
  53442. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53443. }
  53444. else {
  53445. propertyPath = value;
  53446. }
  53447. parameters.push(value);
  53448. }
  53449. }
  53450. if (combineArray === null) {
  53451. parameters.push(condition);
  53452. }
  53453. else {
  53454. parameters.push(null);
  53455. }
  53456. // If interpolate value action
  53457. if (parsedAction.name === "InterpolateValueAction") {
  53458. var param = parameters[parameters.length - 2];
  53459. parameters[parameters.length - 1] = param;
  53460. parameters[parameters.length - 2] = condition;
  53461. }
  53462. // Action or condition(s) and not CombineAction
  53463. var newAction = instanciate(parsedAction.name, parameters);
  53464. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53465. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53466. if (action)
  53467. action.then(nothing);
  53468. else
  53469. actionManager.registerAction(nothing);
  53470. action = nothing;
  53471. }
  53472. if (combineArray === null) {
  53473. if (newAction instanceof BABYLON.Condition) {
  53474. condition = newAction;
  53475. newAction = action;
  53476. }
  53477. else {
  53478. condition = null;
  53479. if (action)
  53480. action.then(newAction);
  53481. else
  53482. actionManager.registerAction(newAction);
  53483. }
  53484. }
  53485. else {
  53486. combineArray.push(newAction);
  53487. }
  53488. for (var i = 0; i < parsedAction.children.length; i++)
  53489. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53490. };
  53491. // triggers
  53492. for (var i = 0; i < parsedActions.children.length; i++) {
  53493. var triggerParams;
  53494. var trigger = parsedActions.children[i];
  53495. if (trigger.properties.length > 0) {
  53496. var param = trigger.properties[0].value;
  53497. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53498. if (value._meshId) {
  53499. value.mesh = scene.getMeshByID(value._meshId);
  53500. }
  53501. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53502. }
  53503. else
  53504. triggerParams = ActionManager[trigger.name];
  53505. for (var j = 0; j < trigger.children.length; j++) {
  53506. if (!trigger.detached)
  53507. traverse(trigger.children[j], triggerParams, null, null);
  53508. }
  53509. }
  53510. };
  53511. /**
  53512. * Get a trigger name by index
  53513. * @param trigger defines the trigger index
  53514. * @returns a trigger name
  53515. */
  53516. ActionManager.GetTriggerName = function (trigger) {
  53517. switch (trigger) {
  53518. case 0: return "NothingTrigger";
  53519. case 1: return "OnPickTrigger";
  53520. case 2: return "OnLeftPickTrigger";
  53521. case 3: return "OnRightPickTrigger";
  53522. case 4: return "OnCenterPickTrigger";
  53523. case 5: return "OnPickDownTrigger";
  53524. case 6: return "OnPickUpTrigger";
  53525. case 7: return "OnLongPressTrigger";
  53526. case 8: return "OnPointerOverTrigger";
  53527. case 9: return "OnPointerOutTrigger";
  53528. case 10: return "OnEveryFrameTrigger";
  53529. case 11: return "OnIntersectionEnterTrigger";
  53530. case 12: return "OnIntersectionExitTrigger";
  53531. case 13: return "OnKeyDownTrigger";
  53532. case 14: return "OnKeyUpTrigger";
  53533. case 15: return "OnPickOutTrigger";
  53534. default: return "";
  53535. }
  53536. };
  53537. // Statics
  53538. ActionManager._NothingTrigger = 0;
  53539. ActionManager._OnPickTrigger = 1;
  53540. ActionManager._OnLeftPickTrigger = 2;
  53541. ActionManager._OnRightPickTrigger = 3;
  53542. ActionManager._OnCenterPickTrigger = 4;
  53543. ActionManager._OnPickDownTrigger = 5;
  53544. ActionManager._OnDoublePickTrigger = 6;
  53545. ActionManager._OnPickUpTrigger = 7;
  53546. ActionManager._OnLongPressTrigger = 8;
  53547. ActionManager._OnPointerOverTrigger = 9;
  53548. ActionManager._OnPointerOutTrigger = 10;
  53549. ActionManager._OnEveryFrameTrigger = 11;
  53550. ActionManager._OnIntersectionEnterTrigger = 12;
  53551. ActionManager._OnIntersectionExitTrigger = 13;
  53552. ActionManager._OnKeyDownTrigger = 14;
  53553. ActionManager._OnKeyUpTrigger = 15;
  53554. ActionManager._OnPickOutTrigger = 16;
  53555. /** Gets the list of active triggers */
  53556. ActionManager.Triggers = {};
  53557. return ActionManager;
  53558. }());
  53559. BABYLON.ActionManager = ActionManager;
  53560. })(BABYLON || (BABYLON = {}));
  53561. //# sourceMappingURL=babylon.actionManager.js.map
  53562. var BABYLON;
  53563. (function (BABYLON) {
  53564. var InterpolateValueAction = /** @class */ (function (_super) {
  53565. __extends(InterpolateValueAction, _super);
  53566. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53567. if (duration === void 0) { duration = 1000; }
  53568. var _this = _super.call(this, triggerOptions, condition) || this;
  53569. _this.propertyPath = propertyPath;
  53570. _this.value = value;
  53571. _this.duration = duration;
  53572. _this.stopOtherAnimations = stopOtherAnimations;
  53573. _this.onInterpolationDone = onInterpolationDone;
  53574. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53575. _this._target = _this._effectiveTarget = target;
  53576. return _this;
  53577. }
  53578. /** @hidden */
  53579. InterpolateValueAction.prototype._prepare = function () {
  53580. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53581. this._property = this._getProperty(this.propertyPath);
  53582. };
  53583. InterpolateValueAction.prototype.execute = function () {
  53584. var _this = this;
  53585. var scene = this._actionManager.getScene();
  53586. var keys = [
  53587. {
  53588. frame: 0,
  53589. value: this._effectiveTarget[this._property]
  53590. }, {
  53591. frame: 100,
  53592. value: this.value
  53593. }
  53594. ];
  53595. var dataType;
  53596. if (typeof this.value === "number") {
  53597. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53598. }
  53599. else if (this.value instanceof BABYLON.Color3) {
  53600. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53601. }
  53602. else if (this.value instanceof BABYLON.Vector3) {
  53603. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53604. }
  53605. else if (this.value instanceof BABYLON.Matrix) {
  53606. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53607. }
  53608. else if (this.value instanceof BABYLON.Quaternion) {
  53609. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53610. }
  53611. else {
  53612. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53613. return;
  53614. }
  53615. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53616. animation.setKeys(keys);
  53617. if (this.stopOtherAnimations) {
  53618. scene.stopAnimation(this._effectiveTarget);
  53619. }
  53620. var wrapper = function () {
  53621. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53622. if (_this.onInterpolationDone) {
  53623. _this.onInterpolationDone();
  53624. }
  53625. };
  53626. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53627. };
  53628. InterpolateValueAction.prototype.serialize = function (parent) {
  53629. return _super.prototype._serialize.call(this, {
  53630. name: "InterpolateValueAction",
  53631. properties: [
  53632. BABYLON.Action._GetTargetProperty(this._target),
  53633. { name: "propertyPath", value: this.propertyPath },
  53634. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53635. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53636. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53637. ]
  53638. }, parent);
  53639. };
  53640. return InterpolateValueAction;
  53641. }(BABYLON.Action));
  53642. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53643. })(BABYLON || (BABYLON = {}));
  53644. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53645. var BABYLON;
  53646. (function (BABYLON) {
  53647. var SwitchBooleanAction = /** @class */ (function (_super) {
  53648. __extends(SwitchBooleanAction, _super);
  53649. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53650. var _this = _super.call(this, triggerOptions, condition) || this;
  53651. _this.propertyPath = propertyPath;
  53652. _this._target = _this._effectiveTarget = target;
  53653. return _this;
  53654. }
  53655. /** @hidden */
  53656. SwitchBooleanAction.prototype._prepare = function () {
  53657. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53658. this._property = this._getProperty(this.propertyPath);
  53659. };
  53660. SwitchBooleanAction.prototype.execute = function () {
  53661. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53662. };
  53663. SwitchBooleanAction.prototype.serialize = function (parent) {
  53664. return _super.prototype._serialize.call(this, {
  53665. name: "SwitchBooleanAction",
  53666. properties: [
  53667. BABYLON.Action._GetTargetProperty(this._target),
  53668. { name: "propertyPath", value: this.propertyPath }
  53669. ]
  53670. }, parent);
  53671. };
  53672. return SwitchBooleanAction;
  53673. }(BABYLON.Action));
  53674. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53675. var SetStateAction = /** @class */ (function (_super) {
  53676. __extends(SetStateAction, _super);
  53677. function SetStateAction(triggerOptions, target, value, condition) {
  53678. var _this = _super.call(this, triggerOptions, condition) || this;
  53679. _this.value = value;
  53680. _this._target = target;
  53681. return _this;
  53682. }
  53683. SetStateAction.prototype.execute = function () {
  53684. this._target.state = this.value;
  53685. };
  53686. SetStateAction.prototype.serialize = function (parent) {
  53687. return _super.prototype._serialize.call(this, {
  53688. name: "SetStateAction",
  53689. properties: [
  53690. BABYLON.Action._GetTargetProperty(this._target),
  53691. { name: "value", value: this.value }
  53692. ]
  53693. }, parent);
  53694. };
  53695. return SetStateAction;
  53696. }(BABYLON.Action));
  53697. BABYLON.SetStateAction = SetStateAction;
  53698. var SetValueAction = /** @class */ (function (_super) {
  53699. __extends(SetValueAction, _super);
  53700. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53701. var _this = _super.call(this, triggerOptions, condition) || this;
  53702. _this.propertyPath = propertyPath;
  53703. _this.value = value;
  53704. _this._target = _this._effectiveTarget = target;
  53705. return _this;
  53706. }
  53707. /** @hidden */
  53708. SetValueAction.prototype._prepare = function () {
  53709. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53710. this._property = this._getProperty(this.propertyPath);
  53711. };
  53712. SetValueAction.prototype.execute = function () {
  53713. this._effectiveTarget[this._property] = this.value;
  53714. if (this._target.markAsDirty) {
  53715. this._target.markAsDirty(this._property);
  53716. }
  53717. };
  53718. SetValueAction.prototype.serialize = function (parent) {
  53719. return _super.prototype._serialize.call(this, {
  53720. name: "SetValueAction",
  53721. properties: [
  53722. BABYLON.Action._GetTargetProperty(this._target),
  53723. { name: "propertyPath", value: this.propertyPath },
  53724. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53725. ]
  53726. }, parent);
  53727. };
  53728. return SetValueAction;
  53729. }(BABYLON.Action));
  53730. BABYLON.SetValueAction = SetValueAction;
  53731. var IncrementValueAction = /** @class */ (function (_super) {
  53732. __extends(IncrementValueAction, _super);
  53733. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53734. var _this = _super.call(this, triggerOptions, condition) || this;
  53735. _this.propertyPath = propertyPath;
  53736. _this.value = value;
  53737. _this._target = _this._effectiveTarget = target;
  53738. return _this;
  53739. }
  53740. /** @hidden */
  53741. IncrementValueAction.prototype._prepare = function () {
  53742. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53743. this._property = this._getProperty(this.propertyPath);
  53744. if (typeof this._effectiveTarget[this._property] !== "number") {
  53745. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53746. }
  53747. };
  53748. IncrementValueAction.prototype.execute = function () {
  53749. this._effectiveTarget[this._property] += this.value;
  53750. if (this._target.markAsDirty) {
  53751. this._target.markAsDirty(this._property);
  53752. }
  53753. };
  53754. IncrementValueAction.prototype.serialize = function (parent) {
  53755. return _super.prototype._serialize.call(this, {
  53756. name: "IncrementValueAction",
  53757. properties: [
  53758. BABYLON.Action._GetTargetProperty(this._target),
  53759. { name: "propertyPath", value: this.propertyPath },
  53760. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53761. ]
  53762. }, parent);
  53763. };
  53764. return IncrementValueAction;
  53765. }(BABYLON.Action));
  53766. BABYLON.IncrementValueAction = IncrementValueAction;
  53767. var PlayAnimationAction = /** @class */ (function (_super) {
  53768. __extends(PlayAnimationAction, _super);
  53769. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53770. var _this = _super.call(this, triggerOptions, condition) || this;
  53771. _this.from = from;
  53772. _this.to = to;
  53773. _this.loop = loop;
  53774. _this._target = target;
  53775. return _this;
  53776. }
  53777. /** @hidden */
  53778. PlayAnimationAction.prototype._prepare = function () {
  53779. };
  53780. PlayAnimationAction.prototype.execute = function () {
  53781. var scene = this._actionManager.getScene();
  53782. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53783. };
  53784. PlayAnimationAction.prototype.serialize = function (parent) {
  53785. return _super.prototype._serialize.call(this, {
  53786. name: "PlayAnimationAction",
  53787. properties: [
  53788. BABYLON.Action._GetTargetProperty(this._target),
  53789. { name: "from", value: String(this.from) },
  53790. { name: "to", value: String(this.to) },
  53791. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53792. ]
  53793. }, parent);
  53794. };
  53795. return PlayAnimationAction;
  53796. }(BABYLON.Action));
  53797. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53798. var StopAnimationAction = /** @class */ (function (_super) {
  53799. __extends(StopAnimationAction, _super);
  53800. function StopAnimationAction(triggerOptions, target, condition) {
  53801. var _this = _super.call(this, triggerOptions, condition) || this;
  53802. _this._target = target;
  53803. return _this;
  53804. }
  53805. /** @hidden */
  53806. StopAnimationAction.prototype._prepare = function () {
  53807. };
  53808. StopAnimationAction.prototype.execute = function () {
  53809. var scene = this._actionManager.getScene();
  53810. scene.stopAnimation(this._target);
  53811. };
  53812. StopAnimationAction.prototype.serialize = function (parent) {
  53813. return _super.prototype._serialize.call(this, {
  53814. name: "StopAnimationAction",
  53815. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53816. }, parent);
  53817. };
  53818. return StopAnimationAction;
  53819. }(BABYLON.Action));
  53820. BABYLON.StopAnimationAction = StopAnimationAction;
  53821. var DoNothingAction = /** @class */ (function (_super) {
  53822. __extends(DoNothingAction, _super);
  53823. function DoNothingAction(triggerOptions, condition) {
  53824. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53825. return _super.call(this, triggerOptions, condition) || this;
  53826. }
  53827. DoNothingAction.prototype.execute = function () {
  53828. };
  53829. DoNothingAction.prototype.serialize = function (parent) {
  53830. return _super.prototype._serialize.call(this, {
  53831. name: "DoNothingAction",
  53832. properties: []
  53833. }, parent);
  53834. };
  53835. return DoNothingAction;
  53836. }(BABYLON.Action));
  53837. BABYLON.DoNothingAction = DoNothingAction;
  53838. var CombineAction = /** @class */ (function (_super) {
  53839. __extends(CombineAction, _super);
  53840. function CombineAction(triggerOptions, children, condition) {
  53841. var _this = _super.call(this, triggerOptions, condition) || this;
  53842. _this.children = children;
  53843. return _this;
  53844. }
  53845. /** @hidden */
  53846. CombineAction.prototype._prepare = function () {
  53847. for (var index = 0; index < this.children.length; index++) {
  53848. this.children[index]._actionManager = this._actionManager;
  53849. this.children[index]._prepare();
  53850. }
  53851. };
  53852. CombineAction.prototype.execute = function (evt) {
  53853. for (var index = 0; index < this.children.length; index++) {
  53854. this.children[index].execute(evt);
  53855. }
  53856. };
  53857. CombineAction.prototype.serialize = function (parent) {
  53858. var serializationObject = _super.prototype._serialize.call(this, {
  53859. name: "CombineAction",
  53860. properties: [],
  53861. combine: []
  53862. }, parent);
  53863. for (var i = 0; i < this.children.length; i++) {
  53864. serializationObject.combine.push(this.children[i].serialize(null));
  53865. }
  53866. return serializationObject;
  53867. };
  53868. return CombineAction;
  53869. }(BABYLON.Action));
  53870. BABYLON.CombineAction = CombineAction;
  53871. var ExecuteCodeAction = /** @class */ (function (_super) {
  53872. __extends(ExecuteCodeAction, _super);
  53873. function ExecuteCodeAction(triggerOptions, func, condition) {
  53874. var _this = _super.call(this, triggerOptions, condition) || this;
  53875. _this.func = func;
  53876. return _this;
  53877. }
  53878. ExecuteCodeAction.prototype.execute = function (evt) {
  53879. this.func(evt);
  53880. };
  53881. return ExecuteCodeAction;
  53882. }(BABYLON.Action));
  53883. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53884. var SetParentAction = /** @class */ (function (_super) {
  53885. __extends(SetParentAction, _super);
  53886. function SetParentAction(triggerOptions, target, parent, condition) {
  53887. var _this = _super.call(this, triggerOptions, condition) || this;
  53888. _this._target = target;
  53889. _this._parent = parent;
  53890. return _this;
  53891. }
  53892. /** @hidden */
  53893. SetParentAction.prototype._prepare = function () {
  53894. };
  53895. SetParentAction.prototype.execute = function () {
  53896. if (this._target.parent === this._parent) {
  53897. return;
  53898. }
  53899. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53900. invertParentWorldMatrix.invert();
  53901. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53902. this._target.parent = this._parent;
  53903. };
  53904. SetParentAction.prototype.serialize = function (parent) {
  53905. return _super.prototype._serialize.call(this, {
  53906. name: "SetParentAction",
  53907. properties: [
  53908. BABYLON.Action._GetTargetProperty(this._target),
  53909. BABYLON.Action._GetTargetProperty(this._parent),
  53910. ]
  53911. }, parent);
  53912. };
  53913. return SetParentAction;
  53914. }(BABYLON.Action));
  53915. BABYLON.SetParentAction = SetParentAction;
  53916. var PlaySoundAction = /** @class */ (function (_super) {
  53917. __extends(PlaySoundAction, _super);
  53918. function PlaySoundAction(triggerOptions, sound, condition) {
  53919. var _this = _super.call(this, triggerOptions, condition) || this;
  53920. _this._sound = sound;
  53921. return _this;
  53922. }
  53923. /** @hidden */
  53924. PlaySoundAction.prototype._prepare = function () {
  53925. };
  53926. PlaySoundAction.prototype.execute = function () {
  53927. if (this._sound !== undefined)
  53928. this._sound.play();
  53929. };
  53930. PlaySoundAction.prototype.serialize = function (parent) {
  53931. return _super.prototype._serialize.call(this, {
  53932. name: "PlaySoundAction",
  53933. properties: [{ name: "sound", value: this._sound.name }]
  53934. }, parent);
  53935. };
  53936. return PlaySoundAction;
  53937. }(BABYLON.Action));
  53938. BABYLON.PlaySoundAction = PlaySoundAction;
  53939. var StopSoundAction = /** @class */ (function (_super) {
  53940. __extends(StopSoundAction, _super);
  53941. function StopSoundAction(triggerOptions, sound, condition) {
  53942. var _this = _super.call(this, triggerOptions, condition) || this;
  53943. _this._sound = sound;
  53944. return _this;
  53945. }
  53946. /** @hidden */
  53947. StopSoundAction.prototype._prepare = function () {
  53948. };
  53949. StopSoundAction.prototype.execute = function () {
  53950. if (this._sound !== undefined)
  53951. this._sound.stop();
  53952. };
  53953. StopSoundAction.prototype.serialize = function (parent) {
  53954. return _super.prototype._serialize.call(this, {
  53955. name: "StopSoundAction",
  53956. properties: [{ name: "sound", value: this._sound.name }]
  53957. }, parent);
  53958. };
  53959. return StopSoundAction;
  53960. }(BABYLON.Action));
  53961. BABYLON.StopSoundAction = StopSoundAction;
  53962. })(BABYLON || (BABYLON = {}));
  53963. //# sourceMappingURL=babylon.directActions.js.map
  53964. var BABYLON;
  53965. (function (BABYLON) {
  53966. var SpriteManager = /** @class */ (function () {
  53967. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53968. if (epsilon === void 0) { epsilon = 0.01; }
  53969. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53970. this.name = name;
  53971. this.sprites = new Array();
  53972. this.renderingGroupId = 0;
  53973. this.layerMask = 0x0FFFFFFF;
  53974. this.fogEnabled = true;
  53975. this.isPickable = false;
  53976. /**
  53977. * An event triggered when the manager is disposed.
  53978. */
  53979. this.onDisposeObservable = new BABYLON.Observable();
  53980. this._vertexBuffers = {};
  53981. this._capacity = capacity;
  53982. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53983. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53984. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53985. if (cellSize.width && cellSize.height) {
  53986. this.cellWidth = cellSize.width;
  53987. this.cellHeight = cellSize.height;
  53988. }
  53989. else if (cellSize !== undefined) {
  53990. this.cellWidth = cellSize;
  53991. this.cellHeight = cellSize;
  53992. }
  53993. else {
  53994. return;
  53995. }
  53996. this._epsilon = epsilon;
  53997. this._scene = scene;
  53998. this._scene.spriteManagers.push(this);
  53999. var indices = [];
  54000. var index = 0;
  54001. for (var count = 0; count < capacity; count++) {
  54002. indices.push(index);
  54003. indices.push(index + 1);
  54004. indices.push(index + 2);
  54005. indices.push(index);
  54006. indices.push(index + 2);
  54007. indices.push(index + 3);
  54008. index += 4;
  54009. }
  54010. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54011. // VBO
  54012. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54013. this._vertexData = new Float32Array(capacity * 16 * 4);
  54014. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54015. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54016. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54017. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54018. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54019. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54020. this._vertexBuffers["options"] = options;
  54021. this._vertexBuffers["cellInfo"] = cellInfo;
  54022. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54023. // Effects
  54024. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54025. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54026. }
  54027. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54028. set: function (callback) {
  54029. if (this._onDisposeObserver) {
  54030. this.onDisposeObservable.remove(this._onDisposeObserver);
  54031. }
  54032. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54033. },
  54034. enumerable: true,
  54035. configurable: true
  54036. });
  54037. Object.defineProperty(SpriteManager.prototype, "texture", {
  54038. get: function () {
  54039. return this._spriteTexture;
  54040. },
  54041. set: function (value) {
  54042. this._spriteTexture = value;
  54043. },
  54044. enumerable: true,
  54045. configurable: true
  54046. });
  54047. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54048. var arrayOffset = index * 16;
  54049. if (offsetX === 0)
  54050. offsetX = this._epsilon;
  54051. else if (offsetX === 1)
  54052. offsetX = 1 - this._epsilon;
  54053. if (offsetY === 0)
  54054. offsetY = this._epsilon;
  54055. else if (offsetY === 1)
  54056. offsetY = 1 - this._epsilon;
  54057. this._vertexData[arrayOffset] = sprite.position.x;
  54058. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54059. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54060. this._vertexData[arrayOffset + 3] = sprite.angle;
  54061. this._vertexData[arrayOffset + 4] = sprite.width;
  54062. this._vertexData[arrayOffset + 5] = sprite.height;
  54063. this._vertexData[arrayOffset + 6] = offsetX;
  54064. this._vertexData[arrayOffset + 7] = offsetY;
  54065. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54066. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54067. var offset = (sprite.cellIndex / rowSize) >> 0;
  54068. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54069. this._vertexData[arrayOffset + 11] = offset;
  54070. // Color
  54071. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54072. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54073. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54074. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54075. };
  54076. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54077. var count = Math.min(this._capacity, this.sprites.length);
  54078. var min = BABYLON.Vector3.Zero();
  54079. var max = BABYLON.Vector3.Zero();
  54080. var distance = Number.MAX_VALUE;
  54081. var currentSprite = null;
  54082. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54083. var cameraView = camera.getViewMatrix();
  54084. for (var index = 0; index < count; index++) {
  54085. var sprite = this.sprites[index];
  54086. if (!sprite) {
  54087. continue;
  54088. }
  54089. if (predicate) {
  54090. if (!predicate(sprite)) {
  54091. continue;
  54092. }
  54093. }
  54094. else if (!sprite.isPickable) {
  54095. continue;
  54096. }
  54097. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54098. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54099. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54100. if (ray.intersectsBoxMinMax(min, max)) {
  54101. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54102. if (distance > currentDistance) {
  54103. distance = currentDistance;
  54104. currentSprite = sprite;
  54105. if (fastCheck) {
  54106. break;
  54107. }
  54108. }
  54109. }
  54110. }
  54111. if (currentSprite) {
  54112. var result = new BABYLON.PickingInfo();
  54113. result.hit = true;
  54114. result.pickedSprite = currentSprite;
  54115. result.distance = distance;
  54116. return result;
  54117. }
  54118. return null;
  54119. };
  54120. SpriteManager.prototype.render = function () {
  54121. // Check
  54122. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54123. return;
  54124. var engine = this._scene.getEngine();
  54125. var baseSize = this._spriteTexture.getBaseSize();
  54126. // Sprites
  54127. var deltaTime = engine.getDeltaTime();
  54128. var max = Math.min(this._capacity, this.sprites.length);
  54129. var rowSize = baseSize.width / this.cellWidth;
  54130. var offset = 0;
  54131. for (var index = 0; index < max; index++) {
  54132. var sprite = this.sprites[index];
  54133. if (!sprite || !sprite.isVisible) {
  54134. continue;
  54135. }
  54136. sprite._animate(deltaTime);
  54137. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54138. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54139. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54140. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54141. }
  54142. this._buffer.update(this._vertexData);
  54143. // Render
  54144. var effect = this._effectBase;
  54145. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54146. effect = this._effectFog;
  54147. }
  54148. engine.enableEffect(effect);
  54149. var viewMatrix = this._scene.getViewMatrix();
  54150. effect.setTexture("diffuseSampler", this._spriteTexture);
  54151. effect.setMatrix("view", viewMatrix);
  54152. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54153. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54154. // Fog
  54155. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54156. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54157. effect.setColor3("vFogColor", this._scene.fogColor);
  54158. }
  54159. // VBOs
  54160. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54161. // Draw order
  54162. engine.setDepthFunctionToLessOrEqual();
  54163. effect.setBool("alphaTest", true);
  54164. engine.setColorWrite(false);
  54165. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54166. engine.setColorWrite(true);
  54167. effect.setBool("alphaTest", false);
  54168. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54169. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54170. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54171. };
  54172. SpriteManager.prototype.dispose = function () {
  54173. if (this._buffer) {
  54174. this._buffer.dispose();
  54175. this._buffer = null;
  54176. }
  54177. if (this._indexBuffer) {
  54178. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54179. this._indexBuffer = null;
  54180. }
  54181. if (this._spriteTexture) {
  54182. this._spriteTexture.dispose();
  54183. this._spriteTexture = null;
  54184. }
  54185. // Remove from scene
  54186. var index = this._scene.spriteManagers.indexOf(this);
  54187. this._scene.spriteManagers.splice(index, 1);
  54188. // Callback
  54189. this.onDisposeObservable.notifyObservers(this);
  54190. this.onDisposeObservable.clear();
  54191. };
  54192. return SpriteManager;
  54193. }());
  54194. BABYLON.SpriteManager = SpriteManager;
  54195. })(BABYLON || (BABYLON = {}));
  54196. //# sourceMappingURL=babylon.spriteManager.js.map
  54197. var BABYLON;
  54198. (function (BABYLON) {
  54199. var Sprite = /** @class */ (function () {
  54200. function Sprite(name, manager) {
  54201. this.name = name;
  54202. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54203. this.width = 1.0;
  54204. this.height = 1.0;
  54205. this.angle = 0;
  54206. this.cellIndex = 0;
  54207. this.invertU = 0;
  54208. this.invertV = 0;
  54209. this.animations = new Array();
  54210. this.isPickable = false;
  54211. this._animationStarted = false;
  54212. this._loopAnimation = false;
  54213. this._fromIndex = 0;
  54214. this._toIndex = 0;
  54215. this._delay = 0;
  54216. this._direction = 1;
  54217. this._time = 0;
  54218. /**
  54219. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54220. */
  54221. this.isVisible = true;
  54222. this._manager = manager;
  54223. this._manager.sprites.push(this);
  54224. this.position = BABYLON.Vector3.Zero();
  54225. }
  54226. Object.defineProperty(Sprite.prototype, "size", {
  54227. get: function () {
  54228. return this.width;
  54229. },
  54230. set: function (value) {
  54231. this.width = value;
  54232. this.height = value;
  54233. },
  54234. enumerable: true,
  54235. configurable: true
  54236. });
  54237. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54238. this._fromIndex = from;
  54239. this._toIndex = to;
  54240. this._loopAnimation = loop;
  54241. this._delay = delay;
  54242. this._animationStarted = true;
  54243. this._direction = from < to ? 1 : -1;
  54244. this.cellIndex = from;
  54245. this._time = 0;
  54246. this._onAnimationEnd = onAnimationEnd;
  54247. };
  54248. Sprite.prototype.stopAnimation = function () {
  54249. this._animationStarted = false;
  54250. };
  54251. /** @hidden */
  54252. Sprite.prototype._animate = function (deltaTime) {
  54253. if (!this._animationStarted)
  54254. return;
  54255. this._time += deltaTime;
  54256. if (this._time > this._delay) {
  54257. this._time = this._time % this._delay;
  54258. this.cellIndex += this._direction;
  54259. if (this.cellIndex > this._toIndex) {
  54260. if (this._loopAnimation) {
  54261. this.cellIndex = this._fromIndex;
  54262. }
  54263. else {
  54264. this.cellIndex = this._toIndex;
  54265. this._animationStarted = false;
  54266. if (this._onAnimationEnd) {
  54267. this._onAnimationEnd();
  54268. }
  54269. if (this.disposeWhenFinishedAnimating) {
  54270. this.dispose();
  54271. }
  54272. }
  54273. }
  54274. }
  54275. };
  54276. Sprite.prototype.dispose = function () {
  54277. for (var i = 0; i < this._manager.sprites.length; i++) {
  54278. if (this._manager.sprites[i] == this) {
  54279. this._manager.sprites.splice(i, 1);
  54280. }
  54281. }
  54282. };
  54283. return Sprite;
  54284. }());
  54285. BABYLON.Sprite = Sprite;
  54286. })(BABYLON || (BABYLON = {}));
  54287. //# sourceMappingURL=babylon.sprite.js.map
  54288. var BABYLON;
  54289. (function (BABYLON) {
  54290. var IntersectionInfo = /** @class */ (function () {
  54291. function IntersectionInfo(bu, bv, distance) {
  54292. this.bu = bu;
  54293. this.bv = bv;
  54294. this.distance = distance;
  54295. this.faceId = 0;
  54296. this.subMeshId = 0;
  54297. }
  54298. return IntersectionInfo;
  54299. }());
  54300. BABYLON.IntersectionInfo = IntersectionInfo;
  54301. /**
  54302. * Information about the result of picking within a scene
  54303. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54304. */
  54305. var PickingInfo = /** @class */ (function () {
  54306. function PickingInfo() {
  54307. /**
  54308. * If the pick collided with an object
  54309. */
  54310. this.hit = false;
  54311. /**
  54312. * Distance away where the pick collided
  54313. */
  54314. this.distance = 0;
  54315. /**
  54316. * The location of pick collision
  54317. */
  54318. this.pickedPoint = null;
  54319. /**
  54320. * The mesh corresponding the the pick collision
  54321. */
  54322. this.pickedMesh = null;
  54323. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54324. this.bu = 0;
  54325. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54326. this.bv = 0;
  54327. /** The id of the face on the mesh that was picked */
  54328. this.faceId = -1;
  54329. /** Id of the the submesh that was picked */
  54330. this.subMeshId = 0;
  54331. /** If a sprite was picked, this will be the sprite the pick collided with */
  54332. this.pickedSprite = null;
  54333. /**
  54334. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54335. */
  54336. this.originMesh = null;
  54337. /**
  54338. * The ray that was used to perform the picking.
  54339. */
  54340. this.ray = null;
  54341. }
  54342. /**
  54343. * Gets the normal correspodning to the face the pick collided with
  54344. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54345. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54346. * @returns The normal correspodning to the face the pick collided with
  54347. */
  54348. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54349. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54350. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54351. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54352. return null;
  54353. }
  54354. var indices = this.pickedMesh.getIndices();
  54355. if (!indices) {
  54356. return null;
  54357. }
  54358. var result;
  54359. if (useVerticesNormals) {
  54360. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54361. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54362. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54363. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54364. normal0 = normal0.scale(this.bu);
  54365. normal1 = normal1.scale(this.bv);
  54366. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54367. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54368. }
  54369. else {
  54370. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54371. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54372. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54373. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54374. var p1p2 = vertex1.subtract(vertex2);
  54375. var p3p2 = vertex3.subtract(vertex2);
  54376. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54377. }
  54378. if (useWorldCoordinates) {
  54379. var wm = this.pickedMesh.getWorldMatrix();
  54380. if (this.pickedMesh.nonUniformScaling) {
  54381. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54382. wm = BABYLON.Tmp.Matrix[0];
  54383. wm.setTranslationFromFloats(0, 0, 0);
  54384. wm.invert();
  54385. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54386. wm = BABYLON.Tmp.Matrix[1];
  54387. }
  54388. result = BABYLON.Vector3.TransformNormal(result, wm);
  54389. }
  54390. result.normalize();
  54391. return result;
  54392. };
  54393. /**
  54394. * Gets the texture coordinates of where the pick occured
  54395. * @returns the vector containing the coordnates of the texture
  54396. */
  54397. PickingInfo.prototype.getTextureCoordinates = function () {
  54398. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54399. return null;
  54400. }
  54401. var indices = this.pickedMesh.getIndices();
  54402. if (!indices) {
  54403. return null;
  54404. }
  54405. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54406. if (!uvs) {
  54407. return null;
  54408. }
  54409. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54410. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54411. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54412. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54413. uv1 = uv1.scale(this.bu);
  54414. uv2 = uv2.scale(this.bv);
  54415. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54416. };
  54417. return PickingInfo;
  54418. }());
  54419. BABYLON.PickingInfo = PickingInfo;
  54420. })(BABYLON || (BABYLON = {}));
  54421. //# sourceMappingURL=babylon.pickingInfo.js.map
  54422. var BABYLON;
  54423. (function (BABYLON) {
  54424. var Ray = /** @class */ (function () {
  54425. function Ray(origin, direction, length) {
  54426. if (length === void 0) { length = Number.MAX_VALUE; }
  54427. this.origin = origin;
  54428. this.direction = direction;
  54429. this.length = length;
  54430. }
  54431. // Methods
  54432. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54433. var d = 0.0;
  54434. var maxValue = Number.MAX_VALUE;
  54435. var inv;
  54436. var min;
  54437. var max;
  54438. var temp;
  54439. if (Math.abs(this.direction.x) < 0.0000001) {
  54440. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54441. return false;
  54442. }
  54443. }
  54444. else {
  54445. inv = 1.0 / this.direction.x;
  54446. min = (minimum.x - this.origin.x) * inv;
  54447. max = (maximum.x - this.origin.x) * inv;
  54448. if (max === -Infinity) {
  54449. max = Infinity;
  54450. }
  54451. if (min > max) {
  54452. temp = min;
  54453. min = max;
  54454. max = temp;
  54455. }
  54456. d = Math.max(min, d);
  54457. maxValue = Math.min(max, maxValue);
  54458. if (d > maxValue) {
  54459. return false;
  54460. }
  54461. }
  54462. if (Math.abs(this.direction.y) < 0.0000001) {
  54463. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54464. return false;
  54465. }
  54466. }
  54467. else {
  54468. inv = 1.0 / this.direction.y;
  54469. min = (minimum.y - this.origin.y) * inv;
  54470. max = (maximum.y - this.origin.y) * inv;
  54471. if (max === -Infinity) {
  54472. max = Infinity;
  54473. }
  54474. if (min > max) {
  54475. temp = min;
  54476. min = max;
  54477. max = temp;
  54478. }
  54479. d = Math.max(min, d);
  54480. maxValue = Math.min(max, maxValue);
  54481. if (d > maxValue) {
  54482. return false;
  54483. }
  54484. }
  54485. if (Math.abs(this.direction.z) < 0.0000001) {
  54486. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54487. return false;
  54488. }
  54489. }
  54490. else {
  54491. inv = 1.0 / this.direction.z;
  54492. min = (minimum.z - this.origin.z) * inv;
  54493. max = (maximum.z - this.origin.z) * inv;
  54494. if (max === -Infinity) {
  54495. max = Infinity;
  54496. }
  54497. if (min > max) {
  54498. temp = min;
  54499. min = max;
  54500. max = temp;
  54501. }
  54502. d = Math.max(min, d);
  54503. maxValue = Math.min(max, maxValue);
  54504. if (d > maxValue) {
  54505. return false;
  54506. }
  54507. }
  54508. return true;
  54509. };
  54510. Ray.prototype.intersectsBox = function (box) {
  54511. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54512. };
  54513. Ray.prototype.intersectsSphere = function (sphere) {
  54514. var x = sphere.center.x - this.origin.x;
  54515. var y = sphere.center.y - this.origin.y;
  54516. var z = sphere.center.z - this.origin.z;
  54517. var pyth = (x * x) + (y * y) + (z * z);
  54518. var rr = sphere.radius * sphere.radius;
  54519. if (pyth <= rr) {
  54520. return true;
  54521. }
  54522. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54523. if (dot < 0.0) {
  54524. return false;
  54525. }
  54526. var temp = pyth - (dot * dot);
  54527. return temp <= rr;
  54528. };
  54529. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54530. if (!this._edge1) {
  54531. this._edge1 = BABYLON.Vector3.Zero();
  54532. this._edge2 = BABYLON.Vector3.Zero();
  54533. this._pvec = BABYLON.Vector3.Zero();
  54534. this._tvec = BABYLON.Vector3.Zero();
  54535. this._qvec = BABYLON.Vector3.Zero();
  54536. }
  54537. vertex1.subtractToRef(vertex0, this._edge1);
  54538. vertex2.subtractToRef(vertex0, this._edge2);
  54539. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54540. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54541. if (det === 0) {
  54542. return null;
  54543. }
  54544. var invdet = 1 / det;
  54545. this.origin.subtractToRef(vertex0, this._tvec);
  54546. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54547. if (bu < 0 || bu > 1.0) {
  54548. return null;
  54549. }
  54550. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54551. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54552. if (bv < 0 || bu + bv > 1.0) {
  54553. return null;
  54554. }
  54555. //check if the distance is longer than the predefined length.
  54556. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54557. if (distance > this.length) {
  54558. return null;
  54559. }
  54560. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54561. };
  54562. Ray.prototype.intersectsPlane = function (plane) {
  54563. var distance;
  54564. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54565. if (Math.abs(result1) < 9.99999997475243E-07) {
  54566. return null;
  54567. }
  54568. else {
  54569. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54570. distance = (-plane.d - result2) / result1;
  54571. if (distance < 0.0) {
  54572. if (distance < -9.99999997475243E-07) {
  54573. return null;
  54574. }
  54575. else {
  54576. return 0;
  54577. }
  54578. }
  54579. return distance;
  54580. }
  54581. };
  54582. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54583. var tm = BABYLON.Tmp.Matrix[0];
  54584. mesh.getWorldMatrix().invertToRef(tm);
  54585. if (this._tmpRay) {
  54586. Ray.TransformToRef(this, tm, this._tmpRay);
  54587. }
  54588. else {
  54589. this._tmpRay = Ray.Transform(this, tm);
  54590. }
  54591. return mesh.intersects(this._tmpRay, fastCheck);
  54592. };
  54593. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54594. if (results) {
  54595. results.length = 0;
  54596. }
  54597. else {
  54598. results = [];
  54599. }
  54600. for (var i = 0; i < meshes.length; i++) {
  54601. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54602. if (pickInfo.hit) {
  54603. results.push(pickInfo);
  54604. }
  54605. }
  54606. results.sort(this._comparePickingInfo);
  54607. return results;
  54608. };
  54609. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54610. if (pickingInfoA.distance < pickingInfoB.distance) {
  54611. return -1;
  54612. }
  54613. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54614. return 1;
  54615. }
  54616. else {
  54617. return 0;
  54618. }
  54619. };
  54620. /**
  54621. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54622. * @param sega the first point of the segment to test the intersection against
  54623. * @param segb the second point of the segment to test the intersection against
  54624. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54625. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54626. */
  54627. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54628. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54629. var u = segb.subtract(sega);
  54630. var v = rsegb.subtract(this.origin);
  54631. var w = sega.subtract(this.origin);
  54632. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54633. var b = BABYLON.Vector3.Dot(u, v);
  54634. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54635. var d = BABYLON.Vector3.Dot(u, w);
  54636. var e = BABYLON.Vector3.Dot(v, w);
  54637. var D = a * c - b * b; // always >= 0
  54638. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54639. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54640. // compute the line parameters of the two closest points
  54641. if (D < Ray.smallnum) { // the lines are almost parallel
  54642. sN = 0.0; // force using point P0 on segment S1
  54643. sD = 1.0; // to prevent possible division by 0.0 later
  54644. tN = e;
  54645. tD = c;
  54646. }
  54647. else { // get the closest points on the infinite lines
  54648. sN = (b * e - c * d);
  54649. tN = (a * e - b * d);
  54650. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54651. sN = 0.0;
  54652. tN = e;
  54653. tD = c;
  54654. }
  54655. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54656. sN = sD;
  54657. tN = e + b;
  54658. tD = c;
  54659. }
  54660. }
  54661. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54662. tN = 0.0;
  54663. // recompute sc for this edge
  54664. if (-d < 0.0) {
  54665. sN = 0.0;
  54666. }
  54667. else if (-d > a)
  54668. sN = sD;
  54669. else {
  54670. sN = -d;
  54671. sD = a;
  54672. }
  54673. }
  54674. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54675. tN = tD;
  54676. // recompute sc for this edge
  54677. if ((-d + b) < 0.0) {
  54678. sN = 0;
  54679. }
  54680. else if ((-d + b) > a) {
  54681. sN = sD;
  54682. }
  54683. else {
  54684. sN = (-d + b);
  54685. sD = a;
  54686. }
  54687. }
  54688. // finally do the division to get sc and tc
  54689. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54690. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54691. // get the difference of the two closest points
  54692. var qtc = v.multiplyByFloats(tc, tc, tc);
  54693. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54694. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54695. if (isIntersected) {
  54696. return qtc.length();
  54697. }
  54698. return -1;
  54699. };
  54700. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54701. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54702. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54703. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54704. this.direction.normalize();
  54705. return this;
  54706. };
  54707. // Statics
  54708. Ray.Zero = function () {
  54709. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54710. };
  54711. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54712. var result = Ray.Zero();
  54713. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54714. };
  54715. /**
  54716. * 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
  54717. * transformed to the given world matrix.
  54718. * @param origin The origin point
  54719. * @param end The end point
  54720. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54721. */
  54722. Ray.CreateNewFromTo = function (origin, end, world) {
  54723. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54724. var direction = end.subtract(origin);
  54725. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54726. direction.normalize();
  54727. return Ray.Transform(new Ray(origin, direction, length), world);
  54728. };
  54729. Ray.Transform = function (ray, matrix) {
  54730. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54731. Ray.TransformToRef(ray, matrix, result);
  54732. return result;
  54733. };
  54734. Ray.TransformToRef = function (ray, matrix, result) {
  54735. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54736. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54737. result.length = ray.length;
  54738. var dir = result.direction;
  54739. var len = dir.length();
  54740. if (!(len === 0 || len === 1)) {
  54741. var num = 1.0 / len;
  54742. dir.x *= num;
  54743. dir.y *= num;
  54744. dir.z *= num;
  54745. result.length *= len;
  54746. }
  54747. };
  54748. Ray.smallnum = 0.00000001;
  54749. Ray.rayl = 10e8;
  54750. return Ray;
  54751. }());
  54752. BABYLON.Ray = Ray;
  54753. })(BABYLON || (BABYLON = {}));
  54754. //# sourceMappingURL=babylon.ray.js.map
  54755. var BABYLON;
  54756. (function (BABYLON) {
  54757. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54758. if (boxMin.x > sphereCenter.x + sphereRadius)
  54759. return false;
  54760. if (sphereCenter.x - sphereRadius > boxMax.x)
  54761. return false;
  54762. if (boxMin.y > sphereCenter.y + sphereRadius)
  54763. return false;
  54764. if (sphereCenter.y - sphereRadius > boxMax.y)
  54765. return false;
  54766. if (boxMin.z > sphereCenter.z + sphereRadius)
  54767. return false;
  54768. if (sphereCenter.z - sphereRadius > boxMax.z)
  54769. return false;
  54770. return true;
  54771. };
  54772. var getLowestRoot = (function () {
  54773. var result = { root: 0, found: false };
  54774. return function (a, b, c, maxR) {
  54775. result.root = 0;
  54776. result.found = false;
  54777. var determinant = b * b - 4.0 * a * c;
  54778. if (determinant < 0)
  54779. return result;
  54780. var sqrtD = Math.sqrt(determinant);
  54781. var r1 = (-b - sqrtD) / (2.0 * a);
  54782. var r2 = (-b + sqrtD) / (2.0 * a);
  54783. if (r1 > r2) {
  54784. var temp = r2;
  54785. r2 = r1;
  54786. r1 = temp;
  54787. }
  54788. if (r1 > 0 && r1 < maxR) {
  54789. result.root = r1;
  54790. result.found = true;
  54791. return result;
  54792. }
  54793. if (r2 > 0 && r2 < maxR) {
  54794. result.root = r2;
  54795. result.found = true;
  54796. return result;
  54797. }
  54798. return result;
  54799. };
  54800. })();
  54801. var Collider = /** @class */ (function () {
  54802. function Collider() {
  54803. this._collisionPoint = BABYLON.Vector3.Zero();
  54804. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54805. this._tempVector = BABYLON.Vector3.Zero();
  54806. this._tempVector2 = BABYLON.Vector3.Zero();
  54807. this._tempVector3 = BABYLON.Vector3.Zero();
  54808. this._tempVector4 = BABYLON.Vector3.Zero();
  54809. this._edge = BABYLON.Vector3.Zero();
  54810. this._baseToVertex = BABYLON.Vector3.Zero();
  54811. this._destinationPoint = BABYLON.Vector3.Zero();
  54812. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54813. this._displacementVector = BABYLON.Vector3.Zero();
  54814. /** @hidden */
  54815. this._radius = BABYLON.Vector3.One();
  54816. /** @hidden */
  54817. this._retry = 0;
  54818. /** @hidden */
  54819. this._basePointWorld = BABYLON.Vector3.Zero();
  54820. this._velocityWorld = BABYLON.Vector3.Zero();
  54821. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54822. this._collisionMask = -1;
  54823. }
  54824. Object.defineProperty(Collider.prototype, "collisionMask", {
  54825. get: function () {
  54826. return this._collisionMask;
  54827. },
  54828. set: function (mask) {
  54829. this._collisionMask = !isNaN(mask) ? mask : -1;
  54830. },
  54831. enumerable: true,
  54832. configurable: true
  54833. });
  54834. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54835. /**
  54836. * Gets the plane normal used to compute the sliding response (in local space)
  54837. */
  54838. get: function () {
  54839. return this._slidePlaneNormal;
  54840. },
  54841. enumerable: true,
  54842. configurable: true
  54843. });
  54844. // Methods
  54845. /** @hidden */
  54846. Collider.prototype._initialize = function (source, dir, e) {
  54847. this._velocity = dir;
  54848. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54849. this._basePoint = source;
  54850. source.multiplyToRef(this._radius, this._basePointWorld);
  54851. dir.multiplyToRef(this._radius, this._velocityWorld);
  54852. this._velocityWorldLength = this._velocityWorld.length();
  54853. this._epsilon = e;
  54854. this.collisionFound = false;
  54855. };
  54856. /** @hidden */
  54857. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54858. pa.subtractToRef(point, this._tempVector);
  54859. pb.subtractToRef(point, this._tempVector2);
  54860. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54861. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54862. if (d < 0)
  54863. return false;
  54864. pc.subtractToRef(point, this._tempVector3);
  54865. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54866. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54867. if (d < 0)
  54868. return false;
  54869. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54870. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54871. return d >= 0;
  54872. };
  54873. /** @hidden */
  54874. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54875. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54876. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54877. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54878. return false;
  54879. }
  54880. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54881. return false;
  54882. return true;
  54883. };
  54884. /** @hidden */
  54885. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54886. var t0;
  54887. var embeddedInPlane = false;
  54888. //defensive programming, actually not needed.
  54889. if (!trianglePlaneArray) {
  54890. trianglePlaneArray = [];
  54891. }
  54892. if (!trianglePlaneArray[faceIndex]) {
  54893. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54894. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54895. }
  54896. var trianglePlane = trianglePlaneArray[faceIndex];
  54897. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54898. return;
  54899. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54900. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54901. if (normalDotVelocity == 0) {
  54902. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54903. return;
  54904. embeddedInPlane = true;
  54905. t0 = 0;
  54906. }
  54907. else {
  54908. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54909. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54910. if (t0 > t1) {
  54911. var temp = t1;
  54912. t1 = t0;
  54913. t0 = temp;
  54914. }
  54915. if (t0 > 1.0 || t1 < 0.0)
  54916. return;
  54917. if (t0 < 0)
  54918. t0 = 0;
  54919. if (t0 > 1.0)
  54920. t0 = 1.0;
  54921. }
  54922. this._collisionPoint.copyFromFloats(0, 0, 0);
  54923. var found = false;
  54924. var t = 1.0;
  54925. if (!embeddedInPlane) {
  54926. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54927. this._velocity.scaleToRef(t0, this._tempVector);
  54928. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54929. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54930. found = true;
  54931. t = t0;
  54932. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54933. }
  54934. }
  54935. if (!found) {
  54936. var velocitySquaredLength = this._velocity.lengthSquared();
  54937. var a = velocitySquaredLength;
  54938. this._basePoint.subtractToRef(p1, this._tempVector);
  54939. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54940. var c = this._tempVector.lengthSquared() - 1.0;
  54941. var lowestRoot = getLowestRoot(a, b, c, t);
  54942. if (lowestRoot.found) {
  54943. t = lowestRoot.root;
  54944. found = true;
  54945. this._collisionPoint.copyFrom(p1);
  54946. }
  54947. this._basePoint.subtractToRef(p2, this._tempVector);
  54948. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54949. c = this._tempVector.lengthSquared() - 1.0;
  54950. lowestRoot = getLowestRoot(a, b, c, t);
  54951. if (lowestRoot.found) {
  54952. t = lowestRoot.root;
  54953. found = true;
  54954. this._collisionPoint.copyFrom(p2);
  54955. }
  54956. this._basePoint.subtractToRef(p3, this._tempVector);
  54957. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54958. c = this._tempVector.lengthSquared() - 1.0;
  54959. lowestRoot = getLowestRoot(a, b, c, t);
  54960. if (lowestRoot.found) {
  54961. t = lowestRoot.root;
  54962. found = true;
  54963. this._collisionPoint.copyFrom(p3);
  54964. }
  54965. p2.subtractToRef(p1, this._edge);
  54966. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54967. var edgeSquaredLength = this._edge.lengthSquared();
  54968. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54969. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54970. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54971. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54972. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54973. lowestRoot = getLowestRoot(a, b, c, t);
  54974. if (lowestRoot.found) {
  54975. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54976. if (f >= 0.0 && f <= 1.0) {
  54977. t = lowestRoot.root;
  54978. found = true;
  54979. this._edge.scaleInPlace(f);
  54980. p1.addToRef(this._edge, this._collisionPoint);
  54981. }
  54982. }
  54983. p3.subtractToRef(p2, this._edge);
  54984. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54985. edgeSquaredLength = this._edge.lengthSquared();
  54986. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54987. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54988. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54989. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54990. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54991. lowestRoot = getLowestRoot(a, b, c, t);
  54992. if (lowestRoot.found) {
  54993. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54994. if (f >= 0.0 && f <= 1.0) {
  54995. t = lowestRoot.root;
  54996. found = true;
  54997. this._edge.scaleInPlace(f);
  54998. p2.addToRef(this._edge, this._collisionPoint);
  54999. }
  55000. }
  55001. p1.subtractToRef(p3, this._edge);
  55002. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55003. edgeSquaredLength = this._edge.lengthSquared();
  55004. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55005. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55006. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55007. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55008. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55009. lowestRoot = getLowestRoot(a, b, c, t);
  55010. if (lowestRoot.found) {
  55011. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55012. if (f >= 0.0 && f <= 1.0) {
  55013. t = lowestRoot.root;
  55014. found = true;
  55015. this._edge.scaleInPlace(f);
  55016. p3.addToRef(this._edge, this._collisionPoint);
  55017. }
  55018. }
  55019. }
  55020. if (found) {
  55021. var distToCollision = t * this._velocity.length();
  55022. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55023. if (!this.intersectionPoint) {
  55024. this.intersectionPoint = this._collisionPoint.clone();
  55025. }
  55026. else {
  55027. this.intersectionPoint.copyFrom(this._collisionPoint);
  55028. }
  55029. this._nearestDistance = distToCollision;
  55030. this.collisionFound = true;
  55031. }
  55032. }
  55033. };
  55034. /** @hidden */
  55035. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55036. for (var i = indexStart; i < indexEnd; i += 3) {
  55037. var p1 = pts[indices[i] - decal];
  55038. var p2 = pts[indices[i + 1] - decal];
  55039. var p3 = pts[indices[i + 2] - decal];
  55040. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55041. }
  55042. };
  55043. /** @hidden */
  55044. Collider.prototype._getResponse = function (pos, vel) {
  55045. pos.addToRef(vel, this._destinationPoint);
  55046. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55047. this._basePoint.addToRef(vel, pos);
  55048. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55049. this._slidePlaneNormal.normalize();
  55050. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55051. pos.addInPlace(this._displacementVector);
  55052. this.intersectionPoint.addInPlace(this._displacementVector);
  55053. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55054. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55055. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55056. };
  55057. return Collider;
  55058. }());
  55059. BABYLON.Collider = Collider;
  55060. })(BABYLON || (BABYLON = {}));
  55061. //# sourceMappingURL=babylon.collider.js.map
  55062. var BABYLON;
  55063. (function (BABYLON) {
  55064. //WebWorker code will be inserted to this variable.
  55065. BABYLON.CollisionWorker = "";
  55066. /** Defines supported task for worker process */
  55067. var WorkerTaskType;
  55068. (function (WorkerTaskType) {
  55069. /** Initialization */
  55070. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55071. /** Update of geometry */
  55072. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55073. /** Evaluate collision */
  55074. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55075. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55076. /** Defines kind of replies returned by worker */
  55077. var WorkerReplyType;
  55078. (function (WorkerReplyType) {
  55079. /** Success */
  55080. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55081. /** Unkown error */
  55082. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55083. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55084. var CollisionCoordinatorWorker = /** @class */ (function () {
  55085. function CollisionCoordinatorWorker() {
  55086. var _this = this;
  55087. this._scaledPosition = BABYLON.Vector3.Zero();
  55088. this._scaledVelocity = BABYLON.Vector3.Zero();
  55089. this.onMeshUpdated = function (transformNode) {
  55090. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55091. };
  55092. this.onGeometryUpdated = function (geometry) {
  55093. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55094. };
  55095. this._afterRender = function () {
  55096. if (!_this._init)
  55097. return;
  55098. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55099. return;
  55100. }
  55101. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55102. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55103. if (_this._runningUpdated > 4) {
  55104. return;
  55105. }
  55106. ++_this._runningUpdated;
  55107. var payload = {
  55108. updatedMeshes: _this._addUpdateMeshesList,
  55109. updatedGeometries: _this._addUpdateGeometriesList,
  55110. removedGeometries: _this._toRemoveGeometryArray,
  55111. removedMeshes: _this._toRemoveMeshesArray
  55112. };
  55113. var message = {
  55114. payload: payload,
  55115. taskType: WorkerTaskType.UPDATE
  55116. };
  55117. var serializable = [];
  55118. for (var id in payload.updatedGeometries) {
  55119. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55120. //prepare transferables
  55121. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55122. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55123. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55124. }
  55125. }
  55126. _this._worker.postMessage(message, serializable);
  55127. _this._addUpdateMeshesList = {};
  55128. _this._addUpdateGeometriesList = {};
  55129. _this._toRemoveGeometryArray = [];
  55130. _this._toRemoveMeshesArray = [];
  55131. };
  55132. this._onMessageFromWorker = function (e) {
  55133. var returnData = e.data;
  55134. if (returnData.error != WorkerReplyType.SUCCESS) {
  55135. //TODO what errors can be returned from the worker?
  55136. BABYLON.Tools.Warn("error returned from worker!");
  55137. return;
  55138. }
  55139. switch (returnData.taskType) {
  55140. case WorkerTaskType.INIT:
  55141. _this._init = true;
  55142. //Update the worked with ALL of the scene's current state
  55143. _this._scene.meshes.forEach(function (mesh) {
  55144. _this.onMeshAdded(mesh);
  55145. });
  55146. _this._scene.getGeometries().forEach(function (geometry) {
  55147. _this.onGeometryAdded(geometry);
  55148. });
  55149. break;
  55150. case WorkerTaskType.UPDATE:
  55151. _this._runningUpdated--;
  55152. break;
  55153. case WorkerTaskType.COLLIDE:
  55154. var returnPayload = returnData.payload;
  55155. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55156. return;
  55157. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55158. if (callback) {
  55159. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55160. if (mesh) {
  55161. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55162. }
  55163. }
  55164. //cleanup
  55165. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55166. break;
  55167. }
  55168. };
  55169. this._collisionsCallbackArray = [];
  55170. this._init = false;
  55171. this._runningUpdated = 0;
  55172. this._addUpdateMeshesList = {};
  55173. this._addUpdateGeometriesList = {};
  55174. this._toRemoveGeometryArray = [];
  55175. this._toRemoveMeshesArray = [];
  55176. }
  55177. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55178. if (!this._init)
  55179. return;
  55180. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55181. return;
  55182. position.divideToRef(collider._radius, this._scaledPosition);
  55183. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55184. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55185. var payload = {
  55186. collider: {
  55187. position: this._scaledPosition.asArray(),
  55188. velocity: this._scaledVelocity.asArray(),
  55189. radius: collider._radius.asArray()
  55190. },
  55191. collisionId: collisionIndex,
  55192. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55193. maximumRetry: maximumRetry
  55194. };
  55195. var message = {
  55196. payload: payload,
  55197. taskType: WorkerTaskType.COLLIDE
  55198. };
  55199. this._worker.postMessage(message);
  55200. };
  55201. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55202. this._scene = scene;
  55203. this._scene.registerAfterRender(this._afterRender);
  55204. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55205. this._worker = new Worker(workerUrl);
  55206. this._worker.onmessage = this._onMessageFromWorker;
  55207. var message = {
  55208. payload: {},
  55209. taskType: WorkerTaskType.INIT
  55210. };
  55211. this._worker.postMessage(message);
  55212. };
  55213. CollisionCoordinatorWorker.prototype.destroy = function () {
  55214. this._scene.unregisterAfterRender(this._afterRender);
  55215. this._worker.terminate();
  55216. };
  55217. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55218. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55219. this.onMeshUpdated(mesh);
  55220. };
  55221. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55222. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55223. };
  55224. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55225. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55226. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55227. this.onGeometryUpdated(geometry);
  55228. };
  55229. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55230. this._toRemoveGeometryArray.push(geometry.id);
  55231. };
  55232. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55233. var submeshes = [];
  55234. if (mesh.subMeshes) {
  55235. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55236. var boundingInfo = sm.getBoundingInfo();
  55237. return {
  55238. position: idx,
  55239. verticesStart: sm.verticesStart,
  55240. verticesCount: sm.verticesCount,
  55241. indexStart: sm.indexStart,
  55242. indexCount: sm.indexCount,
  55243. hasMaterial: !!sm.getMaterial(),
  55244. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55245. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55246. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55247. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55248. };
  55249. });
  55250. }
  55251. var geometryId = null;
  55252. if (mesh instanceof BABYLON.Mesh) {
  55253. var geometry = mesh.geometry;
  55254. geometryId = geometry ? geometry.id : null;
  55255. }
  55256. else if (mesh instanceof BABYLON.InstancedMesh) {
  55257. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55258. geometryId = geometry ? geometry.id : null;
  55259. }
  55260. var boundingInfo = mesh.getBoundingInfo();
  55261. return {
  55262. uniqueId: mesh.uniqueId,
  55263. id: mesh.id,
  55264. name: mesh.name,
  55265. geometryId: geometryId,
  55266. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55267. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55268. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55269. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55270. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55271. subMeshes: submeshes,
  55272. checkCollisions: mesh.checkCollisions
  55273. };
  55274. };
  55275. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55276. return {
  55277. id: geometry.id,
  55278. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55279. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55280. indices: new Uint32Array(geometry.getIndices() || []),
  55281. };
  55282. };
  55283. return CollisionCoordinatorWorker;
  55284. }());
  55285. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55286. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55287. function CollisionCoordinatorLegacy() {
  55288. this._scaledPosition = BABYLON.Vector3.Zero();
  55289. this._scaledVelocity = BABYLON.Vector3.Zero();
  55290. this._finalPosition = BABYLON.Vector3.Zero();
  55291. }
  55292. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55293. position.divideToRef(collider._radius, this._scaledPosition);
  55294. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55295. collider.collidedMesh = null;
  55296. collider._retry = 0;
  55297. collider._initialVelocity = this._scaledVelocity;
  55298. collider._initialPosition = this._scaledPosition;
  55299. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55300. this._finalPosition.multiplyInPlace(collider._radius);
  55301. //run the callback
  55302. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55303. };
  55304. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55305. this._scene = scene;
  55306. };
  55307. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55308. //Legacy need no destruction method.
  55309. };
  55310. //No update in legacy mode
  55311. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55312. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55313. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55314. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55315. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55316. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55317. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55318. if (excludedMesh === void 0) { excludedMesh = null; }
  55319. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55320. if (collider._retry >= maximumRetry) {
  55321. finalPosition.copyFrom(position);
  55322. return;
  55323. }
  55324. // Check if this is a mesh else camera or -1
  55325. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55326. collider._initialize(position, velocity, closeDistance);
  55327. // Check all meshes
  55328. for (var index = 0; index < this._scene.meshes.length; index++) {
  55329. var mesh = this._scene.meshes[index];
  55330. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55331. mesh._checkCollision(collider);
  55332. }
  55333. }
  55334. if (!collider.collisionFound) {
  55335. position.addToRef(velocity, finalPosition);
  55336. return;
  55337. }
  55338. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55339. collider._getResponse(position, velocity);
  55340. }
  55341. if (velocity.length() <= closeDistance) {
  55342. finalPosition.copyFrom(position);
  55343. return;
  55344. }
  55345. collider._retry++;
  55346. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55347. };
  55348. return CollisionCoordinatorLegacy;
  55349. }());
  55350. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55351. })(BABYLON || (BABYLON = {}));
  55352. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55353. var BABYLON;
  55354. (function (BABYLON) {
  55355. /**
  55356. * A particle represents one of the element emitted by a particle system.
  55357. * This is mainly define by its coordinates, direction, velocity and age.
  55358. */
  55359. var Particle = /** @class */ (function () {
  55360. /**
  55361. * Creates a new instance Particle
  55362. * @param particleSystem the particle system the particle belongs to
  55363. */
  55364. function Particle(
  55365. /**
  55366. * particleSystem the particle system the particle belongs to.
  55367. */
  55368. particleSystem) {
  55369. this.particleSystem = particleSystem;
  55370. /**
  55371. * The world position of the particle in the scene.
  55372. */
  55373. this.position = BABYLON.Vector3.Zero();
  55374. /**
  55375. * The world direction of the particle in the scene.
  55376. */
  55377. this.direction = BABYLON.Vector3.Zero();
  55378. /**
  55379. * The color of the particle.
  55380. */
  55381. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55382. /**
  55383. * The color change of the particle per step.
  55384. */
  55385. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55386. /**
  55387. * Defines how long will the life of the particle be.
  55388. */
  55389. this.lifeTime = 1.0;
  55390. /**
  55391. * The current age of the particle.
  55392. */
  55393. this.age = 0;
  55394. /**
  55395. * The current size of the particle.
  55396. */
  55397. this.size = 0;
  55398. /**
  55399. * The current scale of the particle.
  55400. */
  55401. this.scale = new BABYLON.Vector2(1, 1);
  55402. /**
  55403. * The current angle of the particle.
  55404. */
  55405. this.angle = 0;
  55406. /**
  55407. * Defines how fast is the angle changing.
  55408. */
  55409. this.angularSpeed = 0;
  55410. /**
  55411. * Defines the cell index used by the particle to be rendered from a sprite.
  55412. */
  55413. this.cellIndex = 0;
  55414. /** @hidden */
  55415. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55416. /** @hidden */
  55417. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55418. /** @hidden */
  55419. this._currentSize1 = 0;
  55420. /** @hidden */
  55421. this._currentSize2 = 0;
  55422. /** @hidden */
  55423. this._currentAngularSpeed1 = 0;
  55424. /** @hidden */
  55425. this._currentAngularSpeed2 = 0;
  55426. /** @hidden */
  55427. this._currentVelocity1 = 0;
  55428. /** @hidden */
  55429. this._currentVelocity2 = 0;
  55430. /** @hidden */
  55431. this._currentLimitVelocity1 = 0;
  55432. /** @hidden */
  55433. this._currentLimitVelocity2 = 0;
  55434. /** @hidden */
  55435. this._currentDrag1 = 0;
  55436. /** @hidden */
  55437. this._currentDrag2 = 0;
  55438. if (!this.particleSystem.isAnimationSheetEnabled) {
  55439. return;
  55440. }
  55441. this.updateCellInfoFromSystem();
  55442. }
  55443. Particle.prototype.updateCellInfoFromSystem = function () {
  55444. this.cellIndex = this.particleSystem.startSpriteCellID;
  55445. };
  55446. /**
  55447. * Defines how the sprite cell index is updated for the particle
  55448. */
  55449. Particle.prototype.updateCellIndex = function () {
  55450. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55451. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55452. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55453. };
  55454. /**
  55455. * Copy the properties of particle to another one.
  55456. * @param other the particle to copy the information to.
  55457. */
  55458. Particle.prototype.copyTo = function (other) {
  55459. other.position.copyFrom(this.position);
  55460. if (this._initialDirection) {
  55461. if (other._initialDirection) {
  55462. other._initialDirection.copyFrom(this._initialDirection);
  55463. }
  55464. else {
  55465. other._initialDirection = this._initialDirection.clone();
  55466. }
  55467. }
  55468. else {
  55469. other._initialDirection = null;
  55470. }
  55471. other.direction.copyFrom(this.direction);
  55472. other.color.copyFrom(this.color);
  55473. other.colorStep.copyFrom(this.colorStep);
  55474. other.lifeTime = this.lifeTime;
  55475. other.age = this.age;
  55476. other.size = this.size;
  55477. other.scale.copyFrom(this.scale);
  55478. other.angle = this.angle;
  55479. other.angularSpeed = this.angularSpeed;
  55480. other.particleSystem = this.particleSystem;
  55481. other.cellIndex = this.cellIndex;
  55482. if (this._currentColorGradient) {
  55483. other._currentColorGradient = this._currentColorGradient;
  55484. other._currentColor1.copyFrom(this._currentColor1);
  55485. other._currentColor2.copyFrom(this._currentColor2);
  55486. }
  55487. if (this._currentSizeGradient) {
  55488. other._currentSizeGradient = this._currentSizeGradient;
  55489. other._currentSize1 = this._currentSize1;
  55490. other._currentSize2 = this._currentSize2;
  55491. }
  55492. if (this._currentAngularSpeedGradient) {
  55493. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55494. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55495. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55496. }
  55497. if (this._currentVelocityGradient) {
  55498. other._currentVelocityGradient = this._currentVelocityGradient;
  55499. other._currentVelocity1 = this._currentVelocity1;
  55500. other._currentVelocity2 = this._currentVelocity2;
  55501. }
  55502. if (this._currentLimitVelocityGradient) {
  55503. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55504. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55505. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55506. }
  55507. if (this._currentDragGradient) {
  55508. other._currentDragGradient = this._currentDragGradient;
  55509. other._currentDrag1 = this._currentDrag1;
  55510. other._currentDrag2 = this._currentDrag2;
  55511. }
  55512. if (this.particleSystem.isAnimationSheetEnabled) {
  55513. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55514. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55515. }
  55516. };
  55517. return Particle;
  55518. }());
  55519. BABYLON.Particle = Particle;
  55520. })(BABYLON || (BABYLON = {}));
  55521. //# sourceMappingURL=babylon.particle.js.map
  55522. var BABYLON;
  55523. (function (BABYLON) {
  55524. /**
  55525. * This represents the base class for particle system in Babylon.
  55526. * 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.
  55527. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55528. * @example https://doc.babylonjs.com/babylon101/particles
  55529. */
  55530. var BaseParticleSystem = /** @class */ (function () {
  55531. /**
  55532. * Instantiates a particle system.
  55533. * 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.
  55534. * @param name The name of the particle system
  55535. */
  55536. function BaseParticleSystem(name) {
  55537. /**
  55538. * List of animations used by the particle system.
  55539. */
  55540. this.animations = [];
  55541. /**
  55542. * The rendering group used by the Particle system to chose when to render.
  55543. */
  55544. this.renderingGroupId = 0;
  55545. /**
  55546. * The emitter represents the Mesh or position we are attaching the particle system to.
  55547. */
  55548. this.emitter = null;
  55549. /**
  55550. * The maximum number of particles to emit per frame
  55551. */
  55552. this.emitRate = 10;
  55553. /**
  55554. * If you want to launch only a few particles at once, that can be done, as well.
  55555. */
  55556. this.manualEmitCount = -1;
  55557. /**
  55558. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55559. */
  55560. this.updateSpeed = 0.01;
  55561. /**
  55562. * The amount of time the particle system is running (depends of the overall update speed).
  55563. */
  55564. this.targetStopDuration = 0;
  55565. /**
  55566. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55567. */
  55568. this.disposeOnStop = false;
  55569. /**
  55570. * Minimum power of emitting particles.
  55571. */
  55572. this.minEmitPower = 1;
  55573. /**
  55574. * Maximum power of emitting particles.
  55575. */
  55576. this.maxEmitPower = 1;
  55577. /**
  55578. * Minimum life time of emitting particles.
  55579. */
  55580. this.minLifeTime = 1;
  55581. /**
  55582. * Maximum life time of emitting particles.
  55583. */
  55584. this.maxLifeTime = 1;
  55585. /**
  55586. * Minimum Size of emitting particles.
  55587. */
  55588. this.minSize = 1;
  55589. /**
  55590. * Maximum Size of emitting particles.
  55591. */
  55592. this.maxSize = 1;
  55593. /**
  55594. * Minimum scale of emitting particles on X axis.
  55595. */
  55596. this.minScaleX = 1;
  55597. /**
  55598. * Maximum scale of emitting particles on X axis.
  55599. */
  55600. this.maxScaleX = 1;
  55601. /**
  55602. * Minimum scale of emitting particles on Y axis.
  55603. */
  55604. this.minScaleY = 1;
  55605. /**
  55606. * Maximum scale of emitting particles on Y axis.
  55607. */
  55608. this.maxScaleY = 1;
  55609. /**
  55610. * Gets or sets the minimal initial rotation in radians.
  55611. */
  55612. this.minInitialRotation = 0;
  55613. /**
  55614. * Gets or sets the maximal initial rotation in radians.
  55615. */
  55616. this.maxInitialRotation = 0;
  55617. /**
  55618. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55619. */
  55620. this.minAngularSpeed = 0;
  55621. /**
  55622. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55623. */
  55624. this.maxAngularSpeed = 0;
  55625. /**
  55626. * The layer mask we are rendering the particles through.
  55627. */
  55628. this.layerMask = 0x0FFFFFFF;
  55629. /**
  55630. * This can help using your own shader to render the particle system.
  55631. * The according effect will be created
  55632. */
  55633. this.customShader = null;
  55634. /**
  55635. * By default particle system starts as soon as they are created. This prevents the
  55636. * automatic start to happen and let you decide when to start emitting particles.
  55637. */
  55638. this.preventAutoStart = false;
  55639. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55640. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55641. /**
  55642. * Callback triggered when the particle animation is ending.
  55643. */
  55644. this.onAnimationEnd = null;
  55645. /**
  55646. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55647. */
  55648. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55649. /**
  55650. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55651. * to override the particles.
  55652. */
  55653. this.forceDepthWrite = false;
  55654. /** 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 */
  55655. this.preWarmCycles = 0;
  55656. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55657. this.preWarmStepOffset = 1;
  55658. /**
  55659. * 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)
  55660. */
  55661. this.spriteCellChangeSpeed = 1;
  55662. /**
  55663. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55664. */
  55665. this.startSpriteCellID = 0;
  55666. /**
  55667. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55668. */
  55669. this.endSpriteCellID = 0;
  55670. /**
  55671. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55672. */
  55673. this.spriteCellWidth = 0;
  55674. /**
  55675. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55676. */
  55677. this.spriteCellHeight = 0;
  55678. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55679. this.translationPivot = new BABYLON.Vector2(0, 0);
  55680. /**
  55681. * You can use gravity if you want to give an orientation to your particles.
  55682. */
  55683. this.gravity = BABYLON.Vector3.Zero();
  55684. this._colorGradients = null;
  55685. this._sizeGradients = null;
  55686. this._lifeTimeGradients = null;
  55687. this._angularSpeedGradients = null;
  55688. this._velocityGradients = null;
  55689. this._limitVelocityGradients = null;
  55690. this._dragGradients = null;
  55691. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55692. this.limitVelocityDamping = 0.4;
  55693. /**
  55694. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55695. */
  55696. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55697. /**
  55698. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55699. */
  55700. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55701. /**
  55702. * Color the particle will have at the end of its lifetime
  55703. */
  55704. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55705. /**
  55706. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55707. */
  55708. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55709. /**
  55710. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55711. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55712. */
  55713. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55714. this._isBillboardBased = true;
  55715. /**
  55716. * Local cache of defines for image processing.
  55717. */
  55718. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55719. this.id = name;
  55720. this.name = name;
  55721. }
  55722. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55723. /**
  55724. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55725. */
  55726. get: function () {
  55727. return this._isAnimationSheetEnabled;
  55728. },
  55729. set: function (value) {
  55730. if (this._isAnimationSheetEnabled == value) {
  55731. return;
  55732. }
  55733. this._isAnimationSheetEnabled = value;
  55734. this._reset();
  55735. },
  55736. enumerable: true,
  55737. configurable: true
  55738. });
  55739. /**
  55740. * Gets the current list of drag gradients.
  55741. * You must use addDragGradient and removeDragGradient to udpate this list
  55742. * @returns the list of drag gradients
  55743. */
  55744. BaseParticleSystem.prototype.getDragGradients = function () {
  55745. return this._dragGradients;
  55746. };
  55747. /**
  55748. * Gets the current list of limit velocity gradients.
  55749. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55750. * @returns the list of limit velocity gradients
  55751. */
  55752. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55753. return this._limitVelocityGradients;
  55754. };
  55755. /**
  55756. * Gets the current list of color gradients.
  55757. * You must use addColorGradient and removeColorGradient to udpate this list
  55758. * @returns the list of color gradients
  55759. */
  55760. BaseParticleSystem.prototype.getColorGradients = function () {
  55761. return this._colorGradients;
  55762. };
  55763. /**
  55764. * Gets the current list of size gradients.
  55765. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55766. * @returns the list of size gradients
  55767. */
  55768. BaseParticleSystem.prototype.getSizeGradients = function () {
  55769. return this._sizeGradients;
  55770. };
  55771. /**
  55772. * Gets the current list of life time gradients.
  55773. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55774. * @returns the list of life time gradients
  55775. */
  55776. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55777. return this._lifeTimeGradients;
  55778. };
  55779. /**
  55780. * Gets the current list of angular speed gradients.
  55781. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55782. * @returns the list of angular speed gradients
  55783. */
  55784. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55785. return this._angularSpeedGradients;
  55786. };
  55787. /**
  55788. * Gets the current list of velocity gradients.
  55789. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55790. * @returns the list of velocity gradients
  55791. */
  55792. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55793. return this._velocityGradients;
  55794. };
  55795. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55796. /**
  55797. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55798. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55799. */
  55800. get: function () {
  55801. if (this.particleEmitterType.direction1) {
  55802. return this.particleEmitterType.direction1;
  55803. }
  55804. return BABYLON.Vector3.Zero();
  55805. },
  55806. set: function (value) {
  55807. if (this.particleEmitterType.direction1) {
  55808. this.particleEmitterType.direction1 = value;
  55809. }
  55810. },
  55811. enumerable: true,
  55812. configurable: true
  55813. });
  55814. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55815. /**
  55816. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55817. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55818. */
  55819. get: function () {
  55820. if (this.particleEmitterType.direction2) {
  55821. return this.particleEmitterType.direction2;
  55822. }
  55823. return BABYLON.Vector3.Zero();
  55824. },
  55825. set: function (value) {
  55826. if (this.particleEmitterType.direction2) {
  55827. this.particleEmitterType.direction2 = value;
  55828. }
  55829. },
  55830. enumerable: true,
  55831. configurable: true
  55832. });
  55833. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55834. /**
  55835. * 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.
  55836. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55837. */
  55838. get: function () {
  55839. if (this.particleEmitterType.minEmitBox) {
  55840. return this.particleEmitterType.minEmitBox;
  55841. }
  55842. return BABYLON.Vector3.Zero();
  55843. },
  55844. set: function (value) {
  55845. if (this.particleEmitterType.minEmitBox) {
  55846. this.particleEmitterType.minEmitBox = value;
  55847. }
  55848. },
  55849. enumerable: true,
  55850. configurable: true
  55851. });
  55852. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55853. /**
  55854. * 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.
  55855. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55856. */
  55857. get: function () {
  55858. if (this.particleEmitterType.maxEmitBox) {
  55859. return this.particleEmitterType.maxEmitBox;
  55860. }
  55861. return BABYLON.Vector3.Zero();
  55862. },
  55863. set: function (value) {
  55864. if (this.particleEmitterType.maxEmitBox) {
  55865. this.particleEmitterType.maxEmitBox = value;
  55866. }
  55867. },
  55868. enumerable: true,
  55869. configurable: true
  55870. });
  55871. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55872. /**
  55873. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55874. */
  55875. get: function () {
  55876. return this._isBillboardBased;
  55877. },
  55878. set: function (value) {
  55879. if (this._isBillboardBased === value) {
  55880. return;
  55881. }
  55882. this._isBillboardBased = value;
  55883. this._reset();
  55884. },
  55885. enumerable: true,
  55886. configurable: true
  55887. });
  55888. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55889. /**
  55890. * Gets the image processing configuration used either in this material.
  55891. */
  55892. get: function () {
  55893. return this._imageProcessingConfiguration;
  55894. },
  55895. /**
  55896. * Sets the Default image processing configuration used either in the this material.
  55897. *
  55898. * If sets to null, the scene one is in use.
  55899. */
  55900. set: function (value) {
  55901. this._attachImageProcessingConfiguration(value);
  55902. },
  55903. enumerable: true,
  55904. configurable: true
  55905. });
  55906. /**
  55907. * Attaches a new image processing configuration to the Standard Material.
  55908. * @param configuration
  55909. */
  55910. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  55911. if (configuration === this._imageProcessingConfiguration) {
  55912. return;
  55913. }
  55914. // Pick the scene configuration if needed.
  55915. if (!configuration) {
  55916. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  55917. }
  55918. else {
  55919. this._imageProcessingConfiguration = configuration;
  55920. }
  55921. };
  55922. /** @hidden */
  55923. BaseParticleSystem.prototype._reset = function () {
  55924. };
  55925. /**
  55926. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  55927. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55928. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55929. * @returns the emitter
  55930. */
  55931. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  55932. var particleEmitter = new BABYLON.PointParticleEmitter();
  55933. particleEmitter.direction1 = direction1;
  55934. particleEmitter.direction2 = direction2;
  55935. this.particleEmitterType = particleEmitter;
  55936. return particleEmitter;
  55937. };
  55938. /**
  55939. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  55940. * @param radius The radius of the hemisphere to emit from
  55941. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55942. * @returns the emitter
  55943. */
  55944. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  55945. if (radius === void 0) { radius = 1; }
  55946. if (radiusRange === void 0) { radiusRange = 1; }
  55947. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  55948. this.particleEmitterType = particleEmitter;
  55949. return particleEmitter;
  55950. };
  55951. /**
  55952. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  55953. * @param radius The radius of the sphere to emit from
  55954. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55955. * @returns the emitter
  55956. */
  55957. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  55958. if (radius === void 0) { radius = 1; }
  55959. if (radiusRange === void 0) { radiusRange = 1; }
  55960. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  55961. this.particleEmitterType = particleEmitter;
  55962. return particleEmitter;
  55963. };
  55964. /**
  55965. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  55966. * @param radius The radius of the sphere to emit from
  55967. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55968. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55969. * @returns the emitter
  55970. */
  55971. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55972. if (radius === void 0) { radius = 1; }
  55973. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55974. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55975. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55976. this.particleEmitterType = particleEmitter;
  55977. return particleEmitter;
  55978. };
  55979. /**
  55980. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  55981. * @param radius The radius of the cone to emit from
  55982. * @param angle The base angle of the cone
  55983. * @returns the emitter
  55984. */
  55985. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55986. if (radius === void 0) { radius = 1; }
  55987. if (angle === void 0) { angle = Math.PI / 4; }
  55988. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55989. this.particleEmitterType = particleEmitter;
  55990. return particleEmitter;
  55991. };
  55992. /**
  55993. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55994. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55995. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55996. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55997. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55998. * @returns the emitter
  55999. */
  56000. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56001. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56002. this.particleEmitterType = particleEmitter;
  56003. this.direction1 = direction1;
  56004. this.direction2 = direction2;
  56005. this.minEmitBox = minEmitBox;
  56006. this.maxEmitBox = maxEmitBox;
  56007. return particleEmitter;
  56008. };
  56009. /**
  56010. * Source color is added to the destination color without alpha affecting the result.
  56011. */
  56012. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  56013. /**
  56014. * Blend current color and particle color using particle’s alpha.
  56015. */
  56016. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  56017. /**
  56018. * Add current color and particle color multiplied by particle’s alpha.
  56019. */
  56020. BaseParticleSystem.BLENDMODE_ADD = 2;
  56021. return BaseParticleSystem;
  56022. }());
  56023. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56024. })(BABYLON || (BABYLON = {}));
  56025. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56026. var BABYLON;
  56027. (function (BABYLON) {
  56028. /**
  56029. * This represents a particle system in Babylon.
  56030. * 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.
  56031. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56032. * @example https://doc.babylonjs.com/babylon101/particles
  56033. */
  56034. var ParticleSystem = /** @class */ (function (_super) {
  56035. __extends(ParticleSystem, _super);
  56036. /**
  56037. * Instantiates a particle system.
  56038. * 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.
  56039. * @param name The name of the particle system
  56040. * @param capacity The max number of particles alive at the same time
  56041. * @param scene The scene the particle system belongs to
  56042. * @param customEffect a custom effect used to change the way particles are rendered by default
  56043. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56044. * @param epsilon Offset used to render the particles
  56045. */
  56046. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56047. if (customEffect === void 0) { customEffect = null; }
  56048. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56049. if (epsilon === void 0) { epsilon = 0.01; }
  56050. var _this = _super.call(this, name) || this;
  56051. /**
  56052. * An event triggered when the system is disposed
  56053. */
  56054. _this.onDisposeObservable = new BABYLON.Observable();
  56055. _this._particles = new Array();
  56056. _this._stockParticles = new Array();
  56057. _this._newPartsExcess = 0;
  56058. _this._vertexBuffers = {};
  56059. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56060. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56061. _this._scaledDirection = BABYLON.Vector3.Zero();
  56062. _this._scaledGravity = BABYLON.Vector3.Zero();
  56063. _this._currentRenderId = -1;
  56064. _this._useInstancing = false;
  56065. _this._started = false;
  56066. _this._stopped = false;
  56067. _this._actualFrame = 0;
  56068. // start of sub system methods
  56069. /**
  56070. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56071. * Its lifetime will start back at 0.
  56072. */
  56073. _this.recycleParticle = function (particle) {
  56074. var lastParticle = _this._particles.pop();
  56075. if (lastParticle !== particle) {
  56076. lastParticle.copyTo(particle);
  56077. }
  56078. _this._stockParticles.push(lastParticle);
  56079. };
  56080. _this._createParticle = function () {
  56081. var particle;
  56082. if (_this._stockParticles.length !== 0) {
  56083. particle = _this._stockParticles.pop();
  56084. particle.age = 0;
  56085. particle._currentColorGradient = null;
  56086. particle.cellIndex = _this.startSpriteCellID;
  56087. }
  56088. else {
  56089. particle = new BABYLON.Particle(_this);
  56090. }
  56091. return particle;
  56092. };
  56093. _this._emitFromParticle = function (particle) {
  56094. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56095. return;
  56096. }
  56097. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56098. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56099. subSystem._rootParticleSystem = _this;
  56100. _this.activeSubSystems.push(subSystem);
  56101. subSystem.start();
  56102. };
  56103. _this._capacity = capacity;
  56104. _this._epsilon = epsilon;
  56105. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56106. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56107. // Setup the default processing configuration to the scene.
  56108. _this._attachImageProcessingConfiguration(null);
  56109. _this._customEffect = customEffect;
  56110. _this._scene.particleSystems.push(_this);
  56111. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56112. _this._createIndexBuffer();
  56113. _this._createVertexBuffers();
  56114. // Default emitter type
  56115. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56116. _this.updateFunction = function (particles) {
  56117. var noiseTextureData = null;
  56118. var noiseTextureSize = null;
  56119. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56120. noiseTextureData = (_this.noiseTexture.readPixels());
  56121. noiseTextureSize = _this.noiseTexture.getSize();
  56122. }
  56123. var _loop_1 = function () {
  56124. particle = particles[index];
  56125. particle.age += _this._scaledUpdateSpeed;
  56126. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56127. _this._emitFromParticle(particle);
  56128. _this.recycleParticle(particle);
  56129. index--;
  56130. return "continue";
  56131. }
  56132. else {
  56133. var ratio = particle.age / particle.lifeTime;
  56134. // Color
  56135. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56136. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56137. if (currentGradient !== particle._currentColorGradient) {
  56138. particle._currentColor1.copyFrom(particle._currentColor2);
  56139. nextGradient.getColorToRef(particle._currentColor2);
  56140. particle._currentColorGradient = currentGradient;
  56141. }
  56142. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56143. });
  56144. }
  56145. else {
  56146. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56147. particle.color.addInPlace(_this._scaledColorStep);
  56148. if (particle.color.a < 0) {
  56149. particle.color.a = 0;
  56150. }
  56151. }
  56152. // Angular speed
  56153. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56154. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56155. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56156. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56157. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56158. particle._currentAngularSpeedGradient = currentGradient;
  56159. }
  56160. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56161. });
  56162. }
  56163. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56164. // Direction
  56165. var directionScale_1 = _this._scaledUpdateSpeed;
  56166. /// Velocity
  56167. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56168. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56169. if (currentGradient !== particle._currentVelocityGradient) {
  56170. particle._currentVelocity1 = particle._currentVelocity2;
  56171. particle._currentVelocity2 = nextGradient.getFactor();
  56172. particle._currentVelocityGradient = currentGradient;
  56173. }
  56174. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56175. });
  56176. }
  56177. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56178. /// Limit velocity
  56179. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56180. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56181. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56182. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56183. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56184. particle._currentLimitVelocityGradient = currentGradient;
  56185. }
  56186. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56187. var currentVelocity = particle.direction.length();
  56188. if (currentVelocity > limitVelocity) {
  56189. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56190. }
  56191. });
  56192. }
  56193. /// Drag
  56194. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56195. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56196. if (currentGradient !== particle._currentDragGradient) {
  56197. particle._currentDrag1 = particle._currentDrag2;
  56198. particle._currentDrag2 = nextGradient.getFactor();
  56199. particle._currentDragGradient = currentGradient;
  56200. }
  56201. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56202. _this._scaledDirection.scaleInPlace(drag);
  56203. });
  56204. }
  56205. particle.position.addInPlace(_this._scaledDirection);
  56206. // Noise
  56207. if (noiseTextureData && noiseTextureSize) {
  56208. var localPosition = BABYLON.Tmp.Vector3[0];
  56209. var emitterPosition = BABYLON.Tmp.Vector3[1];
  56210. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  56211. particle.position.subtractToRef(emitterPosition, localPosition);
  56212. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56213. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56214. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56215. var force = BABYLON.Tmp.Vector3[0];
  56216. var scaledForce = BABYLON.Tmp.Vector3[1];
  56217. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56218. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56219. particle.direction.addInPlace(scaledForce);
  56220. }
  56221. // Gravity
  56222. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56223. particle.direction.addInPlace(_this._scaledGravity);
  56224. // Size
  56225. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56226. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56227. if (currentGradient !== particle._currentSizeGradient) {
  56228. particle._currentSize1 = particle._currentSize2;
  56229. particle._currentSize2 = nextGradient.getFactor();
  56230. particle._currentSizeGradient = currentGradient;
  56231. }
  56232. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56233. });
  56234. }
  56235. if (_this._isAnimationSheetEnabled) {
  56236. particle.updateCellIndex();
  56237. }
  56238. }
  56239. };
  56240. var particle;
  56241. for (var index = 0; index < particles.length; index++) {
  56242. _loop_1();
  56243. }
  56244. };
  56245. return _this;
  56246. }
  56247. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56248. /**
  56249. * Sets a callback that will be triggered when the system is disposed
  56250. */
  56251. set: function (callback) {
  56252. if (this._onDisposeObserver) {
  56253. this.onDisposeObservable.remove(this._onDisposeObserver);
  56254. }
  56255. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56256. },
  56257. enumerable: true,
  56258. configurable: true
  56259. });
  56260. /**
  56261. * Get hosting scene
  56262. * @returns the scene
  56263. */
  56264. ParticleSystem.prototype.getScene = function () {
  56265. return this._scene;
  56266. };
  56267. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56268. //end of Sub-emitter
  56269. /**
  56270. * Gets the current list of active particles
  56271. */
  56272. get: function () {
  56273. return this._particles;
  56274. },
  56275. enumerable: true,
  56276. configurable: true
  56277. });
  56278. /**
  56279. * Returns the string "ParticleSystem"
  56280. * @returns a string containing the class name
  56281. */
  56282. ParticleSystem.prototype.getClassName = function () {
  56283. return "ParticleSystem";
  56284. };
  56285. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56286. var newGradient = new BABYLON.FactorGradient();
  56287. newGradient.gradient = gradient;
  56288. newGradient.factor1 = factor;
  56289. newGradient.factor2 = factor2;
  56290. factorGradients.push(newGradient);
  56291. factorGradients.sort(function (a, b) {
  56292. if (a.gradient < b.gradient) {
  56293. return -1;
  56294. }
  56295. else if (a.gradient > b.gradient) {
  56296. return 1;
  56297. }
  56298. return 0;
  56299. });
  56300. };
  56301. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56302. if (!factorGradients) {
  56303. return;
  56304. }
  56305. var index = 0;
  56306. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56307. var factorGradient = factorGradients_1[_i];
  56308. if (factorGradient.gradient === gradient) {
  56309. factorGradients.splice(index, 1);
  56310. break;
  56311. }
  56312. index++;
  56313. }
  56314. };
  56315. /**
  56316. * Adds a new life time gradient
  56317. * @param gradient defines the gradient to use (between 0 and 1)
  56318. * @param factor defines the life time factor to affect to the specified gradient
  56319. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56320. * @returns the current particle system
  56321. */
  56322. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56323. if (!this._lifeTimeGradients) {
  56324. this._lifeTimeGradients = [];
  56325. }
  56326. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56327. return this;
  56328. };
  56329. /**
  56330. * Remove a specific life time gradient
  56331. * @param gradient defines the gradient to remove
  56332. * @returns the current particle system
  56333. */
  56334. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56335. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56336. return this;
  56337. };
  56338. /**
  56339. * Adds a new size gradient
  56340. * @param gradient defines the gradient to use (between 0 and 1)
  56341. * @param factor defines the size factor to affect to the specified gradient
  56342. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56343. * @returns the current particle system
  56344. */
  56345. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56346. if (!this._sizeGradients) {
  56347. this._sizeGradients = [];
  56348. }
  56349. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56350. return this;
  56351. };
  56352. /**
  56353. * Remove a specific size gradient
  56354. * @param gradient defines the gradient to remove
  56355. * @returns the current particle system
  56356. */
  56357. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56358. this._removeFactorGradient(this._sizeGradients, gradient);
  56359. return this;
  56360. };
  56361. /**
  56362. * Adds a new angular speed gradient
  56363. * @param gradient defines the gradient to use (between 0 and 1)
  56364. * @param factor defines the angular speed to affect to the specified gradient
  56365. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56366. * @returns the current particle system
  56367. */
  56368. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56369. if (!this._angularSpeedGradients) {
  56370. this._angularSpeedGradients = [];
  56371. }
  56372. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56373. return this;
  56374. };
  56375. /**
  56376. * Remove a specific angular speed gradient
  56377. * @param gradient defines the gradient to remove
  56378. * @returns the current particle system
  56379. */
  56380. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56381. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56382. return this;
  56383. };
  56384. /**
  56385. * Adds a new velocity gradient
  56386. * @param gradient defines the gradient to use (between 0 and 1)
  56387. * @param factor defines the velocity to affect to the specified gradient
  56388. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56389. * @returns the current particle system
  56390. */
  56391. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56392. if (!this._velocityGradients) {
  56393. this._velocityGradients = [];
  56394. }
  56395. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56396. return this;
  56397. };
  56398. /**
  56399. * Remove a specific velocity gradient
  56400. * @param gradient defines the gradient to remove
  56401. * @returns the current particle system
  56402. */
  56403. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56404. this._removeFactorGradient(this._velocityGradients, gradient);
  56405. return this;
  56406. };
  56407. /**
  56408. * Adds a new limit velocity gradient
  56409. * @param gradient defines the gradient to use (between 0 and 1)
  56410. * @param factor defines the limit velocity value to affect to the specified gradient
  56411. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56412. * @returns the current particle system
  56413. */
  56414. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56415. if (!this._limitVelocityGradients) {
  56416. this._limitVelocityGradients = [];
  56417. }
  56418. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56419. return this;
  56420. };
  56421. /**
  56422. * Remove a specific limit velocity gradient
  56423. * @param gradient defines the gradient to remove
  56424. * @returns the current particle system
  56425. */
  56426. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56427. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56428. return this;
  56429. };
  56430. /**
  56431. * Adds a new drag gradient
  56432. * @param gradient defines the gradient to use (between 0 and 1)
  56433. * @param factor defines the drag value to affect to the specified gradient
  56434. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56435. * @returns the current particle system
  56436. */
  56437. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56438. if (!this._dragGradients) {
  56439. this._dragGradients = [];
  56440. }
  56441. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56442. return this;
  56443. };
  56444. /**
  56445. * Remove a specific drag gradient
  56446. * @param gradient defines the gradient to remove
  56447. * @returns the current particle system
  56448. */
  56449. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56450. this._removeFactorGradient(this._dragGradients, gradient);
  56451. return this;
  56452. };
  56453. /**
  56454. * Adds a new color gradient
  56455. * @param gradient defines the gradient to use (between 0 and 1)
  56456. * @param color defines the color to affect to the specified gradient
  56457. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56458. */
  56459. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56460. if (!this._colorGradients) {
  56461. this._colorGradients = [];
  56462. }
  56463. var colorGradient = new BABYLON.ColorGradient();
  56464. colorGradient.gradient = gradient;
  56465. colorGradient.color1 = color;
  56466. colorGradient.color2 = color2;
  56467. this._colorGradients.push(colorGradient);
  56468. this._colorGradients.sort(function (a, b) {
  56469. if (a.gradient < b.gradient) {
  56470. return -1;
  56471. }
  56472. else if (a.gradient > b.gradient) {
  56473. return 1;
  56474. }
  56475. return 0;
  56476. });
  56477. return this;
  56478. };
  56479. /**
  56480. * Remove a specific color gradient
  56481. * @param gradient defines the gradient to remove
  56482. */
  56483. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56484. if (!this._colorGradients) {
  56485. return this;
  56486. }
  56487. var index = 0;
  56488. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56489. var colorGradient = _a[_i];
  56490. if (colorGradient.gradient === gradient) {
  56491. this._colorGradients.splice(index, 1);
  56492. break;
  56493. }
  56494. index++;
  56495. }
  56496. return this;
  56497. };
  56498. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56499. u = Math.abs(u) * 0.5 + 0.5;
  56500. v = Math.abs(v) * 0.5 + 0.5;
  56501. var wrappedU = ((u * width) % width) | 0;
  56502. var wrappedV = ((v * height) % height) | 0;
  56503. var position = (wrappedU + wrappedV * width) * 4;
  56504. return pixels[position] / 255;
  56505. };
  56506. ParticleSystem.prototype._reset = function () {
  56507. this._resetEffect();
  56508. };
  56509. ParticleSystem.prototype._resetEffect = function () {
  56510. if (this._vertexBuffer) {
  56511. this._vertexBuffer.dispose();
  56512. this._vertexBuffer = null;
  56513. }
  56514. if (this._spriteBuffer) {
  56515. this._spriteBuffer.dispose();
  56516. this._spriteBuffer = null;
  56517. }
  56518. this._createVertexBuffers();
  56519. };
  56520. ParticleSystem.prototype._createVertexBuffers = function () {
  56521. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56522. if (this._isAnimationSheetEnabled) {
  56523. this._vertexBufferSize += 1;
  56524. }
  56525. if (!this._isBillboardBased) {
  56526. this._vertexBufferSize += 3;
  56527. }
  56528. var engine = this._scene.getEngine();
  56529. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56530. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56531. var dataOffset = 0;
  56532. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56533. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56534. dataOffset += 3;
  56535. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56536. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56537. dataOffset += 4;
  56538. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56539. this._vertexBuffers["angle"] = options;
  56540. dataOffset += 1;
  56541. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56542. this._vertexBuffers["size"] = size;
  56543. dataOffset += 2;
  56544. if (this._isAnimationSheetEnabled) {
  56545. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56546. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56547. dataOffset += 1;
  56548. }
  56549. if (!this._isBillboardBased) {
  56550. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56551. this._vertexBuffers["direction"] = directionBuffer;
  56552. dataOffset += 3;
  56553. }
  56554. var offsets;
  56555. if (this._useInstancing) {
  56556. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56557. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56558. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56559. }
  56560. else {
  56561. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56562. dataOffset += 2;
  56563. }
  56564. this._vertexBuffers["offset"] = offsets;
  56565. };
  56566. ParticleSystem.prototype._createIndexBuffer = function () {
  56567. if (this._useInstancing) {
  56568. return;
  56569. }
  56570. var indices = [];
  56571. var index = 0;
  56572. for (var count = 0; count < this._capacity; count++) {
  56573. indices.push(index);
  56574. indices.push(index + 1);
  56575. indices.push(index + 2);
  56576. indices.push(index);
  56577. indices.push(index + 2);
  56578. indices.push(index + 3);
  56579. index += 4;
  56580. }
  56581. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56582. };
  56583. /**
  56584. * Gets the maximum number of particles active at the same time.
  56585. * @returns The max number of active particles.
  56586. */
  56587. ParticleSystem.prototype.getCapacity = function () {
  56588. return this._capacity;
  56589. };
  56590. /**
  56591. * Gets whether there are still active particles in the system.
  56592. * @returns True if it is alive, otherwise false.
  56593. */
  56594. ParticleSystem.prototype.isAlive = function () {
  56595. return this._alive;
  56596. };
  56597. /**
  56598. * Gets whether the system has been started.
  56599. * @returns True if it has been started, otherwise false.
  56600. */
  56601. ParticleSystem.prototype.isStarted = function () {
  56602. return this._started;
  56603. };
  56604. /**
  56605. * Starts the particle system and begins to emit
  56606. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  56607. */
  56608. ParticleSystem.prototype.start = function (delay) {
  56609. var _this = this;
  56610. if (delay === void 0) { delay = 0; }
  56611. if (delay) {
  56612. setTimeout(function () {
  56613. _this.start(0);
  56614. }, delay);
  56615. return;
  56616. }
  56617. this._started = true;
  56618. this._stopped = false;
  56619. this._actualFrame = 0;
  56620. if (this.subEmitters && this.subEmitters.length != 0) {
  56621. this.activeSubSystems = new Array();
  56622. }
  56623. if (this.preWarmCycles) {
  56624. for (var index = 0; index < this.preWarmCycles; index++) {
  56625. this.animate(true);
  56626. }
  56627. }
  56628. };
  56629. /**
  56630. * Stops the particle system.
  56631. * @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.
  56632. */
  56633. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56634. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56635. this._stopped = true;
  56636. if (stopSubEmitters) {
  56637. this._stopSubEmitters();
  56638. }
  56639. };
  56640. // animation sheet
  56641. /**
  56642. * Remove all active particles
  56643. */
  56644. ParticleSystem.prototype.reset = function () {
  56645. this._stockParticles = [];
  56646. this._particles = [];
  56647. };
  56648. /**
  56649. * @hidden (for internal use only)
  56650. */
  56651. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56652. var offset = index * this._vertexBufferSize;
  56653. this._vertexData[offset++] = particle.position.x;
  56654. this._vertexData[offset++] = particle.position.y;
  56655. this._vertexData[offset++] = particle.position.z;
  56656. this._vertexData[offset++] = particle.color.r;
  56657. this._vertexData[offset++] = particle.color.g;
  56658. this._vertexData[offset++] = particle.color.b;
  56659. this._vertexData[offset++] = particle.color.a;
  56660. this._vertexData[offset++] = particle.angle;
  56661. this._vertexData[offset++] = particle.scale.x * particle.size;
  56662. this._vertexData[offset++] = particle.scale.y * particle.size;
  56663. if (this._isAnimationSheetEnabled) {
  56664. this._vertexData[offset++] = particle.cellIndex;
  56665. }
  56666. if (!this._isBillboardBased) {
  56667. if (particle._initialDirection) {
  56668. this._vertexData[offset++] = particle._initialDirection.x;
  56669. this._vertexData[offset++] = particle._initialDirection.y;
  56670. this._vertexData[offset++] = particle._initialDirection.z;
  56671. }
  56672. else {
  56673. this._vertexData[offset++] = particle.direction.x;
  56674. this._vertexData[offset++] = particle.direction.y;
  56675. this._vertexData[offset++] = particle.direction.z;
  56676. }
  56677. }
  56678. if (!this._useInstancing) {
  56679. if (this._isAnimationSheetEnabled) {
  56680. if (offsetX === 0)
  56681. offsetX = this._epsilon;
  56682. else if (offsetX === 1)
  56683. offsetX = 1 - this._epsilon;
  56684. if (offsetY === 0)
  56685. offsetY = this._epsilon;
  56686. else if (offsetY === 1)
  56687. offsetY = 1 - this._epsilon;
  56688. }
  56689. this._vertexData[offset++] = offsetX;
  56690. this._vertexData[offset++] = offsetY;
  56691. }
  56692. };
  56693. ParticleSystem.prototype._stopSubEmitters = function () {
  56694. if (!this.activeSubSystems) {
  56695. return;
  56696. }
  56697. this.activeSubSystems.forEach(function (subSystem) {
  56698. subSystem.stop(true);
  56699. });
  56700. this.activeSubSystems = new Array();
  56701. };
  56702. ParticleSystem.prototype._removeFromRoot = function () {
  56703. if (!this._rootParticleSystem) {
  56704. return;
  56705. }
  56706. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56707. if (index !== -1) {
  56708. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56709. }
  56710. };
  56711. // End of sub system methods
  56712. ParticleSystem.prototype._update = function (newParticles) {
  56713. // Update current
  56714. this._alive = this._particles.length > 0;
  56715. if (this.emitter.position) {
  56716. var emitterMesh = this.emitter;
  56717. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56718. }
  56719. else {
  56720. var emitterPosition = this.emitter;
  56721. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56722. }
  56723. this.updateFunction(this._particles);
  56724. // Add new ones
  56725. var particle;
  56726. var _loop_2 = function () {
  56727. if (this_1._particles.length === this_1._capacity) {
  56728. return "break";
  56729. }
  56730. particle = this_1._createParticle();
  56731. this_1._particles.push(particle);
  56732. // Emitter
  56733. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56734. if (this_1.startPositionFunction) {
  56735. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56736. }
  56737. else {
  56738. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56739. }
  56740. if (this_1.startDirectionFunction) {
  56741. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56742. }
  56743. else {
  56744. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56745. }
  56746. if (emitPower === 0) {
  56747. if (!particle._initialDirection) {
  56748. particle._initialDirection = particle.direction.clone();
  56749. }
  56750. else {
  56751. particle._initialDirection.copyFrom(particle.direction);
  56752. }
  56753. }
  56754. else {
  56755. particle._initialDirection = null;
  56756. }
  56757. particle.direction.scaleInPlace(emitPower);
  56758. // Life time
  56759. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  56760. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  56761. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  56762. var factorGradient1 = currentGradient;
  56763. var factorGradient2 = nextGradient;
  56764. var lifeTime1 = factorGradient1.getFactor();
  56765. var lifeTime2 = factorGradient2.getFactor();
  56766. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  56767. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  56768. });
  56769. }
  56770. else {
  56771. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  56772. }
  56773. // Size
  56774. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  56775. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  56776. }
  56777. else {
  56778. particle._currentSizeGradient = this_1._sizeGradients[0];
  56779. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  56780. particle.size = particle._currentSize1;
  56781. if (this_1._sizeGradients.length > 1) {
  56782. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  56783. }
  56784. else {
  56785. particle._currentSize2 = particle._currentSize1;
  56786. }
  56787. }
  56788. // Size and scale
  56789. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  56790. // Angle
  56791. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  56792. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  56793. }
  56794. else {
  56795. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  56796. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  56797. particle._currentAngularSpeed1 = particle.angularSpeed;
  56798. if (this_1._angularSpeedGradients.length > 1) {
  56799. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  56800. }
  56801. else {
  56802. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  56803. }
  56804. }
  56805. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  56806. // Velocity
  56807. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  56808. particle._currentVelocityGradient = this_1._velocityGradients[0];
  56809. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  56810. if (this_1._velocityGradients.length > 1) {
  56811. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  56812. }
  56813. else {
  56814. particle._currentVelocity2 = particle._currentVelocity1;
  56815. }
  56816. }
  56817. // Limit velocity
  56818. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  56819. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  56820. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  56821. if (this_1._limitVelocityGradients.length > 1) {
  56822. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  56823. }
  56824. else {
  56825. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  56826. }
  56827. }
  56828. // Drag
  56829. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  56830. particle._currentDragGradient = this_1._dragGradients[0];
  56831. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  56832. if (this_1._dragGradients.length > 1) {
  56833. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  56834. }
  56835. else {
  56836. particle._currentDrag2 = particle._currentDrag1;
  56837. }
  56838. }
  56839. // Color
  56840. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  56841. step = BABYLON.Scalar.RandomRange(0, 1.0);
  56842. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  56843. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  56844. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56845. }
  56846. else {
  56847. particle._currentColorGradient = this_1._colorGradients[0];
  56848. particle._currentColorGradient.getColorToRef(particle.color);
  56849. particle._currentColor1.copyFrom(particle.color);
  56850. if (this_1._colorGradients.length > 1) {
  56851. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  56852. }
  56853. else {
  56854. particle._currentColor2.copyFrom(particle.color);
  56855. }
  56856. }
  56857. // Sheet
  56858. if (this_1._isAnimationSheetEnabled) {
  56859. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  56860. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  56861. }
  56862. };
  56863. var this_1 = this, step;
  56864. for (var index = 0; index < newParticles; index++) {
  56865. var state_1 = _loop_2();
  56866. if (state_1 === "break")
  56867. break;
  56868. }
  56869. };
  56870. /** @hidden */
  56871. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  56872. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56873. if (isBillboardBased === void 0) { isBillboardBased = false; }
  56874. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  56875. if (isAnimationSheetEnabled) {
  56876. attributeNamesOrOptions.push("cellIndex");
  56877. }
  56878. if (!isBillboardBased) {
  56879. attributeNamesOrOptions.push("direction");
  56880. }
  56881. return attributeNamesOrOptions;
  56882. };
  56883. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  56884. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56885. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  56886. if (isAnimationSheetEnabled) {
  56887. effectCreationOption.push("particlesInfos");
  56888. }
  56889. return effectCreationOption;
  56890. };
  56891. ParticleSystem.prototype._getEffect = function () {
  56892. if (this._customEffect) {
  56893. return this._customEffect;
  56894. }
  56895. ;
  56896. var defines = [];
  56897. if (this._scene.clipPlane) {
  56898. defines.push("#define CLIPPLANE");
  56899. }
  56900. if (this._scene.clipPlane2) {
  56901. defines.push("#define CLIPPLANE2");
  56902. }
  56903. if (this._scene.clipPlane3) {
  56904. defines.push("#define CLIPPLANE3");
  56905. }
  56906. if (this._scene.clipPlane4) {
  56907. defines.push("#define CLIPPLANE4");
  56908. }
  56909. if (this._isAnimationSheetEnabled) {
  56910. defines.push("#define ANIMATESHEET");
  56911. }
  56912. if (this._isBillboardBased) {
  56913. defines.push("#define BILLBOARD");
  56914. switch (this.billboardMode) {
  56915. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  56916. defines.push("#define BILLBOARDY");
  56917. break;
  56918. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  56919. default:
  56920. break;
  56921. }
  56922. }
  56923. if (this._imageProcessingConfiguration) {
  56924. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  56925. defines.push(this._imageProcessingConfigurationDefines.toString());
  56926. }
  56927. // Effect
  56928. var join = defines.join("\n");
  56929. if (this._cachedDefines !== join) {
  56930. this._cachedDefines = join;
  56931. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  56932. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  56933. var samplers = ["diffuseSampler"];
  56934. if (BABYLON.ImageProcessingConfiguration) {
  56935. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  56936. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  56937. }
  56938. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56939. }
  56940. return this._effect;
  56941. };
  56942. /**
  56943. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56944. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  56945. */
  56946. ParticleSystem.prototype.animate = function (preWarmOnly) {
  56947. if (preWarmOnly === void 0) { preWarmOnly = false; }
  56948. if (!this._started)
  56949. return;
  56950. if (!preWarmOnly) {
  56951. var effect = this._getEffect();
  56952. // Check
  56953. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56954. return;
  56955. if (this._currentRenderId === this._scene.getRenderId()) {
  56956. return;
  56957. }
  56958. this._currentRenderId = this._scene.getRenderId();
  56959. }
  56960. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  56961. // determine the number of particles we need to create
  56962. var newParticles;
  56963. if (this.manualEmitCount > -1) {
  56964. newParticles = this.manualEmitCount;
  56965. this._newPartsExcess = 0;
  56966. this.manualEmitCount = 0;
  56967. }
  56968. else {
  56969. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56970. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56971. }
  56972. if (this._newPartsExcess > 1.0) {
  56973. newParticles += this._newPartsExcess >> 0;
  56974. this._newPartsExcess -= this._newPartsExcess >> 0;
  56975. }
  56976. this._alive = false;
  56977. if (!this._stopped) {
  56978. this._actualFrame += this._scaledUpdateSpeed;
  56979. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56980. this.stop();
  56981. }
  56982. else {
  56983. newParticles = 0;
  56984. }
  56985. this._update(newParticles);
  56986. // Stopped?
  56987. if (this._stopped) {
  56988. if (!this._alive) {
  56989. this._started = false;
  56990. if (this.onAnimationEnd) {
  56991. this.onAnimationEnd();
  56992. }
  56993. if (this.disposeOnStop) {
  56994. this._scene._toBeDisposed.push(this);
  56995. }
  56996. }
  56997. }
  56998. if (!preWarmOnly) {
  56999. // Update VBO
  57000. var offset = 0;
  57001. for (var index = 0; index < this._particles.length; index++) {
  57002. var particle = this._particles[index];
  57003. this._appendParticleVertices(offset, particle);
  57004. offset += this._useInstancing ? 1 : 4;
  57005. }
  57006. if (this._vertexBuffer) {
  57007. this._vertexBuffer.update(this._vertexData);
  57008. }
  57009. }
  57010. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57011. this.stop();
  57012. }
  57013. };
  57014. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57015. this._appendParticleVertex(offset++, particle, 0, 0);
  57016. if (!this._useInstancing) {
  57017. this._appendParticleVertex(offset++, particle, 1, 0);
  57018. this._appendParticleVertex(offset++, particle, 1, 1);
  57019. this._appendParticleVertex(offset++, particle, 0, 1);
  57020. }
  57021. };
  57022. /**
  57023. * Rebuilds the particle system.
  57024. */
  57025. ParticleSystem.prototype.rebuild = function () {
  57026. this._createIndexBuffer();
  57027. if (this._vertexBuffer) {
  57028. this._vertexBuffer._rebuild();
  57029. }
  57030. };
  57031. /**
  57032. * Is this system ready to be used/rendered
  57033. * @return true if the system is ready
  57034. */
  57035. ParticleSystem.prototype.isReady = function () {
  57036. var effect = this._getEffect();
  57037. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57038. return false;
  57039. }
  57040. return true;
  57041. };
  57042. /**
  57043. * Renders the particle system in its current state.
  57044. * @returns the current number of particles
  57045. */
  57046. ParticleSystem.prototype.render = function () {
  57047. var effect = this._getEffect();
  57048. // Check
  57049. if (!this.isReady() || !this._particles.length) {
  57050. return 0;
  57051. }
  57052. var engine = this._scene.getEngine();
  57053. // Render
  57054. engine.enableEffect(effect);
  57055. engine.setState(false);
  57056. var viewMatrix = this._scene.getViewMatrix();
  57057. effect.setTexture("diffuseSampler", this.particleTexture);
  57058. effect.setMatrix("view", viewMatrix);
  57059. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57060. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57061. var baseSize = this.particleTexture.getBaseSize();
  57062. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57063. }
  57064. effect.setVector2("translationPivot", this.translationPivot);
  57065. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57066. if (this._isBillboardBased) {
  57067. var camera = this._scene.activeCamera;
  57068. effect.setVector3("eyePosition", camera.globalPosition);
  57069. }
  57070. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57071. var invView = viewMatrix.clone();
  57072. invView.invert();
  57073. effect.setMatrix("invView", invView);
  57074. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57075. }
  57076. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57077. // image processing
  57078. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57079. this._imageProcessingConfiguration.bind(effect);
  57080. }
  57081. // Draw order
  57082. switch (this.blendMode) {
  57083. case ParticleSystem.BLENDMODE_ADD:
  57084. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57085. break;
  57086. case ParticleSystem.BLENDMODE_ONEONE:
  57087. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57088. break;
  57089. case ParticleSystem.BLENDMODE_STANDARD:
  57090. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57091. break;
  57092. }
  57093. if (this.forceDepthWrite) {
  57094. engine.setDepthWrite(true);
  57095. }
  57096. if (this._useInstancing) {
  57097. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57098. engine.unbindInstanceAttributes();
  57099. }
  57100. else {
  57101. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57102. }
  57103. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57104. return this._particles.length;
  57105. };
  57106. /**
  57107. * Disposes the particle system and free the associated resources
  57108. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57109. */
  57110. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57111. if (disposeTexture === void 0) { disposeTexture = true; }
  57112. if (this._vertexBuffer) {
  57113. this._vertexBuffer.dispose();
  57114. this._vertexBuffer = null;
  57115. }
  57116. if (this._spriteBuffer) {
  57117. this._spriteBuffer.dispose();
  57118. this._spriteBuffer = null;
  57119. }
  57120. if (this._indexBuffer) {
  57121. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57122. this._indexBuffer = null;
  57123. }
  57124. if (disposeTexture && this.particleTexture) {
  57125. this.particleTexture.dispose();
  57126. this.particleTexture = null;
  57127. }
  57128. if (disposeTexture && this.noiseTexture) {
  57129. this.noiseTexture.dispose();
  57130. this.noiseTexture = null;
  57131. }
  57132. this._removeFromRoot();
  57133. // Remove from scene
  57134. var index = this._scene.particleSystems.indexOf(this);
  57135. if (index > -1) {
  57136. this._scene.particleSystems.splice(index, 1);
  57137. }
  57138. // Callback
  57139. this.onDisposeObservable.notifyObservers(this);
  57140. this.onDisposeObservable.clear();
  57141. };
  57142. // Clone
  57143. /**
  57144. * Clones the particle system.
  57145. * @param name The name of the cloned object
  57146. * @param newEmitter The new emitter to use
  57147. * @returns the cloned particle system
  57148. */
  57149. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57150. var custom = null;
  57151. var program = null;
  57152. if (this.customShader != null) {
  57153. program = this.customShader;
  57154. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57155. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57156. }
  57157. else if (this._customEffect) {
  57158. custom = this._customEffect;
  57159. }
  57160. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57161. result.customShader = program;
  57162. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57163. if (newEmitter === undefined) {
  57164. newEmitter = this.emitter;
  57165. }
  57166. result.emitter = newEmitter;
  57167. if (this.particleTexture) {
  57168. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57169. }
  57170. if (!this.preventAutoStart) {
  57171. result.start();
  57172. }
  57173. return result;
  57174. };
  57175. /**
  57176. * Serializes the particle system to a JSON object.
  57177. * @returns the JSON object
  57178. */
  57179. ParticleSystem.prototype.serialize = function () {
  57180. var serializationObject = {};
  57181. ParticleSystem._Serialize(serializationObject, this);
  57182. serializationObject.textureMask = this.textureMask.asArray();
  57183. serializationObject.customShader = this.customShader;
  57184. serializationObject.preventAutoStart = this.preventAutoStart;
  57185. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57186. return serializationObject;
  57187. };
  57188. /** @hidden */
  57189. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57190. serializationObject.name = particleSystem.name;
  57191. serializationObject.id = particleSystem.id;
  57192. serializationObject.capacity = particleSystem.getCapacity();
  57193. // Emitter
  57194. if (particleSystem.emitter.position) {
  57195. var emitterMesh = particleSystem.emitter;
  57196. serializationObject.emitterId = emitterMesh.id;
  57197. }
  57198. else {
  57199. var emitterPosition = particleSystem.emitter;
  57200. serializationObject.emitter = emitterPosition.asArray();
  57201. }
  57202. // Emitter
  57203. if (particleSystem.particleEmitterType) {
  57204. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57205. }
  57206. if (particleSystem.particleTexture) {
  57207. serializationObject.textureName = particleSystem.particleTexture.name;
  57208. }
  57209. // Animations
  57210. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57211. // Particle system
  57212. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57213. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57214. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57215. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57216. serializationObject.minSize = particleSystem.minSize;
  57217. serializationObject.maxSize = particleSystem.maxSize;
  57218. serializationObject.minScaleX = particleSystem.minScaleX;
  57219. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57220. serializationObject.minScaleY = particleSystem.minScaleY;
  57221. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57222. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57223. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57224. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57225. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57226. serializationObject.emitRate = particleSystem.emitRate;
  57227. serializationObject.gravity = particleSystem.gravity.asArray();
  57228. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57229. serializationObject.color1 = particleSystem.color1.asArray();
  57230. serializationObject.color2 = particleSystem.color2.asArray();
  57231. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57232. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57233. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57234. serializationObject.blendMode = particleSystem.blendMode;
  57235. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57236. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57237. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57238. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57239. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57240. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57241. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57242. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57243. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57244. var colorGradients = particleSystem.getColorGradients();
  57245. if (colorGradients) {
  57246. serializationObject.colorGradients = [];
  57247. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57248. var colorGradient = colorGradients_1[_i];
  57249. var serializedGradient = {
  57250. gradient: colorGradient.gradient,
  57251. color1: colorGradient.color1.asArray()
  57252. };
  57253. if (colorGradient.color2) {
  57254. serializedGradient.color2 = colorGradient.color2.asArray();
  57255. }
  57256. serializationObject.colorGradients.push(serializedGradient);
  57257. }
  57258. }
  57259. var sizeGradients = particleSystem.getSizeGradients();
  57260. if (sizeGradients) {
  57261. serializationObject.sizeGradients = [];
  57262. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  57263. var sizeGradient = sizeGradients_1[_a];
  57264. var serializedGradient = {
  57265. gradient: sizeGradient.gradient,
  57266. factor1: sizeGradient.factor1
  57267. };
  57268. if (sizeGradient.factor2 !== undefined) {
  57269. serializedGradient.factor2 = sizeGradient.factor2;
  57270. }
  57271. serializationObject.sizeGradients.push(serializedGradient);
  57272. }
  57273. }
  57274. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57275. if (angularSpeedGradients) {
  57276. serializationObject.angularSpeedGradients = [];
  57277. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  57278. var angularSpeedGradient = angularSpeedGradients_1[_b];
  57279. var serializedGradient = {
  57280. gradient: angularSpeedGradient.gradient,
  57281. factor1: angularSpeedGradient.factor1
  57282. };
  57283. if (angularSpeedGradient.factor2 !== undefined) {
  57284. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57285. }
  57286. serializationObject.angularSpeedGradients.push(serializedGradient);
  57287. }
  57288. }
  57289. var velocityGradients = particleSystem.getVelocityGradients();
  57290. if (velocityGradients) {
  57291. serializationObject.velocityGradients = [];
  57292. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  57293. var velocityGradient = velocityGradients_1[_c];
  57294. var serializedGradient = {
  57295. gradient: velocityGradient.gradient,
  57296. factor1: velocityGradient.factor1
  57297. };
  57298. if (velocityGradient.factor2 !== undefined) {
  57299. serializedGradient.factor2 = velocityGradient.factor2;
  57300. }
  57301. serializationObject.velocityGradients.push(serializedGradient);
  57302. }
  57303. }
  57304. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57305. if (limitVelocityGradients) {
  57306. serializationObject.limitVelocityGradients = [];
  57307. for (var _d = 0, limitVelocityGradients_1 = limitVelocityGradients; _d < limitVelocityGradients_1.length; _d++) {
  57308. var limitVelocityGradient = limitVelocityGradients_1[_d];
  57309. var serializedGradient = {
  57310. gradient: limitVelocityGradient.gradient,
  57311. factor1: limitVelocityGradient.factor1
  57312. };
  57313. if (limitVelocityGradient.factor2 !== undefined) {
  57314. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57315. }
  57316. serializationObject.limitVelocityGradients.push(serializedGradient);
  57317. }
  57318. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57319. }
  57320. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  57321. var noiseTexture = particleSystem.noiseTexture;
  57322. serializationObject.noiseTexture = noiseTexture.serialize();
  57323. }
  57324. };
  57325. /** @hidden */
  57326. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57327. // Texture
  57328. if (parsedParticleSystem.textureName) {
  57329. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57330. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57331. }
  57332. // Emitter
  57333. if (parsedParticleSystem.emitterId === undefined) {
  57334. particleSystem.emitter = BABYLON.Vector3.Zero();
  57335. }
  57336. else if (parsedParticleSystem.emitterId) {
  57337. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57338. }
  57339. else {
  57340. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57341. }
  57342. // Misc.
  57343. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57344. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57345. }
  57346. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57347. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57348. }
  57349. // Animations
  57350. if (parsedParticleSystem.animations) {
  57351. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57352. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57353. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57354. }
  57355. }
  57356. if (parsedParticleSystem.autoAnimate) {
  57357. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57358. }
  57359. // Particle system
  57360. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57361. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57362. particleSystem.minSize = parsedParticleSystem.minSize;
  57363. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57364. if (parsedParticleSystem.minScaleX) {
  57365. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57366. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57367. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57368. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57369. }
  57370. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57371. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57372. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57373. }
  57374. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57375. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57376. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57377. }
  57378. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57379. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57380. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57381. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57382. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57383. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57384. if (parsedParticleSystem.noiseStrength) {
  57385. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57386. }
  57387. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57388. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57389. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57390. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57391. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57392. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57393. if (parsedParticleSystem.colorGradients) {
  57394. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57395. var colorGradient = _a[_i];
  57396. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57397. }
  57398. }
  57399. if (parsedParticleSystem.sizeGradients) {
  57400. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  57401. var sizeGradient = _c[_b];
  57402. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57403. }
  57404. }
  57405. if (parsedParticleSystem.angularSpeedGradients) {
  57406. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  57407. var angularSpeedGradient = _e[_d];
  57408. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  57409. }
  57410. }
  57411. if (parsedParticleSystem.velocityGradients) {
  57412. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  57413. var velocityGradient = _g[_f];
  57414. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  57415. }
  57416. }
  57417. if (parsedParticleSystem.limitVelocityGradients) {
  57418. for (var _h = 0, _j = parsedParticleSystem.limitVelocityGradients; _h < _j.length; _h++) {
  57419. var limitVelocityGradient = _j[_h];
  57420. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  57421. }
  57422. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  57423. }
  57424. if (parsedParticleSystem.noiseTexture) {
  57425. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  57426. }
  57427. // Emitter
  57428. var emitterType;
  57429. if (parsedParticleSystem.particleEmitterType) {
  57430. switch (parsedParticleSystem.particleEmitterType.type) {
  57431. case "SphereParticleEmitter":
  57432. emitterType = new BABYLON.SphereParticleEmitter();
  57433. break;
  57434. case "SphereDirectedParticleEmitter":
  57435. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57436. break;
  57437. case "ConeEmitter":
  57438. case "ConeParticleEmitter":
  57439. emitterType = new BABYLON.ConeParticleEmitter();
  57440. break;
  57441. case "BoxEmitter":
  57442. case "BoxParticleEmitter":
  57443. default:
  57444. emitterType = new BABYLON.BoxParticleEmitter();
  57445. break;
  57446. }
  57447. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57448. }
  57449. else {
  57450. emitterType = new BABYLON.BoxParticleEmitter();
  57451. emitterType.parse(parsedParticleSystem);
  57452. }
  57453. particleSystem.particleEmitterType = emitterType;
  57454. // Animation sheet
  57455. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57456. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57457. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57458. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57459. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57460. };
  57461. /**
  57462. * Parses a JSON object to create a particle system.
  57463. * @param parsedParticleSystem The JSON object to parse
  57464. * @param scene The scene to create the particle system in
  57465. * @param rootUrl The root url to use to load external dependencies like texture
  57466. * @returns the Parsed particle system
  57467. */
  57468. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57469. var name = parsedParticleSystem.name;
  57470. var custom = null;
  57471. var program = null;
  57472. if (parsedParticleSystem.customShader) {
  57473. program = parsedParticleSystem.customShader;
  57474. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57475. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57476. }
  57477. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57478. particleSystem.customShader = program;
  57479. if (parsedParticleSystem.id) {
  57480. particleSystem.id = parsedParticleSystem.id;
  57481. }
  57482. // Auto start
  57483. if (parsedParticleSystem.preventAutoStart) {
  57484. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57485. }
  57486. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57487. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57488. if (!particleSystem.preventAutoStart) {
  57489. particleSystem.start();
  57490. }
  57491. return particleSystem;
  57492. };
  57493. return ParticleSystem;
  57494. }(BABYLON.BaseParticleSystem));
  57495. BABYLON.ParticleSystem = ParticleSystem;
  57496. })(BABYLON || (BABYLON = {}));
  57497. //# sourceMappingURL=babylon.particleSystem.js.map
  57498. var BABYLON;
  57499. (function (BABYLON) {
  57500. /**
  57501. * Particle emitter emitting particles from the inside of a box.
  57502. * It emits the particles randomly between 2 given directions.
  57503. */
  57504. var BoxParticleEmitter = /** @class */ (function () {
  57505. /**
  57506. * Creates a new instance BoxParticleEmitter
  57507. */
  57508. function BoxParticleEmitter() {
  57509. /**
  57510. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57511. */
  57512. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57513. /**
  57514. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57515. */
  57516. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57517. /**
  57518. * 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.
  57519. */
  57520. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57521. /**
  57522. * 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.
  57523. */
  57524. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57525. }
  57526. /**
  57527. * Called by the particle System when the direction is computed for the created particle.
  57528. * @param worldMatrix is the world matrix of the particle system
  57529. * @param directionToUpdate is the direction vector to update with the result
  57530. * @param particle is the particle we are computed the direction for
  57531. */
  57532. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57533. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57534. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57535. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57536. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57537. };
  57538. /**
  57539. * Called by the particle System when the position is computed for the created particle.
  57540. * @param worldMatrix is the world matrix of the particle system
  57541. * @param positionToUpdate is the position vector to update with the result
  57542. * @param particle is the particle we are computed the position for
  57543. */
  57544. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57545. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57546. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57547. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57548. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57549. };
  57550. /**
  57551. * Clones the current emitter and returns a copy of it
  57552. * @returns the new emitter
  57553. */
  57554. BoxParticleEmitter.prototype.clone = function () {
  57555. var newOne = new BoxParticleEmitter();
  57556. BABYLON.Tools.DeepCopy(this, newOne);
  57557. return newOne;
  57558. };
  57559. /**
  57560. * Called by the GPUParticleSystem to setup the update shader
  57561. * @param effect defines the update shader
  57562. */
  57563. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57564. effect.setVector3("direction1", this.direction1);
  57565. effect.setVector3("direction2", this.direction2);
  57566. effect.setVector3("minEmitBox", this.minEmitBox);
  57567. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57568. };
  57569. /**
  57570. * Returns a string to use to update the GPU particles update shader
  57571. * @returns a string containng the defines string
  57572. */
  57573. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57574. return "#define BOXEMITTER";
  57575. };
  57576. /**
  57577. * Returns the string "BoxParticleEmitter"
  57578. * @returns a string containing the class name
  57579. */
  57580. BoxParticleEmitter.prototype.getClassName = function () {
  57581. return "BoxParticleEmitter";
  57582. };
  57583. /**
  57584. * Serializes the particle system to a JSON object.
  57585. * @returns the JSON object
  57586. */
  57587. BoxParticleEmitter.prototype.serialize = function () {
  57588. var serializationObject = {};
  57589. serializationObject.type = this.getClassName();
  57590. serializationObject.direction1 = this.direction1.asArray();
  57591. serializationObject.direction2 = this.direction2.asArray();
  57592. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57593. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57594. return serializationObject;
  57595. };
  57596. /**
  57597. * Parse properties from a JSON object
  57598. * @param serializationObject defines the JSON object
  57599. */
  57600. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57601. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57602. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57603. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  57604. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  57605. };
  57606. return BoxParticleEmitter;
  57607. }());
  57608. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57609. })(BABYLON || (BABYLON = {}));
  57610. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57611. var BABYLON;
  57612. (function (BABYLON) {
  57613. /**
  57614. * Particle emitter emitting particles from the inside of a cylinder.
  57615. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  57616. */
  57617. var CylinderParticleEmitter = /** @class */ (function () {
  57618. /**
  57619. * Creates a new instance CylinderParticleEmitter
  57620. * @param radius the radius of the emission cylinder (1 by default)
  57621. * @param height the height of the emission cylinder (1 by default)
  57622. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57623. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57624. */
  57625. function CylinderParticleEmitter(
  57626. /**
  57627. * The radius of the emission cylinder.
  57628. */
  57629. radius,
  57630. /**
  57631. * The height of the emission cylinder.
  57632. */
  57633. height,
  57634. /**
  57635. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57636. */
  57637. radiusRange,
  57638. /**
  57639. * How much to randomize the particle direction [0-1].
  57640. */
  57641. directionRandomizer) {
  57642. if (radius === void 0) { radius = 1; }
  57643. if (height === void 0) { height = 1; }
  57644. if (radiusRange === void 0) { radiusRange = 1; }
  57645. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57646. this.radius = radius;
  57647. this.height = height;
  57648. this.radiusRange = radiusRange;
  57649. this.directionRandomizer = directionRandomizer;
  57650. }
  57651. /**
  57652. * Called by the particle System when the direction is computed for the created particle.
  57653. * @param worldMatrix is the world matrix of the particle system
  57654. * @param directionToUpdate is the direction vector to update with the result
  57655. * @param particle is the particle we are computed the direction for
  57656. */
  57657. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57658. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57659. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  57660. var angle = Math.atan2(direction.x, direction.z);
  57661. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  57662. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  57663. direction.x = Math.sin(angle);
  57664. direction.z = Math.cos(angle);
  57665. direction.normalize();
  57666. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57667. };
  57668. /**
  57669. * Called by the particle System when the position is computed for the created particle.
  57670. * @param worldMatrix is the world matrix of the particle system
  57671. * @param positionToUpdate is the position vector to update with the result
  57672. * @param particle is the particle we are computed the position for
  57673. */
  57674. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57675. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  57676. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57677. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  57678. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  57679. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  57680. var xPos = positionRadius * Math.cos(angle);
  57681. var zPos = positionRadius * Math.sin(angle);
  57682. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  57683. };
  57684. /**
  57685. * Clones the current emitter and returns a copy of it
  57686. * @returns the new emitter
  57687. */
  57688. CylinderParticleEmitter.prototype.clone = function () {
  57689. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  57690. BABYLON.Tools.DeepCopy(this, newOne);
  57691. return newOne;
  57692. };
  57693. /**
  57694. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57695. * @param effect defines the update shader
  57696. */
  57697. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  57698. effect.setFloat("radius", this.radius);
  57699. effect.setFloat("height", this.height);
  57700. effect.setFloat("radiusRange", this.radiusRange);
  57701. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57702. };
  57703. /**
  57704. * Returns a string to use to update the GPU particles update shader
  57705. * @returns a string containng the defines string
  57706. */
  57707. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  57708. return "#define CYLINDEREMITTER";
  57709. };
  57710. /**
  57711. * Returns the string "CylinderParticleEmitter"
  57712. * @returns a string containing the class name
  57713. */
  57714. CylinderParticleEmitter.prototype.getClassName = function () {
  57715. return "CylinderParticleEmitter";
  57716. };
  57717. /**
  57718. * Serializes the particle system to a JSON object.
  57719. * @returns the JSON object
  57720. */
  57721. CylinderParticleEmitter.prototype.serialize = function () {
  57722. var serializationObject = {};
  57723. serializationObject.type = this.getClassName();
  57724. serializationObject.radius = this.radius;
  57725. serializationObject.height = this.height;
  57726. serializationObject.radiusRange = this.radiusRange;
  57727. serializationObject.directionRandomizer = this.directionRandomizer;
  57728. return serializationObject;
  57729. };
  57730. /**
  57731. * Parse properties from a JSON object
  57732. * @param serializationObject defines the JSON object
  57733. */
  57734. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  57735. this.radius = serializationObject.radius;
  57736. this.height = serializationObject.height;
  57737. this.radiusRange = serializationObject.radiusRange;
  57738. this.directionRandomizer = serializationObject.directionRandomizer;
  57739. };
  57740. return CylinderParticleEmitter;
  57741. }());
  57742. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  57743. })(BABYLON || (BABYLON = {}));
  57744. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  57745. var BABYLON;
  57746. (function (BABYLON) {
  57747. /**
  57748. * Particle emitter emitting particles from the inside of a cone.
  57749. * It emits the particles alongside the cone volume from the base to the particle.
  57750. * The emission direction might be randomized.
  57751. */
  57752. var ConeParticleEmitter = /** @class */ (function () {
  57753. /**
  57754. * Creates a new instance ConeParticleEmitter
  57755. * @param radius the radius of the emission cone (1 by default)
  57756. * @param angles the cone base angle (PI by default)
  57757. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  57758. */
  57759. function ConeParticleEmitter(radius, angle,
  57760. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  57761. directionRandomizer) {
  57762. if (radius === void 0) { radius = 1; }
  57763. if (angle === void 0) { angle = Math.PI; }
  57764. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57765. this.directionRandomizer = directionRandomizer;
  57766. /**
  57767. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  57768. */
  57769. this.radiusRange = 1;
  57770. /**
  57771. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  57772. */
  57773. this.heightRange = 1;
  57774. /**
  57775. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  57776. */
  57777. this.emitFromSpawnPointOnly = false;
  57778. this.angle = angle;
  57779. this.radius = radius;
  57780. }
  57781. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57782. /**
  57783. * Gets or sets the radius of the emission cone
  57784. */
  57785. get: function () {
  57786. return this._radius;
  57787. },
  57788. set: function (value) {
  57789. this._radius = value;
  57790. this._buildHeight();
  57791. },
  57792. enumerable: true,
  57793. configurable: true
  57794. });
  57795. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  57796. /**
  57797. * Gets or sets the angle of the emission cone
  57798. */
  57799. get: function () {
  57800. return this._angle;
  57801. },
  57802. set: function (value) {
  57803. this._angle = value;
  57804. this._buildHeight();
  57805. },
  57806. enumerable: true,
  57807. configurable: true
  57808. });
  57809. ConeParticleEmitter.prototype._buildHeight = function () {
  57810. if (this._angle !== 0) {
  57811. this._height = this._radius / Math.tan(this._angle / 2);
  57812. }
  57813. else {
  57814. this._height = 1;
  57815. }
  57816. };
  57817. /**
  57818. * Called by the particle System when the direction is computed for the created particle.
  57819. * @param worldMatrix is the world matrix of the particle system
  57820. * @param directionToUpdate is the direction vector to update with the result
  57821. * @param particle is the particle we are computed the direction for
  57822. */
  57823. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57824. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  57825. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  57826. }
  57827. else {
  57828. // measure the direction Vector from the emitter to the particle.
  57829. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57830. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57831. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57832. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57833. direction.x += randX;
  57834. direction.y += randY;
  57835. direction.z += randZ;
  57836. direction.normalize();
  57837. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57838. }
  57839. };
  57840. /**
  57841. * Called by the particle System when the position is computed for the created particle.
  57842. * @param worldMatrix is the world matrix of the particle system
  57843. * @param positionToUpdate is the position vector to update with the result
  57844. * @param particle is the particle we are computed the position for
  57845. */
  57846. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57847. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57848. var h;
  57849. if (!this.emitFromSpawnPointOnly) {
  57850. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  57851. // Better distribution in a cone at normal angles.
  57852. h = 1 - h * h;
  57853. }
  57854. else {
  57855. h = 0.0001;
  57856. }
  57857. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  57858. radius = radius * h;
  57859. var randX = radius * Math.sin(s);
  57860. var randZ = radius * Math.cos(s);
  57861. var randY = h * this._height;
  57862. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57863. };
  57864. /**
  57865. * Clones the current emitter and returns a copy of it
  57866. * @returns the new emitter
  57867. */
  57868. ConeParticleEmitter.prototype.clone = function () {
  57869. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  57870. BABYLON.Tools.DeepCopy(this, newOne);
  57871. return newOne;
  57872. };
  57873. /**
  57874. * Called by the GPUParticleSystem to setup the update shader
  57875. * @param effect defines the update shader
  57876. */
  57877. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57878. effect.setFloat2("radius", this._radius, this.radiusRange);
  57879. effect.setFloat("coneAngle", this._angle);
  57880. effect.setFloat2("height", this._height, this.heightRange);
  57881. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57882. };
  57883. /**
  57884. * Returns a string to use to update the GPU particles update shader
  57885. * @returns a string containng the defines string
  57886. */
  57887. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57888. var defines = "#define CONEEMITTER";
  57889. if (this.emitFromSpawnPointOnly) {
  57890. defines += "\n#define CONEEMITTERSPAWNPOINT";
  57891. }
  57892. return defines;
  57893. };
  57894. /**
  57895. * Returns the string "ConeParticleEmitter"
  57896. * @returns a string containing the class name
  57897. */
  57898. ConeParticleEmitter.prototype.getClassName = function () {
  57899. return "ConeParticleEmitter";
  57900. };
  57901. /**
  57902. * Serializes the particle system to a JSON object.
  57903. * @returns the JSON object
  57904. */
  57905. ConeParticleEmitter.prototype.serialize = function () {
  57906. var serializationObject = {};
  57907. serializationObject.type = this.getClassName();
  57908. serializationObject.radius = this._radius;
  57909. serializationObject.angle = this._angle;
  57910. serializationObject.directionRandomizer = this.directionRandomizer;
  57911. return serializationObject;
  57912. };
  57913. /**
  57914. * Parse properties from a JSON object
  57915. * @param serializationObject defines the JSON object
  57916. */
  57917. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57918. this.radius = serializationObject.radius;
  57919. this.angle = serializationObject.angle;
  57920. this.directionRandomizer = serializationObject.directionRandomizer;
  57921. };
  57922. return ConeParticleEmitter;
  57923. }());
  57924. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57925. })(BABYLON || (BABYLON = {}));
  57926. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57927. var BABYLON;
  57928. (function (BABYLON) {
  57929. /**
  57930. * Particle emitter emitting particles from the inside of a sphere.
  57931. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57932. */
  57933. var SphereParticleEmitter = /** @class */ (function () {
  57934. /**
  57935. * Creates a new instance SphereParticleEmitter
  57936. * @param radius the radius of the emission sphere (1 by default)
  57937. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57938. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57939. */
  57940. function SphereParticleEmitter(
  57941. /**
  57942. * The radius of the emission sphere.
  57943. */
  57944. radius,
  57945. /**
  57946. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57947. */
  57948. radiusRange,
  57949. /**
  57950. * How much to randomize the particle direction [0-1].
  57951. */
  57952. directionRandomizer) {
  57953. if (radius === void 0) { radius = 1; }
  57954. if (radiusRange === void 0) { radiusRange = 1; }
  57955. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57956. this.radius = radius;
  57957. this.radiusRange = radiusRange;
  57958. this.directionRandomizer = directionRandomizer;
  57959. }
  57960. /**
  57961. * Called by the particle System when the direction is computed for the created particle.
  57962. * @param worldMatrix is the world matrix of the particle system
  57963. * @param directionToUpdate is the direction vector to update with the result
  57964. * @param particle is the particle we are computed the direction for
  57965. */
  57966. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57967. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57968. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57969. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57970. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57971. direction.x += randX;
  57972. direction.y += randY;
  57973. direction.z += randZ;
  57974. direction.normalize();
  57975. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57976. };
  57977. /**
  57978. * Called by the particle System when the position is computed for the created particle.
  57979. * @param worldMatrix is the world matrix of the particle system
  57980. * @param positionToUpdate is the position vector to update with the result
  57981. * @param particle is the particle we are computed the position for
  57982. */
  57983. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57984. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  57985. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  57986. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57987. var theta = Math.acos(2 * v - 1);
  57988. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57989. var randY = randRadius * Math.cos(theta);
  57990. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57991. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57992. };
  57993. /**
  57994. * Clones the current emitter and returns a copy of it
  57995. * @returns the new emitter
  57996. */
  57997. SphereParticleEmitter.prototype.clone = function () {
  57998. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57999. BABYLON.Tools.DeepCopy(this, newOne);
  58000. return newOne;
  58001. };
  58002. /**
  58003. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58004. * @param effect defines the update shader
  58005. */
  58006. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58007. effect.setFloat("radius", this.radius);
  58008. effect.setFloat("radiusRange", this.radiusRange);
  58009. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58010. };
  58011. /**
  58012. * Returns a string to use to update the GPU particles update shader
  58013. * @returns a string containng the defines string
  58014. */
  58015. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58016. return "#define SPHEREEMITTER";
  58017. };
  58018. /**
  58019. * Returns the string "SphereParticleEmitter"
  58020. * @returns a string containing the class name
  58021. */
  58022. SphereParticleEmitter.prototype.getClassName = function () {
  58023. return "SphereParticleEmitter";
  58024. };
  58025. /**
  58026. * Serializes the particle system to a JSON object.
  58027. * @returns the JSON object
  58028. */
  58029. SphereParticleEmitter.prototype.serialize = function () {
  58030. var serializationObject = {};
  58031. serializationObject.type = this.getClassName();
  58032. serializationObject.radius = this.radius;
  58033. serializationObject.radiusRange = this.radiusRange;
  58034. serializationObject.directionRandomizer = this.directionRandomizer;
  58035. return serializationObject;
  58036. };
  58037. /**
  58038. * Parse properties from a JSON object
  58039. * @param serializationObject defines the JSON object
  58040. */
  58041. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58042. this.radius = serializationObject.radius;
  58043. this.radiusRange = serializationObject.radiusRange;
  58044. this.directionRandomizer = serializationObject.directionRandomizer;
  58045. };
  58046. return SphereParticleEmitter;
  58047. }());
  58048. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58049. /**
  58050. * Particle emitter emitting particles from the inside of a sphere.
  58051. * It emits the particles randomly between two vectors.
  58052. */
  58053. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58054. __extends(SphereDirectedParticleEmitter, _super);
  58055. /**
  58056. * Creates a new instance SphereDirectedParticleEmitter
  58057. * @param radius the radius of the emission sphere (1 by default)
  58058. * @param direction1 the min limit of the emission direction (up vector by default)
  58059. * @param direction2 the max limit of the emission direction (up vector by default)
  58060. */
  58061. function SphereDirectedParticleEmitter(radius,
  58062. /**
  58063. * The min limit of the emission direction.
  58064. */
  58065. direction1,
  58066. /**
  58067. * The max limit of the emission direction.
  58068. */
  58069. direction2) {
  58070. if (radius === void 0) { radius = 1; }
  58071. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58072. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58073. var _this = _super.call(this, radius) || this;
  58074. _this.direction1 = direction1;
  58075. _this.direction2 = direction2;
  58076. return _this;
  58077. }
  58078. /**
  58079. * Called by the particle System when the direction is computed for the created particle.
  58080. * @param worldMatrix is the world matrix of the particle system
  58081. * @param directionToUpdate is the direction vector to update with the result
  58082. * @param particle is the particle we are computed the direction for
  58083. */
  58084. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58085. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58086. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58087. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58088. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58089. };
  58090. /**
  58091. * Clones the current emitter and returns a copy of it
  58092. * @returns the new emitter
  58093. */
  58094. SphereDirectedParticleEmitter.prototype.clone = function () {
  58095. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58096. BABYLON.Tools.DeepCopy(this, newOne);
  58097. return newOne;
  58098. };
  58099. /**
  58100. * Called by the GPUParticleSystem to setup the update shader
  58101. * @param effect defines the update shader
  58102. */
  58103. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58104. effect.setFloat("radius", this.radius);
  58105. effect.setFloat("radiusRange", this.radiusRange);
  58106. effect.setVector3("direction1", this.direction1);
  58107. effect.setVector3("direction2", this.direction2);
  58108. };
  58109. /**
  58110. * Returns a string to use to update the GPU particles update shader
  58111. * @returns a string containng the defines string
  58112. */
  58113. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58114. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58115. };
  58116. /**
  58117. * Returns the string "SphereDirectedParticleEmitter"
  58118. * @returns a string containing the class name
  58119. */
  58120. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58121. return "SphereDirectedParticleEmitter";
  58122. };
  58123. /**
  58124. * Serializes the particle system to a JSON object.
  58125. * @returns the JSON object
  58126. */
  58127. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58128. var serializationObject = _super.prototype.serialize.call(this);
  58129. serializationObject.direction1 = this.direction1.asArray();
  58130. serializationObject.direction2 = this.direction2.asArray();
  58131. return serializationObject;
  58132. };
  58133. /**
  58134. * Parse properties from a JSON object
  58135. * @param serializationObject defines the JSON object
  58136. */
  58137. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58138. _super.prototype.parse.call(this, serializationObject);
  58139. this.direction1.copyFrom(serializationObject.direction1);
  58140. this.direction2.copyFrom(serializationObject.direction2);
  58141. };
  58142. return SphereDirectedParticleEmitter;
  58143. }(SphereParticleEmitter));
  58144. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58145. })(BABYLON || (BABYLON = {}));
  58146. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58147. var BABYLON;
  58148. (function (BABYLON) {
  58149. /**
  58150. * Particle emitter emitting particles from the inside of a hemisphere.
  58151. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58152. */
  58153. var HemisphericParticleEmitter = /** @class */ (function () {
  58154. /**
  58155. * Creates a new instance HemisphericParticleEmitter
  58156. * @param radius the radius of the emission hemisphere (1 by default)
  58157. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58158. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58159. */
  58160. function HemisphericParticleEmitter(
  58161. /**
  58162. * The radius of the emission hemisphere.
  58163. */
  58164. radius,
  58165. /**
  58166. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58167. */
  58168. radiusRange,
  58169. /**
  58170. * How much to randomize the particle direction [0-1].
  58171. */
  58172. directionRandomizer) {
  58173. if (radius === void 0) { radius = 1; }
  58174. if (radiusRange === void 0) { radiusRange = 1; }
  58175. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58176. this.radius = radius;
  58177. this.radiusRange = radiusRange;
  58178. this.directionRandomizer = directionRandomizer;
  58179. }
  58180. /**
  58181. * Called by the particle System when the direction is computed for the created particle.
  58182. * @param worldMatrix is the world matrix of the particle system
  58183. * @param directionToUpdate is the direction vector to update with the result
  58184. * @param particle is the particle we are computed the direction for
  58185. */
  58186. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58187. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58188. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58189. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58190. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58191. direction.x += randX;
  58192. direction.y += randY;
  58193. direction.z += randZ;
  58194. direction.normalize();
  58195. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58196. };
  58197. /**
  58198. * Called by the particle System when the position is computed for the created particle.
  58199. * @param worldMatrix is the world matrix of the particle system
  58200. * @param positionToUpdate is the position vector to update with the result
  58201. * @param particle is the particle we are computed the position for
  58202. */
  58203. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58204. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58205. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58206. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58207. var theta = Math.acos(2 * v - 1);
  58208. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58209. var randY = randRadius * Math.cos(theta);
  58210. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58211. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58212. };
  58213. /**
  58214. * Clones the current emitter and returns a copy of it
  58215. * @returns the new emitter
  58216. */
  58217. HemisphericParticleEmitter.prototype.clone = function () {
  58218. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58219. BABYLON.Tools.DeepCopy(this, newOne);
  58220. return newOne;
  58221. };
  58222. /**
  58223. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58224. * @param effect defines the update shader
  58225. */
  58226. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  58227. effect.setFloat("radius", this.radius);
  58228. effect.setFloat("radiusRange", this.radiusRange);
  58229. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58230. };
  58231. /**
  58232. * Returns a string to use to update the GPU particles update shader
  58233. * @returns a string containng the defines string
  58234. */
  58235. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  58236. return "#define HEMISPHERICEMITTER";
  58237. };
  58238. /**
  58239. * Returns the string "HemisphericParticleEmitter"
  58240. * @returns a string containing the class name
  58241. */
  58242. HemisphericParticleEmitter.prototype.getClassName = function () {
  58243. return "HemisphericParticleEmitter";
  58244. };
  58245. /**
  58246. * Serializes the particle system to a JSON object.
  58247. * @returns the JSON object
  58248. */
  58249. HemisphericParticleEmitter.prototype.serialize = function () {
  58250. var serializationObject = {};
  58251. serializationObject.type = this.getClassName();
  58252. serializationObject.radius = this.radius;
  58253. serializationObject.radiusRange = this.radiusRange;
  58254. serializationObject.directionRandomizer = this.directionRandomizer;
  58255. return serializationObject;
  58256. };
  58257. /**
  58258. * Parse properties from a JSON object
  58259. * @param serializationObject defines the JSON object
  58260. */
  58261. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  58262. this.radius = serializationObject.radius;
  58263. this.radiusRange = serializationObject.radiusRange;
  58264. this.directionRandomizer = serializationObject.directionRandomizer;
  58265. };
  58266. return HemisphericParticleEmitter;
  58267. }());
  58268. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  58269. })(BABYLON || (BABYLON = {}));
  58270. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  58271. var BABYLON;
  58272. (function (BABYLON) {
  58273. /**
  58274. * Particle emitter emitting particles from a point.
  58275. * It emits the particles randomly between 2 given directions.
  58276. */
  58277. var PointParticleEmitter = /** @class */ (function () {
  58278. /**
  58279. * Creates a new instance PointParticleEmitter
  58280. */
  58281. function PointParticleEmitter() {
  58282. /**
  58283. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58284. */
  58285. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58286. /**
  58287. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58288. */
  58289. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58290. }
  58291. /**
  58292. * Called by the particle System when the direction is computed for the created particle.
  58293. * @param worldMatrix is the world matrix of the particle system
  58294. * @param directionToUpdate is the direction vector to update with the result
  58295. * @param particle is the particle we are computed the direction for
  58296. */
  58297. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58298. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58299. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58300. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58301. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58302. };
  58303. /**
  58304. * Called by the particle System when the position is computed for the created particle.
  58305. * @param worldMatrix is the world matrix of the particle system
  58306. * @param positionToUpdate is the position vector to update with the result
  58307. * @param particle is the particle we are computed the position for
  58308. */
  58309. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58310. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  58311. };
  58312. /**
  58313. * Clones the current emitter and returns a copy of it
  58314. * @returns the new emitter
  58315. */
  58316. PointParticleEmitter.prototype.clone = function () {
  58317. var newOne = new PointParticleEmitter();
  58318. BABYLON.Tools.DeepCopy(this, newOne);
  58319. return newOne;
  58320. };
  58321. /**
  58322. * Called by the GPUParticleSystem to setup the update shader
  58323. * @param effect defines the update shader
  58324. */
  58325. PointParticleEmitter.prototype.applyToShader = function (effect) {
  58326. effect.setVector3("direction1", this.direction1);
  58327. effect.setVector3("direction2", this.direction2);
  58328. };
  58329. /**
  58330. * Returns a string to use to update the GPU particles update shader
  58331. * @returns a string containng the defines string
  58332. */
  58333. PointParticleEmitter.prototype.getEffectDefines = function () {
  58334. return "#define POINTEMITTER";
  58335. };
  58336. /**
  58337. * Returns the string "PointParticleEmitter"
  58338. * @returns a string containing the class name
  58339. */
  58340. PointParticleEmitter.prototype.getClassName = function () {
  58341. return "PointParticleEmitter";
  58342. };
  58343. /**
  58344. * Serializes the particle system to a JSON object.
  58345. * @returns the JSON object
  58346. */
  58347. PointParticleEmitter.prototype.serialize = function () {
  58348. var serializationObject = {};
  58349. serializationObject.type = this.getClassName();
  58350. serializationObject.direction1 = this.direction1.asArray();
  58351. serializationObject.direction2 = this.direction2.asArray();
  58352. return serializationObject;
  58353. };
  58354. /**
  58355. * Parse properties from a JSON object
  58356. * @param serializationObject defines the JSON object
  58357. */
  58358. PointParticleEmitter.prototype.parse = function (serializationObject) {
  58359. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58360. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58361. };
  58362. return PointParticleEmitter;
  58363. }());
  58364. BABYLON.PointParticleEmitter = PointParticleEmitter;
  58365. })(BABYLON || (BABYLON = {}));
  58366. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  58367. var BABYLON;
  58368. (function (BABYLON) {
  58369. // Adds the parsers to the scene parsers.
  58370. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  58371. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  58372. if (!individualParser) {
  58373. return;
  58374. }
  58375. // Particles Systems
  58376. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58377. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58378. var parsedParticleSystem = parsedData.particleSystems[index];
  58379. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  58380. }
  58381. }
  58382. });
  58383. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  58384. if (parsedParticleSystem.activeParticleCount) {
  58385. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58386. return ps;
  58387. }
  58388. else {
  58389. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58390. return ps;
  58391. }
  58392. });
  58393. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  58394. if (uniformsNames === void 0) { uniformsNames = []; }
  58395. if (samplers === void 0) { samplers = []; }
  58396. if (defines === void 0) { defines = ""; }
  58397. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  58398. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  58399. if (defines.indexOf(" BILLBOARD") === -1) {
  58400. defines += "\n#define BILLBOARD\n";
  58401. }
  58402. if (samplers.indexOf("diffuseSampler") === -1) {
  58403. samplers.push("diffuseSampler");
  58404. }
  58405. return this.createEffect({
  58406. vertex: "particles",
  58407. fragmentElement: fragmentName
  58408. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  58409. };
  58410. })(BABYLON || (BABYLON = {}));
  58411. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  58412. var BABYLON;
  58413. (function (BABYLON) {
  58414. var ShaderMaterial = /** @class */ (function (_super) {
  58415. __extends(ShaderMaterial, _super);
  58416. function ShaderMaterial(name, scene, shaderPath, options) {
  58417. var _this = _super.call(this, name, scene) || this;
  58418. _this._textures = {};
  58419. _this._textureArrays = {};
  58420. _this._floats = {};
  58421. _this._ints = {};
  58422. _this._floatsArrays = {};
  58423. _this._colors3 = {};
  58424. _this._colors3Arrays = {};
  58425. _this._colors4 = {};
  58426. _this._vectors2 = {};
  58427. _this._vectors3 = {};
  58428. _this._vectors4 = {};
  58429. _this._matrices = {};
  58430. _this._matrices3x3 = {};
  58431. _this._matrices2x2 = {};
  58432. _this._vectors2Arrays = {};
  58433. _this._vectors3Arrays = {};
  58434. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58435. _this._shaderPath = shaderPath;
  58436. options.needAlphaBlending = options.needAlphaBlending || false;
  58437. options.needAlphaTesting = options.needAlphaTesting || false;
  58438. options.attributes = options.attributes || ["position", "normal", "uv"];
  58439. options.uniforms = options.uniforms || ["worldViewProjection"];
  58440. options.uniformBuffers = options.uniformBuffers || [];
  58441. options.samplers = options.samplers || [];
  58442. options.defines = options.defines || [];
  58443. _this._options = options;
  58444. return _this;
  58445. }
  58446. ShaderMaterial.prototype.getClassName = function () {
  58447. return "ShaderMaterial";
  58448. };
  58449. ShaderMaterial.prototype.needAlphaBlending = function () {
  58450. return this._options.needAlphaBlending;
  58451. };
  58452. ShaderMaterial.prototype.needAlphaTesting = function () {
  58453. return this._options.needAlphaTesting;
  58454. };
  58455. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58456. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58457. this._options.uniforms.push(uniformName);
  58458. }
  58459. };
  58460. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58461. if (this._options.samplers.indexOf(name) === -1) {
  58462. this._options.samplers.push(name);
  58463. }
  58464. this._textures[name] = texture;
  58465. return this;
  58466. };
  58467. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58468. if (this._options.samplers.indexOf(name) === -1) {
  58469. this._options.samplers.push(name);
  58470. }
  58471. this._checkUniform(name);
  58472. this._textureArrays[name] = textures;
  58473. return this;
  58474. };
  58475. ShaderMaterial.prototype.setFloat = function (name, value) {
  58476. this._checkUniform(name);
  58477. this._floats[name] = value;
  58478. return this;
  58479. };
  58480. ShaderMaterial.prototype.setInt = function (name, value) {
  58481. this._checkUniform(name);
  58482. this._ints[name] = value;
  58483. return this;
  58484. };
  58485. ShaderMaterial.prototype.setFloats = function (name, value) {
  58486. this._checkUniform(name);
  58487. this._floatsArrays[name] = value;
  58488. return this;
  58489. };
  58490. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58491. this._checkUniform(name);
  58492. this._colors3[name] = value;
  58493. return this;
  58494. };
  58495. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58496. this._checkUniform(name);
  58497. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58498. color.toArray(arr, arr.length);
  58499. return arr;
  58500. }, []);
  58501. return this;
  58502. };
  58503. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58504. this._checkUniform(name);
  58505. this._colors4[name] = value;
  58506. return this;
  58507. };
  58508. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58509. this._checkUniform(name);
  58510. this._vectors2[name] = value;
  58511. return this;
  58512. };
  58513. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58514. this._checkUniform(name);
  58515. this._vectors3[name] = value;
  58516. return this;
  58517. };
  58518. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58519. this._checkUniform(name);
  58520. this._vectors4[name] = value;
  58521. return this;
  58522. };
  58523. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58524. this._checkUniform(name);
  58525. this._matrices[name] = value;
  58526. return this;
  58527. };
  58528. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58529. this._checkUniform(name);
  58530. this._matrices3x3[name] = value;
  58531. return this;
  58532. };
  58533. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58534. this._checkUniform(name);
  58535. this._matrices2x2[name] = value;
  58536. return this;
  58537. };
  58538. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58539. this._checkUniform(name);
  58540. this._vectors2Arrays[name] = value;
  58541. return this;
  58542. };
  58543. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58544. this._checkUniform(name);
  58545. this._vectors3Arrays[name] = value;
  58546. return this;
  58547. };
  58548. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58549. if (!mesh) {
  58550. return true;
  58551. }
  58552. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58553. return false;
  58554. }
  58555. return false;
  58556. };
  58557. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58558. var scene = this.getScene();
  58559. var engine = scene.getEngine();
  58560. if (!this.checkReadyOnEveryCall) {
  58561. if (this._renderId === scene.getRenderId()) {
  58562. if (this._checkCache(scene, mesh, useInstances)) {
  58563. return true;
  58564. }
  58565. }
  58566. }
  58567. // Instances
  58568. var defines = [];
  58569. var attribs = [];
  58570. var fallbacks = new BABYLON.EffectFallbacks();
  58571. if (useInstances) {
  58572. defines.push("#define INSTANCES");
  58573. }
  58574. for (var index = 0; index < this._options.defines.length; index++) {
  58575. defines.push(this._options.defines[index]);
  58576. }
  58577. for (var index = 0; index < this._options.attributes.length; index++) {
  58578. attribs.push(this._options.attributes[index]);
  58579. }
  58580. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58581. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58582. defines.push("#define VERTEXCOLOR");
  58583. }
  58584. // Bones
  58585. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58586. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58587. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58588. if (mesh.numBoneInfluencers > 4) {
  58589. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58590. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58591. }
  58592. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58593. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58594. fallbacks.addCPUSkinningFallback(0, mesh);
  58595. if (this._options.uniforms.indexOf("mBones") === -1) {
  58596. this._options.uniforms.push("mBones");
  58597. }
  58598. }
  58599. else {
  58600. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58601. }
  58602. // Textures
  58603. for (var name in this._textures) {
  58604. if (!this._textures[name].isReady()) {
  58605. return false;
  58606. }
  58607. }
  58608. // Alpha test
  58609. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58610. defines.push("#define ALPHATEST");
  58611. }
  58612. var previousEffect = this._effect;
  58613. var join = defines.join("\n");
  58614. this._effect = engine.createEffect(this._shaderPath, {
  58615. attributes: attribs,
  58616. uniformsNames: this._options.uniforms,
  58617. uniformBuffersNames: this._options.uniformBuffers,
  58618. samplers: this._options.samplers,
  58619. defines: join,
  58620. fallbacks: fallbacks,
  58621. onCompiled: this.onCompiled,
  58622. onError: this.onError
  58623. }, engine);
  58624. if (!this._effect.isReady()) {
  58625. return false;
  58626. }
  58627. if (previousEffect !== this._effect) {
  58628. scene.resetCachedMaterial();
  58629. }
  58630. this._renderId = scene.getRenderId();
  58631. return true;
  58632. };
  58633. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58634. var scene = this.getScene();
  58635. if (!this._effect) {
  58636. return;
  58637. }
  58638. if (this._options.uniforms.indexOf("world") !== -1) {
  58639. this._effect.setMatrix("world", world);
  58640. }
  58641. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58642. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58643. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58644. }
  58645. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58646. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58647. }
  58648. };
  58649. ShaderMaterial.prototype.bind = function (world, mesh) {
  58650. // Std values
  58651. this.bindOnlyWorldMatrix(world);
  58652. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58653. if (this._options.uniforms.indexOf("view") !== -1) {
  58654. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58655. }
  58656. if (this._options.uniforms.indexOf("projection") !== -1) {
  58657. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58658. }
  58659. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58660. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58661. }
  58662. // Bones
  58663. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58664. var name;
  58665. // Texture
  58666. for (name in this._textures) {
  58667. this._effect.setTexture(name, this._textures[name]);
  58668. }
  58669. // Texture arrays
  58670. for (name in this._textureArrays) {
  58671. this._effect.setTextureArray(name, this._textureArrays[name]);
  58672. }
  58673. // Int
  58674. for (name in this._ints) {
  58675. this._effect.setInt(name, this._ints[name]);
  58676. }
  58677. // Float
  58678. for (name in this._floats) {
  58679. this._effect.setFloat(name, this._floats[name]);
  58680. }
  58681. // Floats
  58682. for (name in this._floatsArrays) {
  58683. this._effect.setArray(name, this._floatsArrays[name]);
  58684. }
  58685. // Color3
  58686. for (name in this._colors3) {
  58687. this._effect.setColor3(name, this._colors3[name]);
  58688. }
  58689. for (name in this._colors3Arrays) {
  58690. this._effect.setArray3(name, this._colors3Arrays[name]);
  58691. }
  58692. // Color4
  58693. for (name in this._colors4) {
  58694. var color = this._colors4[name];
  58695. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58696. }
  58697. // Vector2
  58698. for (name in this._vectors2) {
  58699. this._effect.setVector2(name, this._vectors2[name]);
  58700. }
  58701. // Vector3
  58702. for (name in this._vectors3) {
  58703. this._effect.setVector3(name, this._vectors3[name]);
  58704. }
  58705. // Vector4
  58706. for (name in this._vectors4) {
  58707. this._effect.setVector4(name, this._vectors4[name]);
  58708. }
  58709. // Matrix
  58710. for (name in this._matrices) {
  58711. this._effect.setMatrix(name, this._matrices[name]);
  58712. }
  58713. // Matrix 3x3
  58714. for (name in this._matrices3x3) {
  58715. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58716. }
  58717. // Matrix 2x2
  58718. for (name in this._matrices2x2) {
  58719. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58720. }
  58721. // Vector2Array
  58722. for (name in this._vectors2Arrays) {
  58723. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58724. }
  58725. // Vector3Array
  58726. for (name in this._vectors3Arrays) {
  58727. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58728. }
  58729. }
  58730. this._afterBind(mesh);
  58731. };
  58732. ShaderMaterial.prototype.getActiveTextures = function () {
  58733. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58734. for (var name in this._textures) {
  58735. activeTextures.push(this._textures[name]);
  58736. }
  58737. for (var name in this._textureArrays) {
  58738. var array = this._textureArrays[name];
  58739. for (var index = 0; index < array.length; index++) {
  58740. activeTextures.push(array[index]);
  58741. }
  58742. }
  58743. return activeTextures;
  58744. };
  58745. ShaderMaterial.prototype.hasTexture = function (texture) {
  58746. if (_super.prototype.hasTexture.call(this, texture)) {
  58747. return true;
  58748. }
  58749. for (var name in this._textures) {
  58750. if (this._textures[name] === texture) {
  58751. return true;
  58752. }
  58753. }
  58754. for (var name in this._textureArrays) {
  58755. var array = this._textureArrays[name];
  58756. for (var index = 0; index < array.length; index++) {
  58757. if (array[index] === texture) {
  58758. return true;
  58759. }
  58760. }
  58761. }
  58762. return false;
  58763. };
  58764. ShaderMaterial.prototype.clone = function (name) {
  58765. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58766. return newShaderMaterial;
  58767. };
  58768. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58769. if (forceDisposeTextures) {
  58770. var name;
  58771. for (name in this._textures) {
  58772. this._textures[name].dispose();
  58773. }
  58774. for (name in this._textureArrays) {
  58775. var array = this._textureArrays[name];
  58776. for (var index = 0; index < array.length; index++) {
  58777. array[index].dispose();
  58778. }
  58779. }
  58780. }
  58781. this._textures = {};
  58782. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58783. };
  58784. ShaderMaterial.prototype.serialize = function () {
  58785. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58786. serializationObject.customType = "BABYLON.ShaderMaterial";
  58787. serializationObject.options = this._options;
  58788. serializationObject.shaderPath = this._shaderPath;
  58789. var name;
  58790. // Texture
  58791. serializationObject.textures = {};
  58792. for (name in this._textures) {
  58793. serializationObject.textures[name] = this._textures[name].serialize();
  58794. }
  58795. // Texture arrays
  58796. serializationObject.textureArrays = {};
  58797. for (name in this._textureArrays) {
  58798. serializationObject.textureArrays[name] = [];
  58799. var array = this._textureArrays[name];
  58800. for (var index = 0; index < array.length; index++) {
  58801. serializationObject.textureArrays[name].push(array[index].serialize());
  58802. }
  58803. }
  58804. // Float
  58805. serializationObject.floats = {};
  58806. for (name in this._floats) {
  58807. serializationObject.floats[name] = this._floats[name];
  58808. }
  58809. // Float s
  58810. serializationObject.FloatArrays = {};
  58811. for (name in this._floatsArrays) {
  58812. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58813. }
  58814. // Color3
  58815. serializationObject.colors3 = {};
  58816. for (name in this._colors3) {
  58817. serializationObject.colors3[name] = this._colors3[name].asArray();
  58818. }
  58819. // Color3 array
  58820. serializationObject.colors3Arrays = {};
  58821. for (name in this._colors3Arrays) {
  58822. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58823. }
  58824. // Color4
  58825. serializationObject.colors4 = {};
  58826. for (name in this._colors4) {
  58827. serializationObject.colors4[name] = this._colors4[name].asArray();
  58828. }
  58829. // Vector2
  58830. serializationObject.vectors2 = {};
  58831. for (name in this._vectors2) {
  58832. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58833. }
  58834. // Vector3
  58835. serializationObject.vectors3 = {};
  58836. for (name in this._vectors3) {
  58837. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58838. }
  58839. // Vector4
  58840. serializationObject.vectors4 = {};
  58841. for (name in this._vectors4) {
  58842. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58843. }
  58844. // Matrix
  58845. serializationObject.matrices = {};
  58846. for (name in this._matrices) {
  58847. serializationObject.matrices[name] = this._matrices[name].asArray();
  58848. }
  58849. // Matrix 3x3
  58850. serializationObject.matrices3x3 = {};
  58851. for (name in this._matrices3x3) {
  58852. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58853. }
  58854. // Matrix 2x2
  58855. serializationObject.matrices2x2 = {};
  58856. for (name in this._matrices2x2) {
  58857. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58858. }
  58859. // Vector2Array
  58860. serializationObject.vectors2Arrays = {};
  58861. for (name in this._vectors2Arrays) {
  58862. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58863. }
  58864. // Vector3Array
  58865. serializationObject.vectors3Arrays = {};
  58866. for (name in this._vectors3Arrays) {
  58867. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58868. }
  58869. return serializationObject;
  58870. };
  58871. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58872. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58873. var name;
  58874. // Texture
  58875. for (name in source.textures) {
  58876. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58877. }
  58878. // Texture arrays
  58879. for (name in source.textureArrays) {
  58880. var array = source.textureArrays[name];
  58881. var textureArray = new Array();
  58882. for (var index = 0; index < array.length; index++) {
  58883. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58884. }
  58885. material.setTextureArray(name, textureArray);
  58886. }
  58887. // Float
  58888. for (name in source.floats) {
  58889. material.setFloat(name, source.floats[name]);
  58890. }
  58891. // Float s
  58892. for (name in source.floatsArrays) {
  58893. material.setFloats(name, source.floatsArrays[name]);
  58894. }
  58895. // Color3
  58896. for (name in source.colors3) {
  58897. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58898. }
  58899. // Color3 arrays
  58900. for (name in source.colors3Arrays) {
  58901. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58902. if (i % 3 === 0) {
  58903. arr.push([num]);
  58904. }
  58905. else {
  58906. arr[arr.length - 1].push(num);
  58907. }
  58908. return arr;
  58909. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58910. material.setColor3Array(name, colors);
  58911. }
  58912. // Color4
  58913. for (name in source.colors4) {
  58914. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58915. }
  58916. // Vector2
  58917. for (name in source.vectors2) {
  58918. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58919. }
  58920. // Vector3
  58921. for (name in source.vectors3) {
  58922. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58923. }
  58924. // Vector4
  58925. for (name in source.vectors4) {
  58926. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58927. }
  58928. // Matrix
  58929. for (name in source.matrices) {
  58930. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58931. }
  58932. // Matrix 3x3
  58933. for (name in source.matrices3x3) {
  58934. material.setMatrix3x3(name, source.matrices3x3[name]);
  58935. }
  58936. // Matrix 2x2
  58937. for (name in source.matrices2x2) {
  58938. material.setMatrix2x2(name, source.matrices2x2[name]);
  58939. }
  58940. // Vector2Array
  58941. for (name in source.vectors2Arrays) {
  58942. material.setArray2(name, source.vectors2Arrays[name]);
  58943. }
  58944. // Vector3Array
  58945. for (name in source.vectors3Arrays) {
  58946. material.setArray3(name, source.vectors3Arrays[name]);
  58947. }
  58948. return material;
  58949. };
  58950. return ShaderMaterial;
  58951. }(BABYLON.Material));
  58952. BABYLON.ShaderMaterial = ShaderMaterial;
  58953. })(BABYLON || (BABYLON = {}));
  58954. //# sourceMappingURL=babylon.shaderMaterial.js.map
  58955. var BABYLON;
  58956. (function (BABYLON) {
  58957. var GroundMesh = /** @class */ (function (_super) {
  58958. __extends(GroundMesh, _super);
  58959. function GroundMesh(name, scene) {
  58960. var _this = _super.call(this, name, scene) || this;
  58961. _this.generateOctree = false;
  58962. return _this;
  58963. }
  58964. GroundMesh.prototype.getClassName = function () {
  58965. return "GroundMesh";
  58966. };
  58967. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  58968. get: function () {
  58969. return Math.min(this._subdivisionsX, this._subdivisionsY);
  58970. },
  58971. enumerable: true,
  58972. configurable: true
  58973. });
  58974. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  58975. get: function () {
  58976. return this._subdivisionsX;
  58977. },
  58978. enumerable: true,
  58979. configurable: true
  58980. });
  58981. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  58982. get: function () {
  58983. return this._subdivisionsY;
  58984. },
  58985. enumerable: true,
  58986. configurable: true
  58987. });
  58988. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  58989. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  58990. this._subdivisionsX = chunksCount;
  58991. this._subdivisionsY = chunksCount;
  58992. this.subdivide(chunksCount);
  58993. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  58994. };
  58995. /**
  58996. * Returns a height (y) value in the Worl system :
  58997. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58998. * Returns the ground y position if (x, z) are outside the ground surface.
  58999. */
  59000. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59001. var world = this.getWorldMatrix();
  59002. var invMat = BABYLON.Tmp.Matrix[5];
  59003. world.invertToRef(invMat);
  59004. var tmpVect = BABYLON.Tmp.Vector3[8];
  59005. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59006. x = tmpVect.x;
  59007. z = tmpVect.z;
  59008. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59009. return this.position.y;
  59010. }
  59011. if (!this._heightQuads || this._heightQuads.length == 0) {
  59012. this._initHeightQuads();
  59013. this._computeHeightQuads();
  59014. }
  59015. var facet = this._getFacetAt(x, z);
  59016. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59017. // return y in the World system
  59018. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59019. return tmpVect.y;
  59020. };
  59021. /**
  59022. * Returns a normalized vector (Vector3) orthogonal to the ground
  59023. * at the ground coordinates (x, z) expressed in the World system.
  59024. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59025. */
  59026. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59027. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59028. this.getNormalAtCoordinatesToRef(x, z, normal);
  59029. return normal;
  59030. };
  59031. /**
  59032. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59033. * at the ground coordinates (x, z) expressed in the World system.
  59034. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59035. * Returns the GroundMesh.
  59036. */
  59037. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59038. var world = this.getWorldMatrix();
  59039. var tmpMat = BABYLON.Tmp.Matrix[5];
  59040. world.invertToRef(tmpMat);
  59041. var tmpVect = BABYLON.Tmp.Vector3[8];
  59042. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59043. x = tmpVect.x;
  59044. z = tmpVect.z;
  59045. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59046. return this;
  59047. }
  59048. if (!this._heightQuads || this._heightQuads.length == 0) {
  59049. this._initHeightQuads();
  59050. this._computeHeightQuads();
  59051. }
  59052. var facet = this._getFacetAt(x, z);
  59053. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59054. return this;
  59055. };
  59056. /**
  59057. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59058. * if the ground has been updated.
  59059. * This can be used in the render loop.
  59060. * Returns the GroundMesh.
  59061. */
  59062. GroundMesh.prototype.updateCoordinateHeights = function () {
  59063. if (!this._heightQuads || this._heightQuads.length == 0) {
  59064. this._initHeightQuads();
  59065. }
  59066. this._computeHeightQuads();
  59067. return this;
  59068. };
  59069. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59070. GroundMesh.prototype._getFacetAt = function (x, z) {
  59071. // retrieve col and row from x, z coordinates in the ground local system
  59072. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59073. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59074. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59075. var facet;
  59076. if (z < quad.slope.x * x + quad.slope.y) {
  59077. facet = quad.facet1;
  59078. }
  59079. else {
  59080. facet = quad.facet2;
  59081. }
  59082. return facet;
  59083. };
  59084. // Creates and populates the heightMap array with "facet" elements :
  59085. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59086. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59087. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59088. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59089. // Returns the GroundMesh.
  59090. GroundMesh.prototype._initHeightQuads = function () {
  59091. var subdivisionsX = this._subdivisionsX;
  59092. var subdivisionsY = this._subdivisionsY;
  59093. this._heightQuads = new Array();
  59094. for (var row = 0; row < subdivisionsY; row++) {
  59095. for (var col = 0; col < subdivisionsX; col++) {
  59096. 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) };
  59097. this._heightQuads[row * subdivisionsX + col] = quad;
  59098. }
  59099. }
  59100. return this;
  59101. };
  59102. // Compute each quad element values and update the the heightMap array :
  59103. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59104. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59105. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59106. // Returns the GroundMesh.
  59107. GroundMesh.prototype._computeHeightQuads = function () {
  59108. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59109. if (!positions) {
  59110. return this;
  59111. }
  59112. var v1 = BABYLON.Tmp.Vector3[3];
  59113. var v2 = BABYLON.Tmp.Vector3[2];
  59114. var v3 = BABYLON.Tmp.Vector3[1];
  59115. var v4 = BABYLON.Tmp.Vector3[0];
  59116. var v1v2 = BABYLON.Tmp.Vector3[4];
  59117. var v1v3 = BABYLON.Tmp.Vector3[5];
  59118. var v1v4 = BABYLON.Tmp.Vector3[6];
  59119. var norm1 = BABYLON.Tmp.Vector3[7];
  59120. var norm2 = BABYLON.Tmp.Vector3[8];
  59121. var i = 0;
  59122. var j = 0;
  59123. var k = 0;
  59124. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59125. var h = 0;
  59126. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59127. var d2 = 0;
  59128. var subdivisionsX = this._subdivisionsX;
  59129. var subdivisionsY = this._subdivisionsY;
  59130. for (var row = 0; row < subdivisionsY; row++) {
  59131. for (var col = 0; col < subdivisionsX; col++) {
  59132. i = col * 3;
  59133. j = row * (subdivisionsX + 1) * 3;
  59134. k = (row + 1) * (subdivisionsX + 1) * 3;
  59135. v1.x = positions[j + i];
  59136. v1.y = positions[j + i + 1];
  59137. v1.z = positions[j + i + 2];
  59138. v2.x = positions[j + i + 3];
  59139. v2.y = positions[j + i + 4];
  59140. v2.z = positions[j + i + 5];
  59141. v3.x = positions[k + i];
  59142. v3.y = positions[k + i + 1];
  59143. v3.z = positions[k + i + 2];
  59144. v4.x = positions[k + i + 3];
  59145. v4.y = positions[k + i + 4];
  59146. v4.z = positions[k + i + 5];
  59147. // 2D slope V1V4
  59148. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59149. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59150. // facet equations :
  59151. // we compute each facet normal vector
  59152. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59153. // we compute the value d by applying the equation to v1 which belongs to the plane
  59154. // then we store the facet equation in a Vector4
  59155. v2.subtractToRef(v1, v1v2);
  59156. v3.subtractToRef(v1, v1v3);
  59157. v4.subtractToRef(v1, v1v4);
  59158. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59159. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59160. norm1.normalize();
  59161. norm2.normalize();
  59162. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59163. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59164. var quad = this._heightQuads[row * subdivisionsX + col];
  59165. quad.slope.copyFromFloats(cd, h);
  59166. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59167. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59168. }
  59169. }
  59170. return this;
  59171. };
  59172. GroundMesh.prototype.serialize = function (serializationObject) {
  59173. _super.prototype.serialize.call(this, serializationObject);
  59174. serializationObject.subdivisionsX = this._subdivisionsX;
  59175. serializationObject.subdivisionsY = this._subdivisionsY;
  59176. serializationObject.minX = this._minX;
  59177. serializationObject.maxX = this._maxX;
  59178. serializationObject.minZ = this._minZ;
  59179. serializationObject.maxZ = this._maxZ;
  59180. serializationObject.width = this._width;
  59181. serializationObject.height = this._height;
  59182. };
  59183. GroundMesh.Parse = function (parsedMesh, scene) {
  59184. var result = new GroundMesh(parsedMesh.name, scene);
  59185. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59186. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59187. result._minX = parsedMesh.minX;
  59188. result._maxX = parsedMesh.maxX;
  59189. result._minZ = parsedMesh.minZ;
  59190. result._maxZ = parsedMesh.maxZ;
  59191. result._width = parsedMesh.width;
  59192. result._height = parsedMesh.height;
  59193. return result;
  59194. };
  59195. return GroundMesh;
  59196. }(BABYLON.Mesh));
  59197. BABYLON.GroundMesh = GroundMesh;
  59198. })(BABYLON || (BABYLON = {}));
  59199. //# sourceMappingURL=babylon.groundMesh.js.map
  59200. var BABYLON;
  59201. (function (BABYLON) {
  59202. /**
  59203. * Creates an instance based on a source mesh.
  59204. */
  59205. var InstancedMesh = /** @class */ (function (_super) {
  59206. __extends(InstancedMesh, _super);
  59207. function InstancedMesh(name, source) {
  59208. var _this = _super.call(this, name, source.getScene()) || this;
  59209. source.instances.push(_this);
  59210. _this._sourceMesh = source;
  59211. _this.position.copyFrom(source.position);
  59212. _this.rotation.copyFrom(source.rotation);
  59213. _this.scaling.copyFrom(source.scaling);
  59214. if (source.rotationQuaternion) {
  59215. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59216. }
  59217. _this.infiniteDistance = source.infiniteDistance;
  59218. _this.setPivotMatrix(source.getPivotMatrix());
  59219. _this.refreshBoundingInfo();
  59220. _this._syncSubMeshes();
  59221. return _this;
  59222. }
  59223. /**
  59224. * Returns the string "InstancedMesh".
  59225. */
  59226. InstancedMesh.prototype.getClassName = function () {
  59227. return "InstancedMesh";
  59228. };
  59229. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59230. // Methods
  59231. get: function () {
  59232. return this._sourceMesh.receiveShadows;
  59233. },
  59234. enumerable: true,
  59235. configurable: true
  59236. });
  59237. Object.defineProperty(InstancedMesh.prototype, "material", {
  59238. get: function () {
  59239. return this._sourceMesh.material;
  59240. },
  59241. enumerable: true,
  59242. configurable: true
  59243. });
  59244. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59245. get: function () {
  59246. return this._sourceMesh.visibility;
  59247. },
  59248. enumerable: true,
  59249. configurable: true
  59250. });
  59251. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59252. get: function () {
  59253. return this._sourceMesh.skeleton;
  59254. },
  59255. enumerable: true,
  59256. configurable: true
  59257. });
  59258. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59259. get: function () {
  59260. return this._sourceMesh.renderingGroupId;
  59261. },
  59262. set: function (value) {
  59263. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59264. return;
  59265. }
  59266. //no-op with warning
  59267. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59268. },
  59269. enumerable: true,
  59270. configurable: true
  59271. });
  59272. /**
  59273. * Returns the total number of vertices (integer).
  59274. */
  59275. InstancedMesh.prototype.getTotalVertices = function () {
  59276. return this._sourceMesh.getTotalVertices();
  59277. };
  59278. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59279. get: function () {
  59280. return this._sourceMesh;
  59281. },
  59282. enumerable: true,
  59283. configurable: true
  59284. });
  59285. /**
  59286. * Is this node ready to be used/rendered
  59287. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59288. * @return {boolean} is it ready
  59289. */
  59290. InstancedMesh.prototype.isReady = function (completeCheck) {
  59291. if (completeCheck === void 0) { completeCheck = false; }
  59292. return this._sourceMesh.isReady(completeCheck, true);
  59293. };
  59294. /**
  59295. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59296. */
  59297. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59298. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59299. };
  59300. /**
  59301. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59302. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59303. * The `data` are either a numeric array either a Float32Array.
  59304. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59305. * 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).
  59306. * Note that a new underlying VertexBuffer object is created each call.
  59307. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59308. *
  59309. * Possible `kind` values :
  59310. * - BABYLON.VertexBuffer.PositionKind
  59311. * - BABYLON.VertexBuffer.UVKind
  59312. * - BABYLON.VertexBuffer.UV2Kind
  59313. * - BABYLON.VertexBuffer.UV3Kind
  59314. * - BABYLON.VertexBuffer.UV4Kind
  59315. * - BABYLON.VertexBuffer.UV5Kind
  59316. * - BABYLON.VertexBuffer.UV6Kind
  59317. * - BABYLON.VertexBuffer.ColorKind
  59318. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59319. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59320. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59321. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59322. *
  59323. * Returns the Mesh.
  59324. */
  59325. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59326. if (this.sourceMesh) {
  59327. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59328. }
  59329. return this.sourceMesh;
  59330. };
  59331. /**
  59332. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59333. * If the mesh has no geometry, it is simply returned as it is.
  59334. * The `data` are either a numeric array either a Float32Array.
  59335. * No new underlying VertexBuffer object is created.
  59336. * 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.
  59337. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59338. *
  59339. * Possible `kind` values :
  59340. * - BABYLON.VertexBuffer.PositionKind
  59341. * - BABYLON.VertexBuffer.UVKind
  59342. * - BABYLON.VertexBuffer.UV2Kind
  59343. * - BABYLON.VertexBuffer.UV3Kind
  59344. * - BABYLON.VertexBuffer.UV4Kind
  59345. * - BABYLON.VertexBuffer.UV5Kind
  59346. * - BABYLON.VertexBuffer.UV6Kind
  59347. * - BABYLON.VertexBuffer.ColorKind
  59348. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59349. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59350. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59351. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59352. *
  59353. * Returns the Mesh.
  59354. */
  59355. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59356. if (this.sourceMesh) {
  59357. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59358. }
  59359. return this.sourceMesh;
  59360. };
  59361. /**
  59362. * Sets the mesh indices.
  59363. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59364. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59365. * This method creates a new index buffer each call.
  59366. * Returns the Mesh.
  59367. */
  59368. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59369. if (totalVertices === void 0) { totalVertices = null; }
  59370. if (this.sourceMesh) {
  59371. this.sourceMesh.setIndices(indices, totalVertices);
  59372. }
  59373. return this.sourceMesh;
  59374. };
  59375. /**
  59376. * Boolean : True if the mesh owns the requested kind of data.
  59377. */
  59378. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59379. return this._sourceMesh.isVerticesDataPresent(kind);
  59380. };
  59381. /**
  59382. * Returns an array of indices (IndicesArray).
  59383. */
  59384. InstancedMesh.prototype.getIndices = function () {
  59385. return this._sourceMesh.getIndices();
  59386. };
  59387. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59388. get: function () {
  59389. return this._sourceMesh._positions;
  59390. },
  59391. enumerable: true,
  59392. configurable: true
  59393. });
  59394. /**
  59395. * Sets a new updated BoundingInfo to the mesh.
  59396. * Returns the mesh.
  59397. */
  59398. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59399. var meshBB = this._sourceMesh.getBoundingInfo();
  59400. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59401. this._updateBoundingInfo();
  59402. return this;
  59403. };
  59404. /** @hidden */
  59405. InstancedMesh.prototype._preActivate = function () {
  59406. if (this._currentLOD) {
  59407. this._currentLOD._preActivate();
  59408. }
  59409. return this;
  59410. };
  59411. /** @hidden */
  59412. InstancedMesh.prototype._activate = function (renderId) {
  59413. if (this._currentLOD) {
  59414. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59415. }
  59416. return this;
  59417. };
  59418. /**
  59419. * Returns the current associated LOD AbstractMesh.
  59420. */
  59421. InstancedMesh.prototype.getLOD = function (camera) {
  59422. if (!camera) {
  59423. return this;
  59424. }
  59425. var boundingInfo = this.getBoundingInfo();
  59426. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59427. if (this._currentLOD === this.sourceMesh) {
  59428. return this;
  59429. }
  59430. return this._currentLOD;
  59431. };
  59432. /** @hidden */
  59433. InstancedMesh.prototype._syncSubMeshes = function () {
  59434. this.releaseSubMeshes();
  59435. if (this._sourceMesh.subMeshes) {
  59436. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59437. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59438. }
  59439. }
  59440. return this;
  59441. };
  59442. /** @hidden */
  59443. InstancedMesh.prototype._generatePointsArray = function () {
  59444. return this._sourceMesh._generatePointsArray();
  59445. };
  59446. /**
  59447. * Creates a new InstancedMesh from the current mesh.
  59448. * - name (string) : the cloned mesh name
  59449. * - newParent (optional Node) : the optional Node to parent the clone to.
  59450. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59451. *
  59452. * Returns the clone.
  59453. */
  59454. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59455. var result = this._sourceMesh.createInstance(name);
  59456. // Deep copy
  59457. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59458. // Bounding info
  59459. this.refreshBoundingInfo();
  59460. // Parent
  59461. if (newParent) {
  59462. result.parent = newParent;
  59463. }
  59464. if (!doNotCloneChildren) {
  59465. // Children
  59466. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59467. var mesh = this.getScene().meshes[index];
  59468. if (mesh.parent === this) {
  59469. mesh.clone(mesh.name, result);
  59470. }
  59471. }
  59472. }
  59473. result.computeWorldMatrix(true);
  59474. return result;
  59475. };
  59476. /**
  59477. * Disposes the InstancedMesh.
  59478. * Returns nothing.
  59479. */
  59480. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59481. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59482. // Remove from mesh
  59483. var index = this._sourceMesh.instances.indexOf(this);
  59484. this._sourceMesh.instances.splice(index, 1);
  59485. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59486. };
  59487. return InstancedMesh;
  59488. }(BABYLON.AbstractMesh));
  59489. BABYLON.InstancedMesh = InstancedMesh;
  59490. })(BABYLON || (BABYLON = {}));
  59491. //# sourceMappingURL=babylon.instancedMesh.js.map
  59492. var BABYLON;
  59493. (function (BABYLON) {
  59494. var LinesMesh = /** @class */ (function (_super) {
  59495. __extends(LinesMesh, _super);
  59496. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59497. if (scene === void 0) { scene = null; }
  59498. if (parent === void 0) { parent = null; }
  59499. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59500. _this.useVertexColor = useVertexColor;
  59501. _this.useVertexAlpha = useVertexAlpha;
  59502. _this.color = new BABYLON.Color3(1, 1, 1);
  59503. _this.alpha = 1;
  59504. if (source) {
  59505. _this.color = source.color.clone();
  59506. _this.alpha = source.alpha;
  59507. _this.useVertexColor = source.useVertexColor;
  59508. _this.useVertexAlpha = source.useVertexAlpha;
  59509. }
  59510. _this._intersectionThreshold = 0.1;
  59511. var defines = [];
  59512. var options = {
  59513. attributes: [BABYLON.VertexBuffer.PositionKind],
  59514. uniforms: ["world", "viewProjection"],
  59515. needAlphaBlending: true,
  59516. defines: defines
  59517. };
  59518. if (useVertexAlpha === false) {
  59519. options.needAlphaBlending = false;
  59520. }
  59521. if (!useVertexColor) {
  59522. options.uniforms.push("color");
  59523. }
  59524. else {
  59525. options.defines.push("#define VERTEXCOLOR");
  59526. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59527. }
  59528. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59529. return _this;
  59530. }
  59531. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59532. /**
  59533. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59534. * This margin is expressed in world space coordinates, so its value may vary.
  59535. * Default value is 0.1
  59536. * @returns the intersection Threshold value.
  59537. */
  59538. get: function () {
  59539. return this._intersectionThreshold;
  59540. },
  59541. /**
  59542. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59543. * This margin is expressed in world space coordinates, so its value may vary.
  59544. * @param value the new threshold to apply
  59545. */
  59546. set: function (value) {
  59547. if (this._intersectionThreshold === value) {
  59548. return;
  59549. }
  59550. this._intersectionThreshold = value;
  59551. if (this.geometry) {
  59552. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59553. }
  59554. },
  59555. enumerable: true,
  59556. configurable: true
  59557. });
  59558. /**
  59559. * Returns the string "LineMesh"
  59560. */
  59561. LinesMesh.prototype.getClassName = function () {
  59562. return "LinesMesh";
  59563. };
  59564. Object.defineProperty(LinesMesh.prototype, "material", {
  59565. /**
  59566. * @hidden
  59567. */
  59568. get: function () {
  59569. return this._colorShader;
  59570. },
  59571. /**
  59572. * @hidden
  59573. */
  59574. set: function (value) {
  59575. // Do nothing
  59576. },
  59577. enumerable: true,
  59578. configurable: true
  59579. });
  59580. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59581. /**
  59582. * @hidden
  59583. */
  59584. get: function () {
  59585. return false;
  59586. },
  59587. enumerable: true,
  59588. configurable: true
  59589. });
  59590. LinesMesh.prototype.createInstance = function (name) {
  59591. throw new Error("LinesMeshes do not support createInstance.");
  59592. };
  59593. /** @hidden */
  59594. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59595. if (!this._geometry) {
  59596. return this;
  59597. }
  59598. // VBOs
  59599. this._geometry._bind(this._colorShader.getEffect());
  59600. // Color
  59601. if (!this.useVertexColor) {
  59602. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59603. }
  59604. return this;
  59605. };
  59606. /** @hidden */
  59607. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59608. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59609. return this;
  59610. }
  59611. var engine = this.getScene().getEngine();
  59612. // Draw order
  59613. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59614. return this;
  59615. };
  59616. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59617. this._colorShader.dispose();
  59618. _super.prototype.dispose.call(this, doNotRecurse);
  59619. };
  59620. /**
  59621. * Returns a new LineMesh object cloned from the current one.
  59622. */
  59623. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59624. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59625. };
  59626. /**
  59627. * Enables the edge rendering mode on the mesh.
  59628. * This mode makes the mesh edges visible
  59629. * @param epsilon defines the maximal distance between two angles to detect a face
  59630. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  59631. * @returns the currentAbstractMesh
  59632. * @see https://www.babylonjs-playground.com/#19O9TU#0
  59633. */
  59634. LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  59635. if (epsilon === void 0) { epsilon = 0.95; }
  59636. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  59637. this.disableEdgesRendering();
  59638. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  59639. return this;
  59640. };
  59641. return LinesMesh;
  59642. }(BABYLON.Mesh));
  59643. BABYLON.LinesMesh = LinesMesh;
  59644. })(BABYLON || (BABYLON = {}));
  59645. //# sourceMappingURL=babylon.linesMesh.js.map
  59646. var BABYLON;
  59647. (function (BABYLON) {
  59648. /**
  59649. * This class implement a typical dictionary using a string as key and the generic type T as value.
  59650. * The underlying implementation relies on an associative array to ensure the best performances.
  59651. * The value can be anything including 'null' but except 'undefined'
  59652. */
  59653. var StringDictionary = /** @class */ (function () {
  59654. function StringDictionary() {
  59655. this._count = 0;
  59656. this._data = {};
  59657. }
  59658. /**
  59659. * This will clear this dictionary and copy the content from the 'source' one.
  59660. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  59661. * @param source the dictionary to take the content from and copy to this dictionary
  59662. */
  59663. StringDictionary.prototype.copyFrom = function (source) {
  59664. var _this = this;
  59665. this.clear();
  59666. source.forEach(function (t, v) { return _this.add(t, v); });
  59667. };
  59668. /**
  59669. * Get a value based from its key
  59670. * @param key the given key to get the matching value from
  59671. * @return the value if found, otherwise undefined is returned
  59672. */
  59673. StringDictionary.prototype.get = function (key) {
  59674. var val = this._data[key];
  59675. if (val !== undefined) {
  59676. return val;
  59677. }
  59678. return undefined;
  59679. };
  59680. /**
  59681. * Get a value from its key or add it if it doesn't exist.
  59682. * This method will ensure you that a given key/data will be present in the dictionary.
  59683. * @param key the given key to get the matching value from
  59684. * @param factory the factory that will create the value if the key is not present in the dictionary.
  59685. * The factory will only be invoked if there's no data for the given key.
  59686. * @return the value corresponding to the key.
  59687. */
  59688. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  59689. var val = this.get(key);
  59690. if (val !== undefined) {
  59691. return val;
  59692. }
  59693. val = factory(key);
  59694. if (val) {
  59695. this.add(key, val);
  59696. }
  59697. return val;
  59698. };
  59699. /**
  59700. * Get a value from its key if present in the dictionary otherwise add it
  59701. * @param key the key to get the value from
  59702. * @param val if there's no such key/value pair in the dictionary add it with this value
  59703. * @return the value corresponding to the key
  59704. */
  59705. StringDictionary.prototype.getOrAdd = function (key, val) {
  59706. var curVal = this.get(key);
  59707. if (curVal !== undefined) {
  59708. return curVal;
  59709. }
  59710. this.add(key, val);
  59711. return val;
  59712. };
  59713. /**
  59714. * Check if there's a given key in the dictionary
  59715. * @param key the key to check for
  59716. * @return true if the key is present, false otherwise
  59717. */
  59718. StringDictionary.prototype.contains = function (key) {
  59719. return this._data[key] !== undefined;
  59720. };
  59721. /**
  59722. * Add a new key and its corresponding value
  59723. * @param key the key to add
  59724. * @param value the value corresponding to the key
  59725. * @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
  59726. */
  59727. StringDictionary.prototype.add = function (key, value) {
  59728. if (this._data[key] !== undefined) {
  59729. return false;
  59730. }
  59731. this._data[key] = value;
  59732. ++this._count;
  59733. return true;
  59734. };
  59735. StringDictionary.prototype.set = function (key, value) {
  59736. if (this._data[key] === undefined) {
  59737. return false;
  59738. }
  59739. this._data[key] = value;
  59740. return true;
  59741. };
  59742. /**
  59743. * Get the element of the given key and remove it from the dictionary
  59744. * @param key
  59745. */
  59746. StringDictionary.prototype.getAndRemove = function (key) {
  59747. var val = this.get(key);
  59748. if (val !== undefined) {
  59749. delete this._data[key];
  59750. --this._count;
  59751. return val;
  59752. }
  59753. return null;
  59754. };
  59755. /**
  59756. * Remove a key/value from the dictionary.
  59757. * @param key the key to remove
  59758. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  59759. */
  59760. StringDictionary.prototype.remove = function (key) {
  59761. if (this.contains(key)) {
  59762. delete this._data[key];
  59763. --this._count;
  59764. return true;
  59765. }
  59766. return false;
  59767. };
  59768. /**
  59769. * Clear the whole content of the dictionary
  59770. */
  59771. StringDictionary.prototype.clear = function () {
  59772. this._data = {};
  59773. this._count = 0;
  59774. };
  59775. Object.defineProperty(StringDictionary.prototype, "count", {
  59776. get: function () {
  59777. return this._count;
  59778. },
  59779. enumerable: true,
  59780. configurable: true
  59781. });
  59782. /**
  59783. * Execute a callback on each key/val of the dictionary.
  59784. * Note that you can remove any element in this dictionary in the callback implementation
  59785. * @param callback the callback to execute on a given key/value pair
  59786. */
  59787. StringDictionary.prototype.forEach = function (callback) {
  59788. for (var cur in this._data) {
  59789. var val = this._data[cur];
  59790. callback(cur, val);
  59791. }
  59792. };
  59793. /**
  59794. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  59795. * If the callback returns null or undefined the method will iterate to the next key/value pair
  59796. * Note that you can remove any element in this dictionary in the callback implementation
  59797. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  59798. */
  59799. StringDictionary.prototype.first = function (callback) {
  59800. for (var cur in this._data) {
  59801. var val = this._data[cur];
  59802. var res = callback(cur, val);
  59803. if (res) {
  59804. return res;
  59805. }
  59806. }
  59807. return null;
  59808. };
  59809. return StringDictionary;
  59810. }());
  59811. BABYLON.StringDictionary = StringDictionary;
  59812. })(BABYLON || (BABYLON = {}));
  59813. //# sourceMappingURL=babylon.stringDictionary.js.map
  59814. var BABYLON;
  59815. (function (BABYLON) {
  59816. var Debug;
  59817. (function (Debug) {
  59818. /**
  59819. * Class used to render a debug view of a given skeleton
  59820. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  59821. */
  59822. var SkeletonViewer = /** @class */ (function () {
  59823. /**
  59824. * Creates a new SkeletonViewer
  59825. * @param skeleton defines the skeleton to render
  59826. * @param mesh defines the mesh attached to the skeleton
  59827. * @param scene defines the hosting scene
  59828. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  59829. * @param renderingGroupId defines the rendering group id to use with the viewer
  59830. */
  59831. function SkeletonViewer(
  59832. /** defines the skeleton to render */
  59833. skeleton,
  59834. /** defines the mesh attached to the skeleton */
  59835. mesh, scene,
  59836. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  59837. autoUpdateBonesMatrices,
  59838. /** defines the rendering group id to use with the viewer */
  59839. renderingGroupId) {
  59840. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59841. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59842. this.skeleton = skeleton;
  59843. this.mesh = mesh;
  59844. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59845. this.renderingGroupId = renderingGroupId;
  59846. /** Gets or sets the color used to render the skeleton */
  59847. this.color = BABYLON.Color3.White();
  59848. this._debugLines = new Array();
  59849. this._isEnabled = false;
  59850. this._scene = scene;
  59851. this.update();
  59852. this._renderFunction = this.update.bind(this);
  59853. }
  59854. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59855. get: function () {
  59856. return this._isEnabled;
  59857. },
  59858. /** Gets or sets a boolean indicating if the viewer is enabled */
  59859. set: function (value) {
  59860. if (this._isEnabled === value) {
  59861. return;
  59862. }
  59863. this._isEnabled = value;
  59864. if (value) {
  59865. this._scene.registerBeforeRender(this._renderFunction);
  59866. }
  59867. else {
  59868. this._scene.unregisterBeforeRender(this._renderFunction);
  59869. }
  59870. },
  59871. enumerable: true,
  59872. configurable: true
  59873. });
  59874. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59875. if (x === void 0) { x = 0; }
  59876. if (y === void 0) { y = 0; }
  59877. if (z === void 0) { z = 0; }
  59878. var tmat = BABYLON.Tmp.Matrix[0];
  59879. var parentBone = bone.getParent();
  59880. tmat.copyFrom(bone.getLocalMatrix());
  59881. if (x !== 0 || y !== 0 || z !== 0) {
  59882. var tmat2 = BABYLON.Tmp.Matrix[1];
  59883. BABYLON.Matrix.IdentityToRef(tmat2);
  59884. tmat2.m[12] = x;
  59885. tmat2.m[13] = y;
  59886. tmat2.m[14] = z;
  59887. tmat2.multiplyToRef(tmat, tmat);
  59888. }
  59889. if (parentBone) {
  59890. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59891. }
  59892. tmat.multiplyToRef(meshMat, tmat);
  59893. position.x = tmat.m[12];
  59894. position.y = tmat.m[13];
  59895. position.z = tmat.m[14];
  59896. };
  59897. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59898. var len = bones.length;
  59899. var meshPos = this.mesh.position;
  59900. for (var i = 0; i < len; i++) {
  59901. var bone = bones[i];
  59902. var points = this._debugLines[i];
  59903. if (!points) {
  59904. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59905. this._debugLines[i] = points;
  59906. }
  59907. this._getBonePosition(points[0], bone, meshMat);
  59908. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59909. points[0].subtractInPlace(meshPos);
  59910. points[1].subtractInPlace(meshPos);
  59911. }
  59912. };
  59913. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59914. var len = bones.length;
  59915. var boneNum = 0;
  59916. var meshPos = this.mesh.position;
  59917. for (var i = len - 1; i >= 0; i--) {
  59918. var childBone = bones[i];
  59919. var parentBone = childBone.getParent();
  59920. if (!parentBone) {
  59921. continue;
  59922. }
  59923. var points = this._debugLines[boneNum];
  59924. if (!points) {
  59925. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59926. this._debugLines[boneNum] = points;
  59927. }
  59928. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  59929. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  59930. points[0].subtractInPlace(meshPos);
  59931. points[1].subtractInPlace(meshPos);
  59932. boneNum++;
  59933. }
  59934. };
  59935. /** Update the viewer to sync with current skeleton state */
  59936. SkeletonViewer.prototype.update = function () {
  59937. if (this.autoUpdateBonesMatrices) {
  59938. this.skeleton.computeAbsoluteTransforms();
  59939. }
  59940. if (this.skeleton.bones[0].length === undefined) {
  59941. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59942. }
  59943. else {
  59944. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59945. }
  59946. if (!this._debugMesh) {
  59947. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  59948. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59949. }
  59950. else {
  59951. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59952. }
  59953. this._debugMesh.position.copyFrom(this.mesh.position);
  59954. this._debugMesh.color = this.color;
  59955. };
  59956. /** Release associated resources */
  59957. SkeletonViewer.prototype.dispose = function () {
  59958. if (this._debugMesh) {
  59959. this.isEnabled = false;
  59960. this._debugMesh.dispose();
  59961. this._debugMesh = null;
  59962. }
  59963. };
  59964. return SkeletonViewer;
  59965. }());
  59966. Debug.SkeletonViewer = SkeletonViewer;
  59967. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59968. })(BABYLON || (BABYLON = {}));
  59969. //# sourceMappingURL=babylon.skeletonViewer.js.map
  59970. /**
  59971. * Module Debug contains the (visual) components to debug a scene correctly
  59972. */
  59973. var BABYLON;
  59974. (function (BABYLON) {
  59975. var Debug;
  59976. (function (Debug) {
  59977. /**
  59978. * The Axes viewer will show 3 axes in a specific point in space
  59979. */
  59980. var AxesViewer = /** @class */ (function () {
  59981. /**
  59982. * Creates a new AxesViewer
  59983. * @param scene defines the hosting scene
  59984. * @param scaleLines defines a number used to scale line length (1 by default)
  59985. */
  59986. function AxesViewer(scene, scaleLines) {
  59987. if (scaleLines === void 0) { scaleLines = 1; }
  59988. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59989. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59990. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59991. /**
  59992. * Gets or sets a number used to scale line length
  59993. */
  59994. this.scaleLines = 1;
  59995. this.scaleLines = scaleLines;
  59996. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  59997. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  59998. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  59999. this._xmesh.renderingGroupId = 2;
  60000. this._ymesh.renderingGroupId = 2;
  60001. this._zmesh.renderingGroupId = 2;
  60002. this._xmesh.material.checkReadyOnlyOnce = true;
  60003. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60004. this._ymesh.material.checkReadyOnlyOnce = true;
  60005. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60006. this._zmesh.material.checkReadyOnlyOnce = true;
  60007. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60008. this.scene = scene;
  60009. }
  60010. /**
  60011. * Force the viewer to update
  60012. * @param position defines the position of the viewer
  60013. * @param xaxis defines the x axis of the viewer
  60014. * @param yaxis defines the y axis of the viewer
  60015. * @param zaxis defines the z axis of the viewer
  60016. */
  60017. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60018. var scaleLines = this.scaleLines;
  60019. if (this._xmesh) {
  60020. this._xmesh.position.copyFrom(position);
  60021. }
  60022. if (this._ymesh) {
  60023. this._ymesh.position.copyFrom(position);
  60024. }
  60025. if (this._zmesh) {
  60026. this._zmesh.position.copyFrom(position);
  60027. }
  60028. var point2 = this._xline[1];
  60029. point2.x = xaxis.x * scaleLines;
  60030. point2.y = xaxis.y * scaleLines;
  60031. point2.z = xaxis.z * scaleLines;
  60032. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60033. point2 = this._yline[1];
  60034. point2.x = yaxis.x * scaleLines;
  60035. point2.y = yaxis.y * scaleLines;
  60036. point2.z = yaxis.z * scaleLines;
  60037. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60038. point2 = this._zline[1];
  60039. point2.x = zaxis.x * scaleLines;
  60040. point2.y = zaxis.y * scaleLines;
  60041. point2.z = zaxis.z * scaleLines;
  60042. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60043. };
  60044. /** Releases resources */
  60045. AxesViewer.prototype.dispose = function () {
  60046. if (this._xmesh) {
  60047. this._xmesh.dispose();
  60048. }
  60049. if (this._ymesh) {
  60050. this._ymesh.dispose();
  60051. }
  60052. if (this._zmesh) {
  60053. this._zmesh.dispose();
  60054. }
  60055. this._xmesh = null;
  60056. this._ymesh = null;
  60057. this._zmesh = null;
  60058. this.scene = null;
  60059. };
  60060. return AxesViewer;
  60061. }());
  60062. Debug.AxesViewer = AxesViewer;
  60063. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60064. })(BABYLON || (BABYLON = {}));
  60065. //# sourceMappingURL=babylon.axesViewer.js.map
  60066. var BABYLON;
  60067. (function (BABYLON) {
  60068. var Debug;
  60069. (function (Debug) {
  60070. /**
  60071. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60072. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60073. */
  60074. var BoneAxesViewer = /** @class */ (function (_super) {
  60075. __extends(BoneAxesViewer, _super);
  60076. /**
  60077. * Creates a new BoneAxesViewer
  60078. * @param scene defines the hosting scene
  60079. * @param bone defines the target bone
  60080. * @param mesh defines the target mesh
  60081. * @param scaleLines defines a scaling factor for line length (1 by default)
  60082. */
  60083. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  60084. if (scaleLines === void 0) { scaleLines = 1; }
  60085. var _this = _super.call(this, scene, scaleLines) || this;
  60086. /** Gets current position */
  60087. _this.pos = BABYLON.Vector3.Zero();
  60088. /** Gets direction of X axis */
  60089. _this.xaxis = BABYLON.Vector3.Zero();
  60090. /** Gets direction of Y axis */
  60091. _this.yaxis = BABYLON.Vector3.Zero();
  60092. /** Gets direction of Z axis */
  60093. _this.zaxis = BABYLON.Vector3.Zero();
  60094. _this.mesh = mesh;
  60095. _this.bone = bone;
  60096. return _this;
  60097. }
  60098. /**
  60099. * Force the viewer to update
  60100. */
  60101. BoneAxesViewer.prototype.update = function () {
  60102. if (!this.mesh || !this.bone) {
  60103. return;
  60104. }
  60105. var bone = this.bone;
  60106. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  60107. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  60108. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  60109. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  60110. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  60111. };
  60112. /** Releases resources */
  60113. BoneAxesViewer.prototype.dispose = function () {
  60114. if (this.mesh) {
  60115. this.mesh = null;
  60116. this.bone = null;
  60117. _super.prototype.dispose.call(this);
  60118. }
  60119. };
  60120. return BoneAxesViewer;
  60121. }(Debug.AxesViewer));
  60122. Debug.BoneAxesViewer = BoneAxesViewer;
  60123. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60124. })(BABYLON || (BABYLON = {}));
  60125. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  60126. var BABYLON;
  60127. (function (BABYLON) {
  60128. var RayHelper = /** @class */ (function () {
  60129. function RayHelper(ray) {
  60130. this.ray = ray;
  60131. }
  60132. RayHelper.CreateAndShow = function (ray, scene, color) {
  60133. var helper = new RayHelper(ray);
  60134. helper.show(scene, color);
  60135. return helper;
  60136. };
  60137. RayHelper.prototype.show = function (scene, color) {
  60138. if (!this._renderFunction && this.ray) {
  60139. var ray = this.ray;
  60140. this._renderFunction = this._render.bind(this);
  60141. this._scene = scene;
  60142. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  60143. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  60144. if (this._renderFunction) {
  60145. this._scene.registerBeforeRender(this._renderFunction);
  60146. }
  60147. }
  60148. if (color && this._renderLine) {
  60149. this._renderLine.color.copyFrom(color);
  60150. }
  60151. };
  60152. RayHelper.prototype.hide = function () {
  60153. if (this._renderFunction && this._scene) {
  60154. this._scene.unregisterBeforeRender(this._renderFunction);
  60155. this._scene = null;
  60156. this._renderFunction = null;
  60157. if (this._renderLine) {
  60158. this._renderLine.dispose();
  60159. this._renderLine = null;
  60160. }
  60161. this._renderPoints = [];
  60162. }
  60163. };
  60164. RayHelper.prototype._render = function () {
  60165. var ray = this.ray;
  60166. if (!ray) {
  60167. return;
  60168. }
  60169. var point = this._renderPoints[1];
  60170. var len = Math.min(ray.length, 1000000);
  60171. point.copyFrom(ray.direction);
  60172. point.scaleInPlace(len);
  60173. point.addInPlace(ray.origin);
  60174. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  60175. };
  60176. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  60177. this._attachedToMesh = mesh;
  60178. var ray = this.ray;
  60179. if (!ray) {
  60180. return;
  60181. }
  60182. if (!ray.direction) {
  60183. ray.direction = BABYLON.Vector3.Zero();
  60184. }
  60185. if (!ray.origin) {
  60186. ray.origin = BABYLON.Vector3.Zero();
  60187. }
  60188. if (length) {
  60189. ray.length = length;
  60190. }
  60191. if (!meshSpaceOrigin) {
  60192. meshSpaceOrigin = BABYLON.Vector3.Zero();
  60193. }
  60194. if (!meshSpaceDirection) {
  60195. // -1 so that this will work with Mesh.lookAt
  60196. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  60197. }
  60198. if (!this._meshSpaceDirection) {
  60199. this._meshSpaceDirection = meshSpaceDirection.clone();
  60200. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  60201. }
  60202. else {
  60203. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  60204. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  60205. }
  60206. if (!this._updateToMeshFunction) {
  60207. this._updateToMeshFunction = this._updateToMesh.bind(this);
  60208. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  60209. }
  60210. this._updateToMesh();
  60211. };
  60212. RayHelper.prototype.detachFromMesh = function () {
  60213. if (this._attachedToMesh) {
  60214. if (this._updateToMeshFunction) {
  60215. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  60216. }
  60217. this._attachedToMesh = null;
  60218. this._updateToMeshFunction = null;
  60219. }
  60220. };
  60221. RayHelper.prototype._updateToMesh = function () {
  60222. var ray = this.ray;
  60223. if (!this._attachedToMesh || !ray) {
  60224. return;
  60225. }
  60226. if (this._attachedToMesh._isDisposed) {
  60227. this.detachFromMesh();
  60228. return;
  60229. }
  60230. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  60231. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  60232. };
  60233. RayHelper.prototype.dispose = function () {
  60234. this.hide();
  60235. this.detachFromMesh();
  60236. this.ray = null;
  60237. };
  60238. return RayHelper;
  60239. }());
  60240. BABYLON.RayHelper = RayHelper;
  60241. })(BABYLON || (BABYLON = {}));
  60242. //# sourceMappingURL=babylon.rayHelper.js.map
  60243. var BABYLON;
  60244. (function (BABYLON) {
  60245. // load the inspector using require, if not present in the global namespace.
  60246. var DebugLayer = /** @class */ (function () {
  60247. function DebugLayer(scene) {
  60248. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60249. this.onPropertyChangedObservable = new BABYLON.Observable();
  60250. this._scene = scene;
  60251. }
  60252. /** Creates the inspector window. */
  60253. DebugLayer.prototype._createInspector = function (config) {
  60254. if (config === void 0) { config = {}; }
  60255. var popup = config.popup || false;
  60256. var initialTab = config.initialTab || 0;
  60257. var parentElement = config.parentElement || null;
  60258. if (!this._inspector) {
  60259. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60260. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60261. } // else nothing to do as instance is already created
  60262. };
  60263. DebugLayer.prototype.isVisible = function () {
  60264. if (!this._inspector) {
  60265. return false;
  60266. }
  60267. return true;
  60268. };
  60269. DebugLayer.prototype.hide = function () {
  60270. if (this._inspector) {
  60271. try {
  60272. this._inspector.dispose();
  60273. }
  60274. catch (e) {
  60275. // If the inspector has been removed directly from the inspector tool
  60276. }
  60277. this.onPropertyChangedObservable.clear();
  60278. this._inspector = null;
  60279. }
  60280. };
  60281. /**
  60282. *
  60283. * Launch the debugLayer.
  60284. *
  60285. * initialTab:
  60286. * | Value | Tab Name |
  60287. * | --- | --- |
  60288. * | 0 | Scene |
  60289. * | 1 | Console |
  60290. * | 2 | Stats |
  60291. * | 3 | Textures |
  60292. * | 4 | Mesh |
  60293. * | 5 | Light |
  60294. * | 6 | Material |
  60295. * | 7 | GLTF |
  60296. * | 8 | GUI |
  60297. * | 9 | Physics |
  60298. * | 10 | Camera |
  60299. * | 11 | Audio |
  60300. *
  60301. */
  60302. DebugLayer.prototype.show = function (config) {
  60303. if (config === void 0) { config = {}; }
  60304. if (typeof this.BJSINSPECTOR == 'undefined') {
  60305. // Load inspector and add it to the DOM
  60306. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60307. }
  60308. else {
  60309. // Otherwise creates the inspector
  60310. this._createInspector(config);
  60311. }
  60312. };
  60313. /**
  60314. * Gets the active tab
  60315. * @return the index of the active tab or -1 if the inspector is hidden
  60316. */
  60317. DebugLayer.prototype.getActiveTab = function () {
  60318. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  60319. };
  60320. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  60321. return DebugLayer;
  60322. }());
  60323. BABYLON.DebugLayer = DebugLayer;
  60324. })(BABYLON || (BABYLON = {}));
  60325. //# sourceMappingURL=babylon.debugLayer.js.map
  60326. var BABYLON;
  60327. (function (BABYLON) {
  60328. var Debug;
  60329. (function (Debug) {
  60330. /**
  60331. * Used to show the physics impostor around the specific mesh
  60332. */
  60333. var PhysicsViewer = /** @class */ (function () {
  60334. /**
  60335. * Creates a new PhysicsViewer
  60336. * @param scene defines the hosting scene
  60337. */
  60338. function PhysicsViewer(scene) {
  60339. /** @hidden */
  60340. this._impostors = [];
  60341. /** @hidden */
  60342. this._meshes = [];
  60343. /** @hidden */
  60344. this._numMeshes = 0;
  60345. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60346. var physicEngine = this._scene.getPhysicsEngine();
  60347. if (physicEngine) {
  60348. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  60349. }
  60350. }
  60351. /** @hidden */
  60352. PhysicsViewer.prototype._updateDebugMeshes = function () {
  60353. var plugin = this._physicsEnginePlugin;
  60354. for (var i = 0; i < this._numMeshes; i++) {
  60355. var impostor = this._impostors[i];
  60356. if (!impostor) {
  60357. continue;
  60358. }
  60359. if (impostor.isDisposed) {
  60360. this.hideImpostor(this._impostors[i--]);
  60361. }
  60362. else {
  60363. var mesh = this._meshes[i];
  60364. if (mesh && plugin) {
  60365. plugin.syncMeshWithImpostor(mesh, impostor);
  60366. }
  60367. }
  60368. }
  60369. };
  60370. /**
  60371. * Renders a specified physic impostor
  60372. * @param impostor defines the impostor to render
  60373. */
  60374. PhysicsViewer.prototype.showImpostor = function (impostor) {
  60375. if (!this._scene) {
  60376. return;
  60377. }
  60378. for (var i = 0; i < this._numMeshes; i++) {
  60379. if (this._impostors[i] == impostor) {
  60380. return;
  60381. }
  60382. }
  60383. var debugMesh = this._getDebugMesh(impostor, this._scene);
  60384. if (debugMesh) {
  60385. this._impostors[this._numMeshes] = impostor;
  60386. this._meshes[this._numMeshes] = debugMesh;
  60387. if (this._numMeshes === 0) {
  60388. this._renderFunction = this._updateDebugMeshes.bind(this);
  60389. this._scene.registerBeforeRender(this._renderFunction);
  60390. }
  60391. this._numMeshes++;
  60392. }
  60393. };
  60394. /**
  60395. * Hides a specified physic impostor
  60396. * @param impostor defines the impostor to hide
  60397. */
  60398. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  60399. if (!impostor || !this._scene) {
  60400. return;
  60401. }
  60402. var removed = false;
  60403. for (var i = 0; i < this._numMeshes; i++) {
  60404. if (this._impostors[i] == impostor) {
  60405. var mesh = this._meshes[i];
  60406. if (!mesh) {
  60407. continue;
  60408. }
  60409. this._scene.removeMesh(mesh);
  60410. mesh.dispose();
  60411. this._numMeshes--;
  60412. if (this._numMeshes > 0) {
  60413. this._meshes[i] = this._meshes[this._numMeshes];
  60414. this._impostors[i] = this._impostors[this._numMeshes];
  60415. this._meshes[this._numMeshes] = null;
  60416. this._impostors[this._numMeshes] = null;
  60417. }
  60418. else {
  60419. this._meshes[0] = null;
  60420. this._impostors[0] = null;
  60421. }
  60422. removed = true;
  60423. break;
  60424. }
  60425. }
  60426. if (removed && this._numMeshes === 0) {
  60427. this._scene.unregisterBeforeRender(this._renderFunction);
  60428. }
  60429. };
  60430. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  60431. if (!this._debugMaterial) {
  60432. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  60433. this._debugMaterial.wireframe = true;
  60434. }
  60435. return this._debugMaterial;
  60436. };
  60437. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  60438. if (!this._debugBoxMesh) {
  60439. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  60440. this._debugBoxMesh.renderingGroupId = 1;
  60441. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60442. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  60443. scene.removeMesh(this._debugBoxMesh);
  60444. }
  60445. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  60446. };
  60447. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  60448. if (!this._debugSphereMesh) {
  60449. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  60450. this._debugSphereMesh.renderingGroupId = 1;
  60451. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60452. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  60453. scene.removeMesh(this._debugSphereMesh);
  60454. }
  60455. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  60456. };
  60457. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  60458. var mesh = null;
  60459. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  60460. mesh = this._getDebugBoxMesh(scene);
  60461. impostor.getBoxSizeToRef(mesh.scaling);
  60462. }
  60463. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  60464. mesh = this._getDebugSphereMesh(scene);
  60465. var radius = impostor.getRadius();
  60466. mesh.scaling.x = radius * 2;
  60467. mesh.scaling.y = radius * 2;
  60468. mesh.scaling.z = radius * 2;
  60469. }
  60470. return mesh;
  60471. };
  60472. /** Releases all resources */
  60473. PhysicsViewer.prototype.dispose = function () {
  60474. for (var i = 0; i < this._numMeshes; i++) {
  60475. this.hideImpostor(this._impostors[i]);
  60476. }
  60477. if (this._debugBoxMesh) {
  60478. this._debugBoxMesh.dispose();
  60479. }
  60480. if (this._debugSphereMesh) {
  60481. this._debugSphereMesh.dispose();
  60482. }
  60483. if (this._debugMaterial) {
  60484. this._debugMaterial.dispose();
  60485. }
  60486. this._impostors.length = 0;
  60487. this._scene = null;
  60488. this._physicsEnginePlugin = null;
  60489. };
  60490. return PhysicsViewer;
  60491. }());
  60492. Debug.PhysicsViewer = PhysicsViewer;
  60493. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60494. })(BABYLON || (BABYLON = {}));
  60495. //# sourceMappingURL=babylon.physicsViewer.js.map
  60496. var BABYLON;
  60497. (function (BABYLON) {
  60498. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  60499. get: function () {
  60500. return this._forceShowBoundingBoxes || false;
  60501. },
  60502. set: function (value) {
  60503. this._forceShowBoundingBoxes = value;
  60504. // Lazyly creates a BB renderer if needed.
  60505. if (value) {
  60506. this.getBoundingBoxRenderer();
  60507. }
  60508. },
  60509. enumerable: true,
  60510. configurable: true
  60511. });
  60512. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  60513. if (!this._boundingBoxRenderer) {
  60514. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  60515. }
  60516. return this._boundingBoxRenderer;
  60517. };
  60518. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  60519. get: function () {
  60520. return this._showBoundingBox || false;
  60521. },
  60522. set: function (value) {
  60523. this._showBoundingBox = value;
  60524. // Lazyly creates a BB renderer if needed.
  60525. if (value) {
  60526. this.getScene().getBoundingBoxRenderer();
  60527. }
  60528. },
  60529. enumerable: true,
  60530. configurable: true
  60531. });
  60532. var BoundingBoxRenderer = /** @class */ (function () {
  60533. function BoundingBoxRenderer(scene) {
  60534. /**
  60535. * The component name helpfull to identify the component in the list of scene components.
  60536. */
  60537. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  60538. this.frontColor = new BABYLON.Color3(1, 1, 1);
  60539. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  60540. this.showBackLines = true;
  60541. this.renderList = new BABYLON.SmartArray(32);
  60542. this._vertexBuffers = {};
  60543. this.scene = scene;
  60544. scene._addComponent(this);
  60545. }
  60546. /**
  60547. * Registers the component in a given scene
  60548. */
  60549. BoundingBoxRenderer.prototype.register = function () {
  60550. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  60551. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  60552. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  60553. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  60554. };
  60555. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  60556. if (mesh.showSubMeshesBoundingBox) {
  60557. var boundingInfo = subMesh.getBoundingInfo();
  60558. if (boundingInfo !== null && boundingInfo !== undefined) {
  60559. this.renderList.push(boundingInfo.boundingBox);
  60560. }
  60561. }
  60562. };
  60563. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  60564. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  60565. var boundingInfo = sourceMesh.getBoundingInfo();
  60566. this.renderList.push(boundingInfo.boundingBox);
  60567. }
  60568. };
  60569. BoundingBoxRenderer.prototype._prepareRessources = function () {
  60570. if (this._colorShader) {
  60571. return;
  60572. }
  60573. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  60574. attributes: [BABYLON.VertexBuffer.PositionKind],
  60575. uniforms: ["world", "viewProjection", "color"]
  60576. });
  60577. var engine = this.scene.getEngine();
  60578. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  60579. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  60580. this._createIndexBuffer();
  60581. };
  60582. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  60583. var engine = this.scene.getEngine();
  60584. 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]);
  60585. };
  60586. /**
  60587. * Rebuilds the elements related to this component in case of
  60588. * context lost for instance.
  60589. */
  60590. BoundingBoxRenderer.prototype.rebuild = function () {
  60591. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60592. if (vb) {
  60593. vb._rebuild();
  60594. }
  60595. this._createIndexBuffer();
  60596. };
  60597. BoundingBoxRenderer.prototype.reset = function () {
  60598. this.renderList.reset();
  60599. };
  60600. BoundingBoxRenderer.prototype.render = function () {
  60601. if (this.renderList.length === 0) {
  60602. return;
  60603. }
  60604. this._prepareRessources();
  60605. if (!this._colorShader.isReady()) {
  60606. return;
  60607. }
  60608. var engine = this.scene.getEngine();
  60609. engine.setDepthWrite(false);
  60610. this._colorShader._preBind();
  60611. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  60612. var boundingBox = this.renderList.data[boundingBoxIndex];
  60613. var min = boundingBox.minimum;
  60614. var max = boundingBox.maximum;
  60615. var diff = max.subtract(min);
  60616. var median = min.add(diff.scale(0.5));
  60617. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60618. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60619. .multiply(boundingBox.getWorldMatrix());
  60620. // VBOs
  60621. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60622. if (this.showBackLines) {
  60623. // Back
  60624. engine.setDepthFunctionToGreaterOrEqual();
  60625. this.scene.resetCachedMaterial();
  60626. this._colorShader.setColor4("color", this.backColor.toColor4());
  60627. this._colorShader.bind(worldMatrix);
  60628. // Draw order
  60629. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60630. }
  60631. // Front
  60632. engine.setDepthFunctionToLess();
  60633. this.scene.resetCachedMaterial();
  60634. this._colorShader.setColor4("color", this.frontColor.toColor4());
  60635. this._colorShader.bind(worldMatrix);
  60636. // Draw order
  60637. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60638. }
  60639. this._colorShader.unbind();
  60640. engine.setDepthFunctionToLessOrEqual();
  60641. engine.setDepthWrite(true);
  60642. };
  60643. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  60644. this._prepareRessources();
  60645. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  60646. return;
  60647. }
  60648. var engine = this.scene.getEngine();
  60649. engine.setDepthWrite(false);
  60650. engine.setColorWrite(false);
  60651. this._colorShader._preBind();
  60652. var boundingBox = mesh._boundingInfo.boundingBox;
  60653. var min = boundingBox.minimum;
  60654. var max = boundingBox.maximum;
  60655. var diff = max.subtract(min);
  60656. var median = min.add(diff.scale(0.5));
  60657. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60658. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60659. .multiply(boundingBox.getWorldMatrix());
  60660. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60661. engine.setDepthFunctionToLess();
  60662. this.scene.resetCachedMaterial();
  60663. this._colorShader.bind(worldMatrix);
  60664. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60665. this._colorShader.unbind();
  60666. engine.setDepthFunctionToLessOrEqual();
  60667. engine.setDepthWrite(true);
  60668. engine.setColorWrite(true);
  60669. };
  60670. BoundingBoxRenderer.prototype.dispose = function () {
  60671. if (!this._colorShader) {
  60672. return;
  60673. }
  60674. this.renderList.dispose();
  60675. this._colorShader.dispose();
  60676. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60677. if (buffer) {
  60678. buffer.dispose();
  60679. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60680. }
  60681. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  60682. };
  60683. return BoundingBoxRenderer;
  60684. }());
  60685. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  60686. })(BABYLON || (BABYLON = {}));
  60687. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  60688. var BABYLON;
  60689. (function (BABYLON) {
  60690. BABYLON.Engine.prototype.createTransformFeedback = function () {
  60691. return this._gl.createTransformFeedback();
  60692. };
  60693. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  60694. this._gl.deleteTransformFeedback(value);
  60695. };
  60696. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  60697. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  60698. };
  60699. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  60700. if (usePoints === void 0) { usePoints = true; }
  60701. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  60702. };
  60703. BABYLON.Engine.prototype.endTransformFeedback = function () {
  60704. this._gl.endTransformFeedback();
  60705. };
  60706. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  60707. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  60708. };
  60709. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  60710. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  60711. };
  60712. })(BABYLON || (BABYLON = {}));
  60713. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  60714. var BABYLON;
  60715. (function (BABYLON) {
  60716. /**
  60717. * This represents a GPU particle system in Babylon
  60718. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  60719. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  60720. */
  60721. var GPUParticleSystem = /** @class */ (function (_super) {
  60722. __extends(GPUParticleSystem, _super);
  60723. /**
  60724. * Instantiates a GPU particle system.
  60725. * 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.
  60726. * @param name The name of the particle system
  60727. * @param options The options used to create the system
  60728. * @param scene The scene the particle system belongs to
  60729. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60730. */
  60731. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  60732. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60733. var _this = _super.call(this, name) || this;
  60734. /**
  60735. * The layer mask we are rendering the particles through.
  60736. */
  60737. _this.layerMask = 0x0FFFFFFF;
  60738. _this._accumulatedCount = 0;
  60739. _this._targetIndex = 0;
  60740. _this._currentRenderId = -1;
  60741. _this._started = false;
  60742. _this._stopped = false;
  60743. _this._timeDelta = 0;
  60744. _this._attributesStrideSize = 21;
  60745. _this._actualFrame = 0;
  60746. _this._rawTextureWidth = 256;
  60747. /**
  60748. * An event triggered when the system is disposed.
  60749. */
  60750. _this.onDisposeObservable = new BABYLON.Observable();
  60751. /**
  60752. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  60753. * to override the particles.
  60754. */
  60755. _this.forceDepthWrite = false;
  60756. _this._preWarmDone = false;
  60757. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60758. // Setup the default processing configuration to the scene.
  60759. _this._attachImageProcessingConfiguration(null);
  60760. _this._engine = _this._scene.getEngine();
  60761. if (!options.randomTextureSize) {
  60762. delete options.randomTextureSize;
  60763. }
  60764. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  60765. var optionsAsNumber = options;
  60766. if (isFinite(optionsAsNumber)) {
  60767. fullOptions.capacity = optionsAsNumber;
  60768. }
  60769. _this._capacity = fullOptions.capacity;
  60770. _this._activeCount = fullOptions.capacity;
  60771. _this._currentActiveCount = 0;
  60772. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60773. _this._scene.particleSystems.push(_this);
  60774. _this._updateEffectOptions = {
  60775. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  60776. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  60777. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  60778. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  60779. uniformBuffersNames: [],
  60780. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  60781. defines: "",
  60782. fallbacks: null,
  60783. onCompiled: null,
  60784. onError: null,
  60785. indexParameters: null,
  60786. maxSimultaneousLights: 0,
  60787. transformFeedbackVaryings: []
  60788. };
  60789. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60790. // Random data
  60791. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  60792. var d = [];
  60793. for (var i = 0; i < maxTextureSize; ++i) {
  60794. d.push(Math.random());
  60795. d.push(Math.random());
  60796. d.push(Math.random());
  60797. d.push(Math.random());
  60798. }
  60799. _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);
  60800. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60801. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60802. d = [];
  60803. for (var i = 0; i < maxTextureSize; ++i) {
  60804. d.push(Math.random());
  60805. d.push(Math.random());
  60806. d.push(Math.random());
  60807. d.push(Math.random());
  60808. }
  60809. _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);
  60810. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60811. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60812. _this._randomTextureSize = maxTextureSize;
  60813. return _this;
  60814. }
  60815. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  60816. /**
  60817. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  60818. */
  60819. get: function () {
  60820. if (!BABYLON.Engine.LastCreatedEngine) {
  60821. return false;
  60822. }
  60823. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  60824. },
  60825. enumerable: true,
  60826. configurable: true
  60827. });
  60828. /**
  60829. * Gets the maximum number of particles active at the same time.
  60830. * @returns The max number of active particles.
  60831. */
  60832. GPUParticleSystem.prototype.getCapacity = function () {
  60833. return this._capacity;
  60834. };
  60835. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  60836. /**
  60837. * Gets or set the number of active particles
  60838. */
  60839. get: function () {
  60840. return this._activeCount;
  60841. },
  60842. set: function (value) {
  60843. this._activeCount = Math.min(value, this._capacity);
  60844. },
  60845. enumerable: true,
  60846. configurable: true
  60847. });
  60848. /**
  60849. * Is this system ready to be used/rendered
  60850. * @return true if the system is ready
  60851. */
  60852. GPUParticleSystem.prototype.isReady = function () {
  60853. if (!this._updateEffect) {
  60854. this._recreateUpdateEffect();
  60855. this._recreateRenderEffect();
  60856. return false;
  60857. }
  60858. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60859. return false;
  60860. }
  60861. return true;
  60862. };
  60863. /**
  60864. * Gets Wether the system has been started.
  60865. * @returns True if it has been started, otherwise false.
  60866. */
  60867. GPUParticleSystem.prototype.isStarted = function () {
  60868. return this._started;
  60869. };
  60870. /**
  60871. * Starts the particle system and begins to emit
  60872. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  60873. */
  60874. GPUParticleSystem.prototype.start = function (delay) {
  60875. var _this = this;
  60876. if (delay === void 0) { delay = 0; }
  60877. if (delay) {
  60878. setTimeout(function () {
  60879. _this.start(0);
  60880. }, delay);
  60881. return;
  60882. }
  60883. this._started = true;
  60884. this._stopped = false;
  60885. this._preWarmDone = false;
  60886. };
  60887. /**
  60888. * Stops the particle system.
  60889. */
  60890. GPUParticleSystem.prototype.stop = function () {
  60891. this._stopped = true;
  60892. };
  60893. /**
  60894. * Remove all active particles
  60895. */
  60896. GPUParticleSystem.prototype.reset = function () {
  60897. this._releaseBuffers();
  60898. this._releaseVAOs();
  60899. this._currentActiveCount = 0;
  60900. this._targetIndex = 0;
  60901. };
  60902. /**
  60903. * Returns the string "GPUParticleSystem"
  60904. * @returns a string containing the class name
  60905. */
  60906. GPUParticleSystem.prototype.getClassName = function () {
  60907. return "GPUParticleSystem";
  60908. };
  60909. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  60910. if (!gradients) {
  60911. return this;
  60912. }
  60913. var index = 0;
  60914. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60915. var valueGradient = gradients_1[_i];
  60916. if (valueGradient.gradient === gradient) {
  60917. gradients.splice(index, 1);
  60918. break;
  60919. }
  60920. index++;
  60921. }
  60922. if (texture) {
  60923. texture.dispose();
  60924. }
  60925. this._releaseBuffers();
  60926. return this;
  60927. };
  60928. /**
  60929. * Adds a new color gradient
  60930. * @param gradient defines the gradient to use (between 0 and 1)
  60931. * @param color defines the color to affect to the specified gradient
  60932. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  60933. * @returns the current particle system
  60934. */
  60935. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  60936. if (!this._colorGradients) {
  60937. this._colorGradients = [];
  60938. }
  60939. var colorGradient = new BABYLON.ColorGradient();
  60940. colorGradient.gradient = gradient;
  60941. colorGradient.color1 = color1;
  60942. this._colorGradients.push(colorGradient);
  60943. this._colorGradients.sort(function (a, b) {
  60944. if (a.gradient < b.gradient) {
  60945. return -1;
  60946. }
  60947. else if (a.gradient > b.gradient) {
  60948. return 1;
  60949. }
  60950. return 0;
  60951. });
  60952. if (this._colorGradientsTexture) {
  60953. this._colorGradientsTexture.dispose();
  60954. this._colorGradientsTexture = null;
  60955. }
  60956. this._releaseBuffers();
  60957. return this;
  60958. };
  60959. /**
  60960. * Remove a specific color gradient
  60961. * @param gradient defines the gradient to remove
  60962. * @returns the current particle system
  60963. */
  60964. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  60965. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  60966. this._colorGradientsTexture = null;
  60967. return this;
  60968. };
  60969. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  60970. var valueGradient = new BABYLON.FactorGradient();
  60971. valueGradient.gradient = gradient;
  60972. valueGradient.factor1 = factor;
  60973. factorGradients.push(valueGradient);
  60974. factorGradients.sort(function (a, b) {
  60975. if (a.gradient < b.gradient) {
  60976. return -1;
  60977. }
  60978. else if (a.gradient > b.gradient) {
  60979. return 1;
  60980. }
  60981. return 0;
  60982. });
  60983. this._releaseBuffers();
  60984. };
  60985. /**
  60986. * Adds a new size gradient
  60987. * @param gradient defines the gradient to use (between 0 and 1)
  60988. * @param factor defines the size factor to affect to the specified gradient
  60989. * @returns the current particle system
  60990. */
  60991. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  60992. if (!this._sizeGradients) {
  60993. this._sizeGradients = [];
  60994. }
  60995. this._addFactorGradient(this._sizeGradients, gradient, factor);
  60996. if (this._sizeGradientsTexture) {
  60997. this._sizeGradientsTexture.dispose();
  60998. this._sizeGradientsTexture = null;
  60999. }
  61000. this._releaseBuffers();
  61001. return this;
  61002. };
  61003. /**
  61004. * Remove a specific size gradient
  61005. * @param gradient defines the gradient to remove
  61006. * @returns the current particle system
  61007. */
  61008. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61009. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61010. this._sizeGradientsTexture = null;
  61011. return this;
  61012. };
  61013. /**
  61014. * Adds a new angular speed gradient
  61015. * @param gradient defines the gradient to use (between 0 and 1)
  61016. * @param factor defines the angular speed to affect to the specified gradient
  61017. * @returns the current particle system
  61018. */
  61019. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61020. if (!this._angularSpeedGradients) {
  61021. this._angularSpeedGradients = [];
  61022. }
  61023. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61024. if (this._angularSpeedGradientsTexture) {
  61025. this._angularSpeedGradientsTexture.dispose();
  61026. this._angularSpeedGradientsTexture = null;
  61027. }
  61028. this._releaseBuffers();
  61029. return this;
  61030. };
  61031. /**
  61032. * Remove a specific angular speed gradient
  61033. * @param gradient defines the gradient to remove
  61034. * @returns the current particle system
  61035. */
  61036. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61037. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61038. this._angularSpeedGradientsTexture = null;
  61039. return this;
  61040. };
  61041. /**
  61042. * Adds a new velocity gradient
  61043. * @param gradient defines the gradient to use (between 0 and 1)
  61044. * @param factor defines the velocity to affect to the specified gradient
  61045. * @returns the current particle system
  61046. */
  61047. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61048. if (!this._velocityGradients) {
  61049. this._velocityGradients = [];
  61050. }
  61051. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61052. if (this._velocityGradientsTexture) {
  61053. this._velocityGradientsTexture.dispose();
  61054. this._velocityGradientsTexture = null;
  61055. }
  61056. this._releaseBuffers();
  61057. return this;
  61058. };
  61059. /**
  61060. * Remove a specific velocity gradient
  61061. * @param gradient defines the gradient to remove
  61062. * @returns the current particle system
  61063. */
  61064. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61065. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61066. this._velocityGradientsTexture = null;
  61067. return this;
  61068. };
  61069. /**
  61070. * Adds a new limit velocity gradient
  61071. * @param gradient defines the gradient to use (between 0 and 1)
  61072. * @param factor defines the limit velocity value to affect to the specified gradient
  61073. * @returns the current particle system
  61074. */
  61075. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  61076. if (!this._limitVelocityGradients) {
  61077. this._limitVelocityGradients = [];
  61078. }
  61079. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  61080. if (this._limitVelocityGradientsTexture) {
  61081. this._limitVelocityGradientsTexture.dispose();
  61082. this._limitVelocityGradientsTexture = null;
  61083. }
  61084. this._releaseBuffers();
  61085. return this;
  61086. };
  61087. /**
  61088. * Remove a specific limit velocity gradient
  61089. * @param gradient defines the gradient to remove
  61090. * @returns the current particle system
  61091. */
  61092. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61093. this._removeGradient(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  61094. this._limitVelocityGradientsTexture = null;
  61095. return this;
  61096. };
  61097. /**
  61098. * Adds a new drag gradient
  61099. * @param gradient defines the gradient to use (between 0 and 1)
  61100. * @param factor defines the drag value to affect to the specified gradient
  61101. * @returns the current particle system
  61102. */
  61103. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  61104. if (!this._dragGradients) {
  61105. this._dragGradients = [];
  61106. }
  61107. this._addFactorGradient(this._dragGradients, gradient, factor);
  61108. if (this._dragGradientsTexture) {
  61109. this._dragGradientsTexture.dispose();
  61110. this._dragGradientsTexture = null;
  61111. }
  61112. this._releaseBuffers();
  61113. return this;
  61114. };
  61115. /**
  61116. * Remove a specific drag gradient
  61117. * @param gradient defines the gradient to remove
  61118. * @returns the current particle system
  61119. */
  61120. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  61121. this._removeGradient(gradient, this._dragGradients, this._dragGradientsTexture);
  61122. this._dragGradientsTexture = null;
  61123. return this;
  61124. };
  61125. GPUParticleSystem.prototype._reset = function () {
  61126. this._releaseBuffers();
  61127. };
  61128. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  61129. var updateVertexBuffers = {};
  61130. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  61131. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  61132. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  61133. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  61134. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  61135. var offset = 12;
  61136. if (!this._colorGradientsTexture) {
  61137. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  61138. offset += 4;
  61139. }
  61140. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  61141. offset += 3;
  61142. if (!this._isBillboardBased) {
  61143. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  61144. offset += 3;
  61145. }
  61146. if (this._angularSpeedGradientsTexture) {
  61147. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  61148. offset += 1;
  61149. }
  61150. else {
  61151. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  61152. offset += 2;
  61153. }
  61154. if (this._isAnimationSheetEnabled) {
  61155. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  61156. offset += 1;
  61157. }
  61158. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  61159. this._engine.bindArrayBuffer(null);
  61160. return vao;
  61161. };
  61162. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  61163. var renderVertexBuffers = {};
  61164. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  61165. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  61166. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  61167. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  61168. var offset = 12;
  61169. if (!this._colorGradientsTexture) {
  61170. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  61171. offset += 4;
  61172. }
  61173. offset += 3; // Direction
  61174. if (!this._isBillboardBased) {
  61175. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  61176. offset += 3;
  61177. }
  61178. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  61179. if (this._angularSpeedGradientsTexture) {
  61180. offset++;
  61181. }
  61182. else {
  61183. offset += 2;
  61184. }
  61185. if (this._isAnimationSheetEnabled) {
  61186. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  61187. offset += 1;
  61188. }
  61189. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  61190. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  61191. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  61192. this._engine.bindArrayBuffer(null);
  61193. return vao;
  61194. };
  61195. GPUParticleSystem.prototype._initialize = function (force) {
  61196. if (force === void 0) { force = false; }
  61197. if (this._buffer0 && !force) {
  61198. return;
  61199. }
  61200. var engine = this._scene.getEngine();
  61201. var data = new Array();
  61202. if (!this.isBillboardBased) {
  61203. this._attributesStrideSize += 3;
  61204. }
  61205. if (this._colorGradientsTexture) {
  61206. this._attributesStrideSize -= 4;
  61207. }
  61208. if (this._angularSpeedGradientsTexture) {
  61209. this._attributesStrideSize -= 1;
  61210. }
  61211. if (this._isAnimationSheetEnabled) {
  61212. this._attributesStrideSize += 1;
  61213. }
  61214. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  61215. // position
  61216. data.push(0.0);
  61217. data.push(0.0);
  61218. data.push(0.0);
  61219. // Age and life
  61220. data.push(0.0); // create the particle as a dead one to create a new one at start
  61221. data.push(0.0);
  61222. // Seed
  61223. data.push(Math.random());
  61224. data.push(Math.random());
  61225. data.push(Math.random());
  61226. data.push(Math.random());
  61227. // Size
  61228. data.push(0.0);
  61229. data.push(0.0);
  61230. data.push(0.0);
  61231. if (!this._colorGradientsTexture) {
  61232. // color
  61233. data.push(0.0);
  61234. data.push(0.0);
  61235. data.push(0.0);
  61236. data.push(0.0);
  61237. }
  61238. // direction
  61239. data.push(0.0);
  61240. data.push(0.0);
  61241. data.push(0.0);
  61242. if (!this.isBillboardBased) {
  61243. // initialDirection
  61244. data.push(0.0);
  61245. data.push(0.0);
  61246. data.push(0.0);
  61247. }
  61248. // angle
  61249. data.push(0.0);
  61250. if (!this._angularSpeedGradientsTexture) {
  61251. data.push(0.0);
  61252. }
  61253. if (this._isAnimationSheetEnabled) {
  61254. data.push(0.0);
  61255. }
  61256. }
  61257. // Sprite data
  61258. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  61259. -0.5, 0.5, 0, 1,
  61260. -0.5, -0.5, 0, 0,
  61261. 0.5, -0.5, 1, 0]);
  61262. // Buffers
  61263. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61264. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61265. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  61266. // Update VAO
  61267. this._updateVAO = [];
  61268. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  61269. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  61270. // Render VAO
  61271. this._renderVAO = [];
  61272. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  61273. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  61274. // Links
  61275. this._sourceBuffer = this._buffer0;
  61276. this._targetBuffer = this._buffer1;
  61277. };
  61278. /** @hidden */
  61279. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  61280. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  61281. if (this._isBillboardBased) {
  61282. defines += "\n#define BILLBOARD";
  61283. }
  61284. if (this._colorGradientsTexture) {
  61285. defines += "\n#define COLORGRADIENTS";
  61286. }
  61287. if (this._sizeGradientsTexture) {
  61288. defines += "\n#define SIZEGRADIENTS";
  61289. }
  61290. if (this._angularSpeedGradientsTexture) {
  61291. defines += "\n#define ANGULARSPEEDGRADIENTS";
  61292. }
  61293. if (this._velocityGradientsTexture) {
  61294. defines += "\n#define VELOCITYGRADIENTS";
  61295. }
  61296. if (this.isAnimationSheetEnabled) {
  61297. defines += "\n#define ANIMATESHEET";
  61298. }
  61299. if (this.noiseTexture) {
  61300. defines += "\n#define NOISE";
  61301. }
  61302. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  61303. return;
  61304. }
  61305. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  61306. if (!this._colorGradientsTexture) {
  61307. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  61308. }
  61309. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  61310. if (!this._isBillboardBased) {
  61311. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  61312. }
  61313. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  61314. if (this.isAnimationSheetEnabled) {
  61315. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  61316. }
  61317. this._updateEffectOptions.defines = defines;
  61318. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  61319. };
  61320. /** @hidden */
  61321. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  61322. var defines = "";
  61323. if (this._scene.clipPlane) {
  61324. defines = "\n#define CLIPPLANE";
  61325. }
  61326. if (this._scene.clipPlane2) {
  61327. defines = "\n#define CLIPPLANE2";
  61328. }
  61329. if (this._scene.clipPlane3) {
  61330. defines = "\n#define CLIPPLANE3";
  61331. }
  61332. if (this._scene.clipPlane4) {
  61333. defines = "\n#define CLIPPLANE4";
  61334. }
  61335. if (this._isBillboardBased) {
  61336. defines += "\n#define BILLBOARD";
  61337. switch (this.billboardMode) {
  61338. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  61339. defines += "\n#define BILLBOARDY";
  61340. break;
  61341. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  61342. default:
  61343. break;
  61344. }
  61345. }
  61346. if (this._colorGradientsTexture) {
  61347. defines += "\n#define COLORGRADIENTS";
  61348. }
  61349. if (this.isAnimationSheetEnabled) {
  61350. defines += "\n#define ANIMATESHEET";
  61351. }
  61352. if (this._imageProcessingConfiguration) {
  61353. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  61354. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  61355. }
  61356. if (this._renderEffect && this._renderEffect.defines === defines) {
  61357. return;
  61358. }
  61359. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  61360. var samplers = ["textureSampler", "colorGradientSampler"];
  61361. if (BABYLON.ImageProcessingConfiguration) {
  61362. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  61363. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  61364. }
  61365. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  61366. };
  61367. /**
  61368. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  61369. * @param preWarm defines if we are in the pre-warmimg phase
  61370. */
  61371. GPUParticleSystem.prototype.animate = function (preWarm) {
  61372. if (preWarm === void 0) { preWarm = false; }
  61373. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  61374. this._actualFrame += this._timeDelta;
  61375. if (!this._stopped) {
  61376. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  61377. this.stop();
  61378. }
  61379. }
  61380. };
  61381. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  61382. var texture = this[textureName];
  61383. if (!factorGradients || !factorGradients.length || texture) {
  61384. return;
  61385. }
  61386. var data = new Float32Array(this._rawTextureWidth);
  61387. for (var x = 0; x < this._rawTextureWidth; x++) {
  61388. var ratio = x / this._rawTextureWidth;
  61389. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  61390. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  61391. });
  61392. }
  61393. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61394. };
  61395. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  61396. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  61397. };
  61398. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  61399. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  61400. };
  61401. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  61402. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  61403. };
  61404. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  61405. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  61406. return;
  61407. }
  61408. var data = new Uint8Array(this._rawTextureWidth * 4);
  61409. var tmpColor = BABYLON.Tmp.Color4[0];
  61410. for (var x = 0; x < this._rawTextureWidth; x++) {
  61411. var ratio = x / this._rawTextureWidth;
  61412. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  61413. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  61414. data[x * 4] = tmpColor.r * 255;
  61415. data[x * 4 + 1] = tmpColor.g * 255;
  61416. data[x * 4 + 2] = tmpColor.b * 255;
  61417. data[x * 4 + 3] = tmpColor.a * 255;
  61418. });
  61419. }
  61420. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61421. };
  61422. /**
  61423. * Renders the particle system in its current state
  61424. * @param preWarm defines if the system should only update the particles but not render them
  61425. * @returns the current number of particles
  61426. */
  61427. GPUParticleSystem.prototype.render = function (preWarm) {
  61428. if (preWarm === void 0) { preWarm = false; }
  61429. if (!this._started) {
  61430. return 0;
  61431. }
  61432. this._createColorGradientTexture();
  61433. this._createSizeGradientTexture();
  61434. this._createAngularSpeedGradientTexture();
  61435. this._createVelocityGradientTexture();
  61436. this._recreateUpdateEffect();
  61437. this._recreateRenderEffect();
  61438. if (!this.isReady()) {
  61439. return 0;
  61440. }
  61441. if (!preWarm) {
  61442. if (!this._preWarmDone && this.preWarmCycles) {
  61443. for (var index = 0; index < this.preWarmCycles; index++) {
  61444. this.animate(true);
  61445. this.render(true);
  61446. }
  61447. this._preWarmDone = true;
  61448. }
  61449. if (this._currentRenderId === this._scene.getRenderId()) {
  61450. return 0;
  61451. }
  61452. this._currentRenderId = this._scene.getRenderId();
  61453. }
  61454. // Get everything ready to render
  61455. this._initialize();
  61456. this._accumulatedCount += this.emitRate * this._timeDelta;
  61457. if (this._accumulatedCount > 1) {
  61458. var intPart = this._accumulatedCount | 0;
  61459. this._accumulatedCount -= intPart;
  61460. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  61461. }
  61462. if (!this._currentActiveCount) {
  61463. return 0;
  61464. }
  61465. // Enable update effect
  61466. this._engine.enableEffect(this._updateEffect);
  61467. this._engine.setState(false);
  61468. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  61469. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  61470. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  61471. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  61472. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  61473. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  61474. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  61475. if (!this._colorGradientsTexture) {
  61476. this._updateEffect.setDirectColor4("color1", this.color1);
  61477. this._updateEffect.setDirectColor4("color2", this.color2);
  61478. }
  61479. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  61480. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  61481. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  61482. this._updateEffect.setVector3("gravity", this.gravity);
  61483. if (this._sizeGradientsTexture) {
  61484. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  61485. }
  61486. if (this._angularSpeedGradientsTexture) {
  61487. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  61488. }
  61489. if (this._velocityGradientsTexture) {
  61490. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  61491. }
  61492. if (this.particleEmitterType) {
  61493. this.particleEmitterType.applyToShader(this._updateEffect);
  61494. }
  61495. if (this._isAnimationSheetEnabled) {
  61496. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  61497. }
  61498. if (this.noiseTexture) {
  61499. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  61500. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  61501. }
  61502. var emitterWM;
  61503. if (this.emitter.position) {
  61504. var emitterMesh = this.emitter;
  61505. emitterWM = emitterMesh.getWorldMatrix();
  61506. }
  61507. else {
  61508. var emitterPosition = this.emitter;
  61509. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  61510. }
  61511. this._updateEffect.setMatrix("emitterWM", emitterWM);
  61512. // Bind source VAO
  61513. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  61514. // Update
  61515. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  61516. this._engine.setRasterizerState(false);
  61517. this._engine.beginTransformFeedback(true);
  61518. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  61519. this._engine.endTransformFeedback();
  61520. this._engine.setRasterizerState(true);
  61521. this._engine.bindTransformFeedbackBuffer(null);
  61522. if (!preWarm) {
  61523. // Enable render effect
  61524. this._engine.enableEffect(this._renderEffect);
  61525. var viewMatrix = this._scene.getViewMatrix();
  61526. this._renderEffect.setMatrix("view", viewMatrix);
  61527. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  61528. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  61529. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  61530. if (this._colorGradientsTexture) {
  61531. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  61532. }
  61533. else {
  61534. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  61535. }
  61536. if (this._isAnimationSheetEnabled && this.particleTexture) {
  61537. var baseSize = this.particleTexture.getBaseSize();
  61538. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  61539. }
  61540. if (this._isBillboardBased) {
  61541. var camera = this._scene.activeCamera;
  61542. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  61543. }
  61544. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  61545. var invView = viewMatrix.clone();
  61546. invView.invert();
  61547. this._renderEffect.setMatrix("invView", invView);
  61548. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  61549. }
  61550. // image processing
  61551. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  61552. this._imageProcessingConfiguration.bind(this._renderEffect);
  61553. }
  61554. // Draw order
  61555. switch (this.blendMode) {
  61556. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  61557. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  61558. break;
  61559. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  61560. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  61561. break;
  61562. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  61563. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61564. break;
  61565. }
  61566. if (this.forceDepthWrite) {
  61567. this._engine.setDepthWrite(true);
  61568. }
  61569. // Bind source VAO
  61570. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  61571. // Render
  61572. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  61573. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61574. }
  61575. // Switch VAOs
  61576. this._targetIndex++;
  61577. if (this._targetIndex === 2) {
  61578. this._targetIndex = 0;
  61579. }
  61580. // Switch buffers
  61581. var tmpBuffer = this._sourceBuffer;
  61582. this._sourceBuffer = this._targetBuffer;
  61583. this._targetBuffer = tmpBuffer;
  61584. return this._currentActiveCount;
  61585. };
  61586. /**
  61587. * Rebuilds the particle system
  61588. */
  61589. GPUParticleSystem.prototype.rebuild = function () {
  61590. this._initialize(true);
  61591. };
  61592. GPUParticleSystem.prototype._releaseBuffers = function () {
  61593. if (this._buffer0) {
  61594. this._buffer0.dispose();
  61595. this._buffer0 = null;
  61596. }
  61597. if (this._buffer1) {
  61598. this._buffer1.dispose();
  61599. this._buffer1 = null;
  61600. }
  61601. if (this._spriteBuffer) {
  61602. this._spriteBuffer.dispose();
  61603. this._spriteBuffer = null;
  61604. }
  61605. };
  61606. GPUParticleSystem.prototype._releaseVAOs = function () {
  61607. if (!this._updateVAO) {
  61608. return;
  61609. }
  61610. for (var index = 0; index < this._updateVAO.length; index++) {
  61611. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  61612. }
  61613. this._updateVAO = [];
  61614. for (var index = 0; index < this._renderVAO.length; index++) {
  61615. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  61616. }
  61617. this._renderVAO = [];
  61618. };
  61619. /**
  61620. * Disposes the particle system and free the associated resources
  61621. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  61622. */
  61623. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  61624. if (disposeTexture === void 0) { disposeTexture = true; }
  61625. var index = this._scene.particleSystems.indexOf(this);
  61626. if (index > -1) {
  61627. this._scene.particleSystems.splice(index, 1);
  61628. }
  61629. this._releaseBuffers();
  61630. this._releaseVAOs();
  61631. if (this._colorGradientsTexture) {
  61632. this._colorGradientsTexture.dispose();
  61633. this._colorGradientsTexture = null;
  61634. }
  61635. if (this._sizeGradientsTexture) {
  61636. this._sizeGradientsTexture.dispose();
  61637. this._sizeGradientsTexture = null;
  61638. }
  61639. if (this._angularSpeedGradientsTexture) {
  61640. this._angularSpeedGradientsTexture.dispose();
  61641. this._angularSpeedGradientsTexture = null;
  61642. }
  61643. if (this._velocityGradientsTexture) {
  61644. this._velocityGradientsTexture.dispose();
  61645. this._velocityGradientsTexture = null;
  61646. }
  61647. if (this._limitVelocityGradientsTexture) {
  61648. this._limitVelocityGradientsTexture.dispose();
  61649. this._limitVelocityGradientsTexture = null;
  61650. }
  61651. if (this._randomTexture) {
  61652. this._randomTexture.dispose();
  61653. this._randomTexture = null;
  61654. }
  61655. if (this._randomTexture2) {
  61656. this._randomTexture2.dispose();
  61657. this._randomTexture2 = null;
  61658. }
  61659. if (disposeTexture && this.particleTexture) {
  61660. this.particleTexture.dispose();
  61661. this.particleTexture = null;
  61662. }
  61663. if (disposeTexture && this.noiseTexture) {
  61664. this.noiseTexture.dispose();
  61665. this.noiseTexture = null;
  61666. }
  61667. // Callback
  61668. this.onDisposeObservable.notifyObservers(this);
  61669. this.onDisposeObservable.clear();
  61670. };
  61671. /**
  61672. * Clones the particle system.
  61673. * @param name The name of the cloned object
  61674. * @param newEmitter The new emitter to use
  61675. * @returns the cloned particle system
  61676. */
  61677. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  61678. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  61679. BABYLON.Tools.DeepCopy(this, result);
  61680. if (newEmitter === undefined) {
  61681. newEmitter = this.emitter;
  61682. }
  61683. result.emitter = newEmitter;
  61684. if (this.particleTexture) {
  61685. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  61686. }
  61687. return result;
  61688. };
  61689. /**
  61690. * Serializes the particle system to a JSON object.
  61691. * @returns the JSON object
  61692. */
  61693. GPUParticleSystem.prototype.serialize = function () {
  61694. var serializationObject = {};
  61695. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  61696. serializationObject.activeParticleCount = this.activeParticleCount;
  61697. return serializationObject;
  61698. };
  61699. /**
  61700. * Parses a JSON object to create a GPU particle system.
  61701. * @param parsedParticleSystem The JSON object to parse
  61702. * @param scene The scene to create the particle system in
  61703. * @param rootUrl The root url to use to load external dependencies like texture
  61704. * @returns the parsed GPU particle system
  61705. */
  61706. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  61707. var name = parsedParticleSystem.name;
  61708. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  61709. if (parsedParticleSystem.activeParticleCount) {
  61710. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  61711. }
  61712. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61713. return particleSystem;
  61714. };
  61715. return GPUParticleSystem;
  61716. }(BABYLON.BaseParticleSystem));
  61717. BABYLON.GPUParticleSystem = GPUParticleSystem;
  61718. })(BABYLON || (BABYLON = {}));
  61719. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  61720. var BABYLON;
  61721. (function (BABYLON) {
  61722. /**
  61723. * Represents one particle of a solid particle system.
  61724. */
  61725. var SolidParticle = /** @class */ (function () {
  61726. /**
  61727. * Creates a Solid Particle object.
  61728. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  61729. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  61730. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  61731. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  61732. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  61733. * @param shapeId (integer) is the model shape identifier in the SPS.
  61734. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  61735. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  61736. */
  61737. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  61738. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  61739. /**
  61740. * particle global index
  61741. */
  61742. this.idx = 0;
  61743. /**
  61744. * The color of the particle
  61745. */
  61746. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61747. /**
  61748. * The world space position of the particle.
  61749. */
  61750. this.position = BABYLON.Vector3.Zero();
  61751. /**
  61752. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  61753. */
  61754. this.rotation = BABYLON.Vector3.Zero();
  61755. /**
  61756. * The scaling of the particle.
  61757. */
  61758. this.scaling = BABYLON.Vector3.One();
  61759. /**
  61760. * The uvs of the particle.
  61761. */
  61762. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  61763. /**
  61764. * The current speed of the particle.
  61765. */
  61766. this.velocity = BABYLON.Vector3.Zero();
  61767. /**
  61768. * The pivot point in the particle local space.
  61769. */
  61770. this.pivot = BABYLON.Vector3.Zero();
  61771. /**
  61772. * Must the particle be translated from its pivot point in its local space ?
  61773. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  61774. * Default : false
  61775. */
  61776. this.translateFromPivot = false;
  61777. /**
  61778. * Is the particle active or not ?
  61779. */
  61780. this.alive = true;
  61781. /**
  61782. * Is the particle visible or not ?
  61783. */
  61784. this.isVisible = true;
  61785. /**
  61786. * Index of this particle in the global "positions" array (Internal use)
  61787. * @hidden
  61788. */
  61789. this._pos = 0;
  61790. /**
  61791. * @hidden Index of this particle in the global "indices" array (Internal use)
  61792. */
  61793. this._ind = 0;
  61794. /**
  61795. * ModelShape id of this particle
  61796. */
  61797. this.shapeId = 0;
  61798. /**
  61799. * Index of the particle in its shape id (Internal use)
  61800. */
  61801. this.idxInShape = 0;
  61802. /**
  61803. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  61804. */
  61805. this._stillInvisible = false;
  61806. /**
  61807. * @hidden Last computed particle rotation matrix
  61808. */
  61809. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  61810. /**
  61811. * Parent particle Id, if any.
  61812. * Default null.
  61813. */
  61814. this.parentId = null;
  61815. /**
  61816. * @hidden Internal global position in the SPS.
  61817. */
  61818. this._globalPosition = BABYLON.Vector3.Zero();
  61819. this.idx = particleIndex;
  61820. this._pos = positionIndex;
  61821. this._ind = indiceIndex;
  61822. this._model = model;
  61823. this.shapeId = shapeId;
  61824. this.idxInShape = idxInShape;
  61825. this._sps = sps;
  61826. if (modelBoundingInfo) {
  61827. this._modelBoundingInfo = modelBoundingInfo;
  61828. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  61829. }
  61830. }
  61831. Object.defineProperty(SolidParticle.prototype, "scale", {
  61832. /**
  61833. * Legacy support, changed scale to scaling
  61834. */
  61835. get: function () {
  61836. return this.scaling;
  61837. },
  61838. /**
  61839. * Legacy support, changed scale to scaling
  61840. */
  61841. set: function (scale) {
  61842. this.scaling = scale;
  61843. },
  61844. enumerable: true,
  61845. configurable: true
  61846. });
  61847. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  61848. /**
  61849. * Legacy support, changed quaternion to rotationQuaternion
  61850. */
  61851. get: function () {
  61852. return this.rotationQuaternion;
  61853. },
  61854. /**
  61855. * Legacy support, changed quaternion to rotationQuaternion
  61856. */
  61857. set: function (q) {
  61858. this.rotationQuaternion = q;
  61859. },
  61860. enumerable: true,
  61861. configurable: true
  61862. });
  61863. /**
  61864. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  61865. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  61866. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  61867. * @returns true if it intersects
  61868. */
  61869. SolidParticle.prototype.intersectsMesh = function (target) {
  61870. if (!this._boundingInfo || !target._boundingInfo) {
  61871. return false;
  61872. }
  61873. if (this._sps._bSphereOnly) {
  61874. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  61875. }
  61876. return this._boundingInfo.intersects(target._boundingInfo, false);
  61877. };
  61878. return SolidParticle;
  61879. }());
  61880. BABYLON.SolidParticle = SolidParticle;
  61881. /**
  61882. * Represents the shape of the model used by one particle of a solid particle system.
  61883. * SPS internal tool, don't use it manually.
  61884. */
  61885. var ModelShape = /** @class */ (function () {
  61886. /**
  61887. * 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.
  61888. * SPS internal tool, don't use it manually.
  61889. * @hidden
  61890. */
  61891. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  61892. /**
  61893. * length of the shape in the model indices array (internal use)
  61894. * @hidden
  61895. */
  61896. this._indicesLength = 0;
  61897. this.shapeID = id;
  61898. this._shape = shape;
  61899. this._indicesLength = indicesLength;
  61900. this._shapeUV = shapeUV;
  61901. this._positionFunction = posFunction;
  61902. this._vertexFunction = vtxFunction;
  61903. }
  61904. return ModelShape;
  61905. }());
  61906. BABYLON.ModelShape = ModelShape;
  61907. /**
  61908. * Represents a Depth Sorted Particle in the solid particle system.
  61909. */
  61910. var DepthSortedParticle = /** @class */ (function () {
  61911. function DepthSortedParticle() {
  61912. /**
  61913. * Index of the particle in the "indices" array
  61914. */
  61915. this.ind = 0;
  61916. /**
  61917. * Length of the particle shape in the "indices" array
  61918. */
  61919. this.indicesLength = 0;
  61920. /**
  61921. * Squared distance from the particle to the camera
  61922. */
  61923. this.sqDistance = 0.0;
  61924. }
  61925. return DepthSortedParticle;
  61926. }());
  61927. BABYLON.DepthSortedParticle = DepthSortedParticle;
  61928. })(BABYLON || (BABYLON = {}));
  61929. //# sourceMappingURL=babylon.solidParticle.js.map
  61930. var BABYLON;
  61931. (function (BABYLON) {
  61932. /**
  61933. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  61934. *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.
  61935. * The SPS is also a particle system. It provides some methods to manage the particles.
  61936. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  61937. *
  61938. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  61939. */
  61940. var SolidParticleSystem = /** @class */ (function () {
  61941. /**
  61942. * Creates a SPS (Solid Particle System) object.
  61943. * @param name (String) is the SPS name, this will be the underlying mesh name.
  61944. * @param scene (Scene) is the scene in which the SPS is added.
  61945. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  61946. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  61947. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  61948. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  61949. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  61950. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  61951. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  61952. */
  61953. function SolidParticleSystem(name, scene, options) {
  61954. /**
  61955. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  61956. * Example : var p = SPS.particles[i];
  61957. */
  61958. this.particles = new Array();
  61959. /**
  61960. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  61961. */
  61962. this.nbParticles = 0;
  61963. /**
  61964. * If the particles must ever face the camera (default false). Useful for planar particles.
  61965. */
  61966. this.billboard = false;
  61967. /**
  61968. * Recompute normals when adding a shape
  61969. */
  61970. this.recomputeNormals = true;
  61971. /**
  61972. * This a counter ofr your own usage. It's not set by any SPS functions.
  61973. */
  61974. this.counter = 0;
  61975. /**
  61976. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  61977. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  61978. */
  61979. this.vars = {};
  61980. /**
  61981. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  61982. * @hidden
  61983. */
  61984. this._bSphereOnly = false;
  61985. /**
  61986. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  61987. * @hidden
  61988. */
  61989. this._bSphereRadiusFactor = 1.0;
  61990. this._positions = new Array();
  61991. this._indices = new Array();
  61992. this._normals = new Array();
  61993. this._colors = new Array();
  61994. this._uvs = new Array();
  61995. this._index = 0; // indices index
  61996. this._updatable = true;
  61997. this._pickable = false;
  61998. this._isVisibilityBoxLocked = false;
  61999. this._alwaysVisible = false;
  62000. this._depthSort = false;
  62001. this._shapeCounter = 0;
  62002. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  62003. this._color = new BABYLON.Color4(0, 0, 0, 0);
  62004. this._computeParticleColor = true;
  62005. this._computeParticleTexture = true;
  62006. this._computeParticleRotation = true;
  62007. this._computeParticleVertex = false;
  62008. this._computeBoundingBox = false;
  62009. this._depthSortParticles = true;
  62010. this._cam_axisZ = BABYLON.Vector3.Zero();
  62011. this._cam_axisY = BABYLON.Vector3.Zero();
  62012. this._cam_axisX = BABYLON.Vector3.Zero();
  62013. this._axisZ = BABYLON.Axis.Z;
  62014. this._camDir = BABYLON.Vector3.Zero();
  62015. this._camInvertedPosition = BABYLON.Vector3.Zero();
  62016. this._rotMatrix = new BABYLON.Matrix();
  62017. this._invertMatrix = new BABYLON.Matrix();
  62018. this._rotated = BABYLON.Vector3.Zero();
  62019. this._quaternion = new BABYLON.Quaternion();
  62020. this._vertex = BABYLON.Vector3.Zero();
  62021. this._normal = BABYLON.Vector3.Zero();
  62022. this._yaw = 0.0;
  62023. this._pitch = 0.0;
  62024. this._roll = 0.0;
  62025. this._halfroll = 0.0;
  62026. this._halfpitch = 0.0;
  62027. this._halfyaw = 0.0;
  62028. this._sinRoll = 0.0;
  62029. this._cosRoll = 0.0;
  62030. this._sinPitch = 0.0;
  62031. this._cosPitch = 0.0;
  62032. this._sinYaw = 0.0;
  62033. this._cosYaw = 0.0;
  62034. this._mustUnrotateFixedNormals = false;
  62035. this._minimum = BABYLON.Vector3.Zero();
  62036. this._maximum = BABYLON.Vector3.Zero();
  62037. this._minBbox = BABYLON.Vector3.Zero();
  62038. this._maxBbox = BABYLON.Vector3.Zero();
  62039. this._particlesIntersect = false;
  62040. this._depthSortFunction = function (p1, p2) {
  62041. return (p2.sqDistance - p1.sqDistance);
  62042. };
  62043. this._needs32Bits = false;
  62044. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  62045. this._scaledPivot = BABYLON.Vector3.Zero();
  62046. this._particleHasParent = false;
  62047. this.name = name;
  62048. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62049. this._camera = scene.activeCamera;
  62050. this._pickable = options ? options.isPickable : false;
  62051. this._depthSort = options ? options.enableDepthSort : false;
  62052. this._particlesIntersect = options ? options.particleIntersection : false;
  62053. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  62054. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  62055. if (options && options.updatable !== undefined) {
  62056. this._updatable = options.updatable;
  62057. }
  62058. else {
  62059. this._updatable = true;
  62060. }
  62061. if (this._pickable) {
  62062. this.pickedParticles = [];
  62063. }
  62064. if (this._depthSort) {
  62065. this.depthSortedParticles = [];
  62066. }
  62067. }
  62068. /**
  62069. * Builds the SPS underlying mesh. Returns a standard Mesh.
  62070. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  62071. * @returns the created mesh
  62072. */
  62073. SolidParticleSystem.prototype.buildMesh = function () {
  62074. if (this.nbParticles === 0) {
  62075. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  62076. this.addShape(triangle, 1);
  62077. triangle.dispose();
  62078. }
  62079. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  62080. this._positions32 = new Float32Array(this._positions);
  62081. this._uvs32 = new Float32Array(this._uvs);
  62082. this._colors32 = new Float32Array(this._colors);
  62083. if (this.recomputeNormals) {
  62084. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  62085. }
  62086. this._normals32 = new Float32Array(this._normals);
  62087. this._fixedNormal32 = new Float32Array(this._normals);
  62088. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  62089. this._unrotateFixedNormals();
  62090. }
  62091. var vertexData = new BABYLON.VertexData();
  62092. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  62093. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  62094. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  62095. if (this._uvs32.length > 0) {
  62096. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  62097. }
  62098. if (this._colors32.length > 0) {
  62099. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  62100. }
  62101. var mesh = new BABYLON.Mesh(this.name, this._scene);
  62102. vertexData.applyToMesh(mesh, this._updatable);
  62103. this.mesh = mesh;
  62104. this.mesh.isPickable = this._pickable;
  62105. // free memory
  62106. if (!this._depthSort) {
  62107. this._indices = null;
  62108. }
  62109. this._positions = null;
  62110. this._normals = null;
  62111. this._uvs = null;
  62112. this._colors = null;
  62113. if (!this._updatable) {
  62114. this.particles.length = 0;
  62115. }
  62116. return mesh;
  62117. };
  62118. /**
  62119. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  62120. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  62121. * Thus the particles generated from `digest()` have their property `position` set yet.
  62122. * @param mesh ( Mesh ) is the mesh to be digested
  62123. * @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
  62124. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  62125. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  62126. * @returns the current SPS
  62127. */
  62128. SolidParticleSystem.prototype.digest = function (mesh, options) {
  62129. var size = (options && options.facetNb) || 1;
  62130. var number = (options && options.number) || 0;
  62131. var delta = (options && options.delta) || 0;
  62132. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62133. var meshInd = mesh.getIndices();
  62134. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62135. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62136. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62137. var f = 0; // facet counter
  62138. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  62139. // compute size from number
  62140. if (number) {
  62141. number = (number > totalFacets) ? totalFacets : number;
  62142. size = Math.round(totalFacets / number);
  62143. delta = 0;
  62144. }
  62145. else {
  62146. size = (size > totalFacets) ? totalFacets : size;
  62147. }
  62148. var facetPos = []; // submesh positions
  62149. var facetInd = []; // submesh indices
  62150. var facetUV = []; // submesh UV
  62151. var facetCol = []; // submesh colors
  62152. var barycenter = BABYLON.Vector3.Zero();
  62153. var sizeO = size;
  62154. while (f < totalFacets) {
  62155. size = sizeO + Math.floor((1 + delta) * Math.random());
  62156. if (f > totalFacets - size) {
  62157. size = totalFacets - f;
  62158. }
  62159. // reset temp arrays
  62160. facetPos.length = 0;
  62161. facetInd.length = 0;
  62162. facetUV.length = 0;
  62163. facetCol.length = 0;
  62164. // iterate over "size" facets
  62165. var fi = 0;
  62166. for (var j = f * 3; j < (f + size) * 3; j++) {
  62167. facetInd.push(fi);
  62168. var i = meshInd[j];
  62169. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  62170. if (meshUV) {
  62171. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  62172. }
  62173. if (meshCol) {
  62174. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  62175. }
  62176. fi++;
  62177. }
  62178. // create a model shape for each single particle
  62179. var idx = this.nbParticles;
  62180. var shape = this._posToShape(facetPos);
  62181. var shapeUV = this._uvsToShapeUV(facetUV);
  62182. // compute the barycenter of the shape
  62183. var v;
  62184. for (v = 0; v < shape.length; v++) {
  62185. barycenter.addInPlace(shape[v]);
  62186. }
  62187. barycenter.scaleInPlace(1 / shape.length);
  62188. // shift the shape from its barycenter to the origin
  62189. for (v = 0; v < shape.length; v++) {
  62190. shape[v].subtractInPlace(barycenter);
  62191. }
  62192. var bInfo;
  62193. if (this._particlesIntersect) {
  62194. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  62195. }
  62196. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  62197. // add the particle in the SPS
  62198. var currentPos = this._positions.length;
  62199. var currentInd = this._indices.length;
  62200. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  62201. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  62202. // initialize the particle position
  62203. this.particles[this.nbParticles].position.addInPlace(barycenter);
  62204. this._index += shape.length;
  62205. idx++;
  62206. this.nbParticles++;
  62207. this._shapeCounter++;
  62208. f += size;
  62209. }
  62210. return this;
  62211. };
  62212. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  62213. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  62214. var index = 0;
  62215. var idx = 0;
  62216. for (var p = 0; p < this.particles.length; p++) {
  62217. this._particle = this.particles[p];
  62218. this._shape = this._particle._model._shape;
  62219. if (this._particle.rotationQuaternion) {
  62220. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62221. }
  62222. else {
  62223. this._yaw = this._particle.rotation.y;
  62224. this._pitch = this._particle.rotation.x;
  62225. this._roll = this._particle.rotation.z;
  62226. this._quaternionRotationYPR();
  62227. }
  62228. this._quaternionToRotationMatrix();
  62229. this._rotMatrix.invertToRef(this._invertMatrix);
  62230. for (var pt = 0; pt < this._shape.length; pt++) {
  62231. idx = index + pt * 3;
  62232. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  62233. this._fixedNormal32[idx] = this._normal.x;
  62234. this._fixedNormal32[idx + 1] = this._normal.y;
  62235. this._fixedNormal32[idx + 2] = this._normal.z;
  62236. }
  62237. index = idx + 3;
  62238. }
  62239. };
  62240. //reset copy
  62241. SolidParticleSystem.prototype._resetCopy = function () {
  62242. this._copy.position.x = 0;
  62243. this._copy.position.y = 0;
  62244. this._copy.position.z = 0;
  62245. this._copy.rotation.x = 0;
  62246. this._copy.rotation.y = 0;
  62247. this._copy.rotation.z = 0;
  62248. this._copy.rotationQuaternion = null;
  62249. this._copy.scaling.x = 1.0;
  62250. this._copy.scaling.y = 1.0;
  62251. this._copy.scaling.z = 1.0;
  62252. this._copy.uvs.x = 0;
  62253. this._copy.uvs.y = 0;
  62254. this._copy.uvs.z = 1.0;
  62255. this._copy.uvs.w = 1.0;
  62256. this._copy.color = null;
  62257. this._copy.translateFromPivot = false;
  62258. };
  62259. // _meshBuilder : inserts the shape model in the global SPS mesh
  62260. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  62261. var i;
  62262. var u = 0;
  62263. var c = 0;
  62264. var n = 0;
  62265. this._resetCopy();
  62266. if (options && options.positionFunction) { // call to custom positionFunction
  62267. options.positionFunction(this._copy, idx, idxInShape);
  62268. this._mustUnrotateFixedNormals = true;
  62269. }
  62270. if (this._copy.rotationQuaternion) {
  62271. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62272. }
  62273. else {
  62274. this._yaw = this._copy.rotation.y;
  62275. this._pitch = this._copy.rotation.x;
  62276. this._roll = this._copy.rotation.z;
  62277. this._quaternionRotationYPR();
  62278. }
  62279. this._quaternionToRotationMatrix();
  62280. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  62281. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  62282. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  62283. if (this._copy.translateFromPivot) {
  62284. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62285. }
  62286. else {
  62287. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62288. }
  62289. for (i = 0; i < shape.length; i++) {
  62290. this._vertex.x = shape[i].x;
  62291. this._vertex.y = shape[i].y;
  62292. this._vertex.z = shape[i].z;
  62293. if (options && options.vertexFunction) {
  62294. options.vertexFunction(this._copy, this._vertex, i);
  62295. }
  62296. this._vertex.x *= this._copy.scaling.x;
  62297. this._vertex.y *= this._copy.scaling.y;
  62298. this._vertex.z *= this._copy.scaling.z;
  62299. this._vertex.x -= this._scaledPivot.x;
  62300. this._vertex.y -= this._scaledPivot.y;
  62301. this._vertex.z -= this._scaledPivot.z;
  62302. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62303. this._rotated.addInPlace(this._pivotBackTranslation);
  62304. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  62305. if (meshUV) {
  62306. 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);
  62307. u += 2;
  62308. }
  62309. if (this._copy.color) {
  62310. this._color = this._copy.color;
  62311. }
  62312. else if (meshCol && meshCol[c] !== undefined) {
  62313. this._color.r = meshCol[c];
  62314. this._color.g = meshCol[c + 1];
  62315. this._color.b = meshCol[c + 2];
  62316. this._color.a = meshCol[c + 3];
  62317. }
  62318. else {
  62319. this._color.r = 1.0;
  62320. this._color.g = 1.0;
  62321. this._color.b = 1.0;
  62322. this._color.a = 1.0;
  62323. }
  62324. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  62325. c += 4;
  62326. if (!this.recomputeNormals && meshNor) {
  62327. this._normal.x = meshNor[n];
  62328. this._normal.y = meshNor[n + 1];
  62329. this._normal.z = meshNor[n + 2];
  62330. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  62331. normals.push(this._normal.x, this._normal.y, this._normal.z);
  62332. n += 3;
  62333. }
  62334. }
  62335. for (i = 0; i < meshInd.length; i++) {
  62336. var current_ind = p + meshInd[i];
  62337. indices.push(current_ind);
  62338. if (current_ind > 65535) {
  62339. this._needs32Bits = true;
  62340. }
  62341. }
  62342. if (this._pickable) {
  62343. var nbfaces = meshInd.length / 3;
  62344. for (i = 0; i < nbfaces; i++) {
  62345. this.pickedParticles.push({ idx: idx, faceId: i });
  62346. }
  62347. }
  62348. if (this._depthSort) {
  62349. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  62350. }
  62351. return this._copy;
  62352. };
  62353. // returns a shape array from positions array
  62354. SolidParticleSystem.prototype._posToShape = function (positions) {
  62355. var shape = [];
  62356. for (var i = 0; i < positions.length; i += 3) {
  62357. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  62358. }
  62359. return shape;
  62360. };
  62361. // returns a shapeUV array from a Vector4 uvs
  62362. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  62363. var shapeUV = [];
  62364. if (uvs) {
  62365. for (var i = 0; i < uvs.length; i++)
  62366. shapeUV.push(uvs[i]);
  62367. }
  62368. return shapeUV;
  62369. };
  62370. // adds a new particle object in the particles array
  62371. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  62372. if (bInfo === void 0) { bInfo = null; }
  62373. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  62374. this.particles.push(sp);
  62375. return sp;
  62376. };
  62377. /**
  62378. * Adds some particles to the SPS from the model shape. Returns the shape id.
  62379. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  62380. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  62381. * @param nb (positive integer) the number of particles to be created from this model
  62382. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  62383. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  62384. * @returns the number of shapes in the system
  62385. */
  62386. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  62387. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62388. var meshInd = mesh.getIndices();
  62389. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62390. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62391. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62392. var bbInfo;
  62393. if (this._particlesIntersect) {
  62394. bbInfo = mesh.getBoundingInfo();
  62395. }
  62396. var shape = this._posToShape(meshPos);
  62397. var shapeUV = this._uvsToShapeUV(meshUV);
  62398. var posfunc = options ? options.positionFunction : null;
  62399. var vtxfunc = options ? options.vertexFunction : null;
  62400. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  62401. // particles
  62402. var sp;
  62403. var currentCopy;
  62404. var idx = this.nbParticles;
  62405. for (var i = 0; i < nb; i++) {
  62406. var currentPos = this._positions.length;
  62407. var currentInd = this._indices.length;
  62408. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  62409. if (this._updatable) {
  62410. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  62411. sp.position.copyFrom(currentCopy.position);
  62412. sp.rotation.copyFrom(currentCopy.rotation);
  62413. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  62414. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  62415. }
  62416. if (currentCopy.color && sp.color) {
  62417. sp.color.copyFrom(currentCopy.color);
  62418. }
  62419. sp.scaling.copyFrom(currentCopy.scaling);
  62420. sp.uvs.copyFrom(currentCopy.uvs);
  62421. }
  62422. this._index += shape.length;
  62423. idx++;
  62424. }
  62425. this.nbParticles += nb;
  62426. this._shapeCounter++;
  62427. return this._shapeCounter - 1;
  62428. };
  62429. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  62430. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  62431. this._resetCopy();
  62432. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  62433. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  62434. }
  62435. if (this._copy.rotationQuaternion) {
  62436. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62437. }
  62438. else {
  62439. this._yaw = this._copy.rotation.y;
  62440. this._pitch = this._copy.rotation.x;
  62441. this._roll = this._copy.rotation.z;
  62442. this._quaternionRotationYPR();
  62443. }
  62444. this._quaternionToRotationMatrix();
  62445. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62446. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62447. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62448. if (this._copy.translateFromPivot) {
  62449. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62450. }
  62451. else {
  62452. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62453. }
  62454. this._shape = particle._model._shape;
  62455. for (var pt = 0; pt < this._shape.length; pt++) {
  62456. this._vertex.x = this._shape[pt].x;
  62457. this._vertex.y = this._shape[pt].y;
  62458. this._vertex.z = this._shape[pt].z;
  62459. if (particle._model._vertexFunction) {
  62460. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  62461. }
  62462. this._vertex.x *= this._copy.scaling.x;
  62463. this._vertex.y *= this._copy.scaling.y;
  62464. this._vertex.z *= this._copy.scaling.z;
  62465. this._vertex.x -= this._scaledPivot.x;
  62466. this._vertex.y -= this._scaledPivot.y;
  62467. this._vertex.z -= this._scaledPivot.z;
  62468. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62469. this._rotated.addInPlace(this._pivotBackTranslation);
  62470. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  62471. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  62472. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  62473. }
  62474. particle.position.x = 0.0;
  62475. particle.position.y = 0.0;
  62476. particle.position.z = 0.0;
  62477. particle.rotation.x = 0.0;
  62478. particle.rotation.y = 0.0;
  62479. particle.rotation.z = 0.0;
  62480. particle.rotationQuaternion = null;
  62481. particle.scaling.x = 1.0;
  62482. particle.scaling.y = 1.0;
  62483. particle.scaling.z = 1.0;
  62484. particle.uvs.x = 0.0;
  62485. particle.uvs.y = 0.0;
  62486. particle.uvs.z = 1.0;
  62487. particle.uvs.w = 1.0;
  62488. particle.pivot.x = 0.0;
  62489. particle.pivot.y = 0.0;
  62490. particle.pivot.z = 0.0;
  62491. particle.translateFromPivot = false;
  62492. particle.parentId = null;
  62493. };
  62494. /**
  62495. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  62496. * @returns the SPS.
  62497. */
  62498. SolidParticleSystem.prototype.rebuildMesh = function () {
  62499. for (var p = 0; p < this.particles.length; p++) {
  62500. this._rebuildParticle(this.particles[p]);
  62501. }
  62502. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62503. return this;
  62504. };
  62505. /**
  62506. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  62507. * This method calls `updateParticle()` for each particle of the SPS.
  62508. * For an animated SPS, it is usually called within the render loop.
  62509. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  62510. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  62511. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  62512. * @returns the SPS.
  62513. */
  62514. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  62515. if (start === void 0) { start = 0; }
  62516. if (end === void 0) { end = this.nbParticles - 1; }
  62517. if (update === void 0) { update = true; }
  62518. if (!this._updatable) {
  62519. return this;
  62520. }
  62521. // custom beforeUpdate
  62522. this.beforeUpdateParticles(start, end, update);
  62523. this._cam_axisX.x = 1.0;
  62524. this._cam_axisX.y = 0.0;
  62525. this._cam_axisX.z = 0.0;
  62526. this._cam_axisY.x = 0.0;
  62527. this._cam_axisY.y = 1.0;
  62528. this._cam_axisY.z = 0.0;
  62529. this._cam_axisZ.x = 0.0;
  62530. this._cam_axisZ.y = 0.0;
  62531. this._cam_axisZ.z = 1.0;
  62532. // cases when the World Matrix is to be computed first
  62533. if (this.billboard || this._depthSort) {
  62534. this.mesh.computeWorldMatrix(true);
  62535. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  62536. }
  62537. // if the particles will always face the camera
  62538. if (this.billboard) {
  62539. // compute the camera position and un-rotate it by the current mesh rotation
  62540. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  62541. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  62542. this._cam_axisZ.normalize();
  62543. // same for camera up vector extracted from the cam view matrix
  62544. var view = this._camera.getViewMatrix(true);
  62545. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  62546. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  62547. this._cam_axisY.normalize();
  62548. this._cam_axisX.normalize();
  62549. }
  62550. // if depthSort, compute the camera global position in the mesh local system
  62551. if (this._depthSort) {
  62552. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  62553. }
  62554. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  62555. var idx = 0; // current position index in the global array positions32
  62556. var index = 0; // position start index in the global array positions32 of the current particle
  62557. var colidx = 0; // current color index in the global array colors32
  62558. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  62559. var uvidx = 0; // current uv index in the global array uvs32
  62560. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  62561. var pt = 0; // current index in the particle model shape
  62562. if (this.mesh.isFacetDataEnabled) {
  62563. this._computeBoundingBox = true;
  62564. }
  62565. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  62566. if (this._computeBoundingBox) {
  62567. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  62568. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  62569. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  62570. }
  62571. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  62572. if (this.mesh._boundingInfo) {
  62573. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  62574. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  62575. }
  62576. }
  62577. }
  62578. // particle loop
  62579. index = this.particles[start]._pos;
  62580. var vpos = (index / 3) | 0;
  62581. colorIndex = vpos * 4;
  62582. uvIndex = vpos * 2;
  62583. for (var p = start; p <= end; p++) {
  62584. this._particle = this.particles[p];
  62585. this._shape = this._particle._model._shape;
  62586. this._shapeUV = this._particle._model._shapeUV;
  62587. // call to custom user function to update the particle properties
  62588. this.updateParticle(this._particle);
  62589. // camera-particle distance for depth sorting
  62590. if (this._depthSort && this._depthSortParticles) {
  62591. var dsp = this.depthSortedParticles[p];
  62592. dsp.ind = this._particle._ind;
  62593. dsp.indicesLength = this._particle._model._indicesLength;
  62594. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  62595. }
  62596. // skip the computations for inactive or already invisible particles
  62597. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  62598. // increment indexes for the next particle
  62599. pt = this._shape.length;
  62600. index += pt * 3;
  62601. colorIndex += pt * 4;
  62602. uvIndex += pt * 2;
  62603. continue;
  62604. }
  62605. if (this._particle.isVisible) {
  62606. this._particle._stillInvisible = false; // un-mark permanent invisibility
  62607. this._particleHasParent = (this._particle.parentId !== null);
  62608. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62609. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62610. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62611. // particle rotation matrix
  62612. if (this.billboard) {
  62613. this._particle.rotation.x = 0.0;
  62614. this._particle.rotation.y = 0.0;
  62615. }
  62616. if (this._computeParticleRotation || this.billboard) {
  62617. if (this._particle.rotationQuaternion) {
  62618. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62619. }
  62620. else {
  62621. this._yaw = this._particle.rotation.y;
  62622. this._pitch = this._particle.rotation.x;
  62623. this._roll = this._particle.rotation.z;
  62624. this._quaternionRotationYPR();
  62625. }
  62626. this._quaternionToRotationMatrix();
  62627. }
  62628. if (this._particleHasParent) {
  62629. this._parent = this.particles[this._particle.parentId];
  62630. 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];
  62631. 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];
  62632. 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];
  62633. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  62634. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  62635. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  62636. if (this._computeParticleRotation || this.billboard) {
  62637. 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];
  62638. 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];
  62639. 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];
  62640. 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];
  62641. 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];
  62642. 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];
  62643. 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];
  62644. 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];
  62645. 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];
  62646. }
  62647. }
  62648. else {
  62649. this._particle._globalPosition.x = this._particle.position.x;
  62650. this._particle._globalPosition.y = this._particle.position.y;
  62651. this._particle._globalPosition.z = this._particle.position.z;
  62652. if (this._computeParticleRotation || this.billboard) {
  62653. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  62654. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  62655. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  62656. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  62657. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  62658. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  62659. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  62660. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  62661. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  62662. }
  62663. }
  62664. if (this._particle.translateFromPivot) {
  62665. this._pivotBackTranslation.x = 0.0;
  62666. this._pivotBackTranslation.y = 0.0;
  62667. this._pivotBackTranslation.z = 0.0;
  62668. }
  62669. else {
  62670. this._pivotBackTranslation.x = this._scaledPivot.x;
  62671. this._pivotBackTranslation.y = this._scaledPivot.y;
  62672. this._pivotBackTranslation.z = this._scaledPivot.z;
  62673. }
  62674. // particle vertex loop
  62675. for (pt = 0; pt < this._shape.length; pt++) {
  62676. idx = index + pt * 3;
  62677. colidx = colorIndex + pt * 4;
  62678. uvidx = uvIndex + pt * 2;
  62679. this._vertex.x = this._shape[pt].x;
  62680. this._vertex.y = this._shape[pt].y;
  62681. this._vertex.z = this._shape[pt].z;
  62682. if (this._computeParticleVertex) {
  62683. this.updateParticleVertex(this._particle, this._vertex, pt);
  62684. }
  62685. // positions
  62686. this._vertex.x *= this._particle.scaling.x;
  62687. this._vertex.y *= this._particle.scaling.y;
  62688. this._vertex.z *= this._particle.scaling.z;
  62689. this._vertex.x -= this._scaledPivot.x;
  62690. this._vertex.y -= this._scaledPivot.y;
  62691. this._vertex.z -= this._scaledPivot.z;
  62692. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62693. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62694. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62695. this._rotated.x += this._pivotBackTranslation.x;
  62696. this._rotated.y += this._pivotBackTranslation.y;
  62697. this._rotated.z += this._pivotBackTranslation.z;
  62698. 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;
  62699. 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;
  62700. 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;
  62701. if (this._computeBoundingBox) {
  62702. if (this._positions32[idx] < this._minimum.x) {
  62703. this._minimum.x = this._positions32[idx];
  62704. }
  62705. if (this._positions32[idx] > this._maximum.x) {
  62706. this._maximum.x = this._positions32[idx];
  62707. }
  62708. if (this._positions32[idx + 1] < this._minimum.y) {
  62709. this._minimum.y = this._positions32[idx + 1];
  62710. }
  62711. if (this._positions32[idx + 1] > this._maximum.y) {
  62712. this._maximum.y = this._positions32[idx + 1];
  62713. }
  62714. if (this._positions32[idx + 2] < this._minimum.z) {
  62715. this._minimum.z = this._positions32[idx + 2];
  62716. }
  62717. if (this._positions32[idx + 2] > this._maximum.z) {
  62718. this._maximum.z = this._positions32[idx + 2];
  62719. }
  62720. }
  62721. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  62722. if (!this._computeParticleVertex) {
  62723. this._normal.x = this._fixedNormal32[idx];
  62724. this._normal.y = this._fixedNormal32[idx + 1];
  62725. this._normal.z = this._fixedNormal32[idx + 2];
  62726. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  62727. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  62728. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  62729. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  62730. 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;
  62731. 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;
  62732. }
  62733. if (this._computeParticleColor && this._particle.color) {
  62734. this._colors32[colidx] = this._particle.color.r;
  62735. this._colors32[colidx + 1] = this._particle.color.g;
  62736. this._colors32[colidx + 2] = this._particle.color.b;
  62737. this._colors32[colidx + 3] = this._particle.color.a;
  62738. }
  62739. if (this._computeParticleTexture) {
  62740. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62741. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62742. }
  62743. }
  62744. }
  62745. // particle just set invisible : scaled to zero and positioned at the origin
  62746. else {
  62747. this._particle._stillInvisible = true; // mark the particle as invisible
  62748. for (pt = 0; pt < this._shape.length; pt++) {
  62749. idx = index + pt * 3;
  62750. colidx = colorIndex + pt * 4;
  62751. uvidx = uvIndex + pt * 2;
  62752. this._positions32[idx] = 0.0;
  62753. this._positions32[idx + 1] = 0.0;
  62754. this._positions32[idx + 2] = 0.0;
  62755. this._normals32[idx] = 0.0;
  62756. this._normals32[idx + 1] = 0.0;
  62757. this._normals32[idx + 2] = 0.0;
  62758. if (this._computeParticleColor && this._particle.color) {
  62759. this._colors32[colidx] = this._particle.color.r;
  62760. this._colors32[colidx + 1] = this._particle.color.g;
  62761. this._colors32[colidx + 2] = this._particle.color.b;
  62762. this._colors32[colidx + 3] = this._particle.color.a;
  62763. }
  62764. if (this._computeParticleTexture) {
  62765. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62766. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62767. }
  62768. }
  62769. }
  62770. // if the particle intersections must be computed : update the bbInfo
  62771. if (this._particlesIntersect) {
  62772. var bInfo = this._particle._boundingInfo;
  62773. var bBox = bInfo.boundingBox;
  62774. var bSphere = bInfo.boundingSphere;
  62775. if (!this._bSphereOnly) {
  62776. // place, scale and rotate the particle bbox within the SPS local system, then update it
  62777. for (var b = 0; b < bBox.vectors.length; b++) {
  62778. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  62779. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  62780. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  62781. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62782. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62783. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62784. 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;
  62785. 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;
  62786. 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;
  62787. }
  62788. bBox._update(this.mesh._worldMatrix);
  62789. }
  62790. // place and scale the particle bouding sphere in the SPS local system, then update it
  62791. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  62792. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  62793. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  62794. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  62795. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  62796. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  62797. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  62798. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  62799. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  62800. 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));
  62801. bSphere._update(this.mesh._worldMatrix);
  62802. }
  62803. // increment indexes for the next particle
  62804. index = idx + 3;
  62805. colorIndex = colidx + 4;
  62806. uvIndex = uvidx + 2;
  62807. }
  62808. // if the VBO must be updated
  62809. if (update) {
  62810. if (this._computeParticleColor) {
  62811. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  62812. }
  62813. if (this._computeParticleTexture) {
  62814. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  62815. }
  62816. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62817. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  62818. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  62819. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  62820. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  62821. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  62822. for (var i = 0; i < this._normals32.length; i++) {
  62823. this._fixedNormal32[i] = this._normals32[i];
  62824. }
  62825. }
  62826. if (!this.mesh.areNormalsFrozen) {
  62827. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  62828. }
  62829. }
  62830. if (this._depthSort && this._depthSortParticles) {
  62831. this.depthSortedParticles.sort(this._depthSortFunction);
  62832. var dspl = this.depthSortedParticles.length;
  62833. var sorted = 0;
  62834. var lind = 0;
  62835. var sind = 0;
  62836. var sid = 0;
  62837. for (sorted = 0; sorted < dspl; sorted++) {
  62838. lind = this.depthSortedParticles[sorted].indicesLength;
  62839. sind = this.depthSortedParticles[sorted].ind;
  62840. for (var i = 0; i < lind; i++) {
  62841. this._indices32[sid] = this._indices[sind + i];
  62842. sid++;
  62843. }
  62844. }
  62845. this.mesh.updateIndices(this._indices32);
  62846. }
  62847. }
  62848. if (this._computeBoundingBox) {
  62849. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  62850. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  62851. }
  62852. this.afterUpdateParticles(start, end, update);
  62853. return this;
  62854. };
  62855. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  62856. this._halfroll = this._roll * 0.5;
  62857. this._halfpitch = this._pitch * 0.5;
  62858. this._halfyaw = this._yaw * 0.5;
  62859. this._sinRoll = Math.sin(this._halfroll);
  62860. this._cosRoll = Math.cos(this._halfroll);
  62861. this._sinPitch = Math.sin(this._halfpitch);
  62862. this._cosPitch = Math.cos(this._halfpitch);
  62863. this._sinYaw = Math.sin(this._halfyaw);
  62864. this._cosYaw = Math.cos(this._halfyaw);
  62865. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  62866. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  62867. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  62868. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  62869. };
  62870. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  62871. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  62872. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  62873. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  62874. this._rotMatrix.m[3] = 0;
  62875. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  62876. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  62877. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  62878. this._rotMatrix.m[7] = 0;
  62879. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  62880. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  62881. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  62882. this._rotMatrix.m[11] = 0;
  62883. this._rotMatrix.m[12] = 0;
  62884. this._rotMatrix.m[13] = 0;
  62885. this._rotMatrix.m[14] = 0;
  62886. this._rotMatrix.m[15] = 1.0;
  62887. };
  62888. /**
  62889. * Disposes the SPS.
  62890. */
  62891. SolidParticleSystem.prototype.dispose = function () {
  62892. this.mesh.dispose();
  62893. this.vars = null;
  62894. // drop references to internal big arrays for the GC
  62895. this._positions = null;
  62896. this._indices = null;
  62897. this._normals = null;
  62898. this._uvs = null;
  62899. this._colors = null;
  62900. this._indices32 = null;
  62901. this._positions32 = null;
  62902. this._normals32 = null;
  62903. this._fixedNormal32 = null;
  62904. this._uvs32 = null;
  62905. this._colors32 = null;
  62906. this.pickedParticles = null;
  62907. };
  62908. /**
  62909. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  62910. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62911. * @returns the SPS.
  62912. */
  62913. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  62914. if (!this._isVisibilityBoxLocked) {
  62915. this.mesh.refreshBoundingInfo();
  62916. }
  62917. return this;
  62918. };
  62919. /**
  62920. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  62921. * @param size the size (float) of the visibility box
  62922. * note : this doesn't lock the SPS mesh bounding box.
  62923. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62924. */
  62925. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  62926. var vis = size / 2;
  62927. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  62928. };
  62929. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  62930. /**
  62931. * Gets whether the SPS as always visible or not
  62932. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62933. */
  62934. get: function () {
  62935. return this._alwaysVisible;
  62936. },
  62937. /**
  62938. * Sets the SPS as always visible or not
  62939. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62940. */
  62941. set: function (val) {
  62942. this._alwaysVisible = val;
  62943. this.mesh.alwaysSelectAsActiveMesh = val;
  62944. },
  62945. enumerable: true,
  62946. configurable: true
  62947. });
  62948. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  62949. /**
  62950. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  62951. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62952. */
  62953. get: function () {
  62954. return this._isVisibilityBoxLocked;
  62955. },
  62956. /**
  62957. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  62958. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62959. */
  62960. set: function (val) {
  62961. this._isVisibilityBoxLocked = val;
  62962. var boundingInfo = this.mesh.getBoundingInfo();
  62963. boundingInfo.isLocked = val;
  62964. },
  62965. enumerable: true,
  62966. configurable: true
  62967. });
  62968. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  62969. /**
  62970. * Gets if `setParticles()` computes the particle rotations or not.
  62971. * Default value : true. The SPS is faster when it's set to false.
  62972. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  62973. */
  62974. get: function () {
  62975. return this._computeParticleRotation;
  62976. },
  62977. /**
  62978. * Tells to `setParticles()` to compute the particle rotations or not.
  62979. * Default value : true. The SPS is faster when it's set to false.
  62980. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  62981. */
  62982. set: function (val) {
  62983. this._computeParticleRotation = val;
  62984. },
  62985. enumerable: true,
  62986. configurable: true
  62987. });
  62988. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  62989. /**
  62990. * Gets if `setParticles()` computes the particle colors or not.
  62991. * Default value : true. The SPS is faster when it's set to false.
  62992. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  62993. */
  62994. get: function () {
  62995. return this._computeParticleColor;
  62996. },
  62997. /**
  62998. * Tells to `setParticles()` to compute the particle colors or not.
  62999. * Default value : true. The SPS is faster when it's set to false.
  63000. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63001. */
  63002. set: function (val) {
  63003. this._computeParticleColor = val;
  63004. },
  63005. enumerable: true,
  63006. configurable: true
  63007. });
  63008. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  63009. /**
  63010. * Gets if `setParticles()` computes the particle textures or not.
  63011. * Default value : true. The SPS is faster when it's set to false.
  63012. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  63013. */
  63014. get: function () {
  63015. return this._computeParticleTexture;
  63016. },
  63017. set: function (val) {
  63018. this._computeParticleTexture = val;
  63019. },
  63020. enumerable: true,
  63021. configurable: true
  63022. });
  63023. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  63024. /**
  63025. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  63026. * Default value : false. The SPS is faster when it's set to false.
  63027. * Note : the particle custom vertex positions aren't stored values.
  63028. */
  63029. get: function () {
  63030. return this._computeParticleVertex;
  63031. },
  63032. /**
  63033. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  63034. * Default value : false. The SPS is faster when it's set to false.
  63035. * Note : the particle custom vertex positions aren't stored values.
  63036. */
  63037. set: function (val) {
  63038. this._computeParticleVertex = val;
  63039. },
  63040. enumerable: true,
  63041. configurable: true
  63042. });
  63043. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  63044. /**
  63045. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  63046. */
  63047. get: function () {
  63048. return this._computeBoundingBox;
  63049. },
  63050. /**
  63051. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  63052. */
  63053. set: function (val) {
  63054. this._computeBoundingBox = val;
  63055. },
  63056. enumerable: true,
  63057. configurable: true
  63058. });
  63059. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  63060. /**
  63061. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  63062. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63063. * Default : `true`
  63064. */
  63065. get: function () {
  63066. return this._depthSortParticles;
  63067. },
  63068. /**
  63069. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  63070. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63071. * Default : `true`
  63072. */
  63073. set: function (val) {
  63074. this._depthSortParticles = val;
  63075. },
  63076. enumerable: true,
  63077. configurable: true
  63078. });
  63079. // =======================================================================
  63080. // Particle behavior logic
  63081. // these following methods may be overwritten by the user to fit his needs
  63082. /**
  63083. * This function does nothing. It may be overwritten to set all the particle first values.
  63084. * The SPS doesn't call this function, you may have to call it by your own.
  63085. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63086. */
  63087. SolidParticleSystem.prototype.initParticles = function () {
  63088. };
  63089. /**
  63090. * This function does nothing. It may be overwritten to recycle a particle.
  63091. * The SPS doesn't call this function, you may have to call it by your own.
  63092. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63093. * @param particle The particle to recycle
  63094. * @returns the recycled particle
  63095. */
  63096. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  63097. return particle;
  63098. };
  63099. /**
  63100. * Updates a particle : this function should be overwritten by the user.
  63101. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  63102. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63103. * @example : just set a particle position or velocity and recycle conditions
  63104. * @param particle The particle to update
  63105. * @returns the updated particle
  63106. */
  63107. SolidParticleSystem.prototype.updateParticle = function (particle) {
  63108. return particle;
  63109. };
  63110. /**
  63111. * Updates a vertex of a particle : it can be overwritten by the user.
  63112. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  63113. * @param particle the current particle
  63114. * @param vertex the current index of the current particle
  63115. * @param pt the index of the current vertex in the particle shape
  63116. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  63117. * @example : just set a vertex particle position
  63118. * @returns the updated vertex
  63119. */
  63120. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  63121. return vertex;
  63122. };
  63123. /**
  63124. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  63125. * This does nothing and may be overwritten by the user.
  63126. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63127. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63128. * @param update the boolean update value actually passed to setParticles()
  63129. */
  63130. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  63131. };
  63132. /**
  63133. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  63134. * This will be passed three parameters.
  63135. * This does nothing and may be overwritten by the user.
  63136. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63137. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63138. * @param update the boolean update value actually passed to setParticles()
  63139. */
  63140. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  63141. };
  63142. return SolidParticleSystem;
  63143. }());
  63144. BABYLON.SolidParticleSystem = SolidParticleSystem;
  63145. })(BABYLON || (BABYLON = {}));
  63146. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  63147. var BABYLON;
  63148. (function (BABYLON) {
  63149. /**
  63150. * Class containing static functions to help procedurally build meshes
  63151. */
  63152. var MeshBuilder = /** @class */ (function () {
  63153. function MeshBuilder() {
  63154. }
  63155. MeshBuilder.updateSideOrientation = function (orientation) {
  63156. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  63157. return BABYLON.Mesh.DOUBLESIDE;
  63158. }
  63159. if (orientation === undefined || orientation === null) {
  63160. return BABYLON.Mesh.FRONTSIDE;
  63161. }
  63162. return orientation;
  63163. };
  63164. /**
  63165. * Creates a box mesh
  63166. * * The parameter `size` sets the size (float) of each box side (default 1)
  63167. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  63168. * * 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)
  63169. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63170. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63171. * * 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
  63172. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63173. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  63174. * @param name defines the name of the mesh
  63175. * @param options defines the options used to create the mesh
  63176. * @param scene defines the hosting scene
  63177. * @returns the box mesh
  63178. */
  63179. MeshBuilder.CreateBox = function (name, options, scene) {
  63180. if (scene === void 0) { scene = null; }
  63181. var box = new BABYLON.Mesh(name, scene);
  63182. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63183. box._originalBuilderSideOrientation = options.sideOrientation;
  63184. var vertexData = BABYLON.VertexData.CreateBox(options);
  63185. vertexData.applyToMesh(box, options.updatable);
  63186. return box;
  63187. };
  63188. /**
  63189. * Creates a sphere mesh
  63190. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  63191. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  63192. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  63193. * * 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
  63194. * * 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)
  63195. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63196. * * 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
  63197. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63198. * @param name defines the name of the mesh
  63199. * @param options defines the options used to create the mesh
  63200. * @param scene defines the hosting scene
  63201. * @returns the sphere mesh
  63202. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  63203. */
  63204. MeshBuilder.CreateSphere = function (name, options, scene) {
  63205. var sphere = new BABYLON.Mesh(name, scene);
  63206. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63207. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63208. var vertexData = BABYLON.VertexData.CreateSphere(options);
  63209. vertexData.applyToMesh(sphere, options.updatable);
  63210. return sphere;
  63211. };
  63212. /**
  63213. * Creates a plane polygonal mesh. By default, this is a disc
  63214. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  63215. * * 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
  63216. * * 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
  63217. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63218. * * 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
  63219. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63220. * @param name defines the name of the mesh
  63221. * @param options defines the options used to create the mesh
  63222. * @param scene defines the hosting scene
  63223. * @returns the plane polygonal mesh
  63224. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  63225. */
  63226. MeshBuilder.CreateDisc = function (name, options, scene) {
  63227. if (scene === void 0) { scene = null; }
  63228. var disc = new BABYLON.Mesh(name, scene);
  63229. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63230. disc._originalBuilderSideOrientation = options.sideOrientation;
  63231. var vertexData = BABYLON.VertexData.CreateDisc(options);
  63232. vertexData.applyToMesh(disc, options.updatable);
  63233. return disc;
  63234. };
  63235. /**
  63236. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  63237. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  63238. * * 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`)
  63239. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  63240. * * 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
  63241. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63242. * * 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
  63243. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63244. * @param name defines the name of the mesh
  63245. * @param options defines the options used to create the mesh
  63246. * @param scene defines the hosting scene
  63247. * @returns the icosahedron mesh
  63248. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  63249. */
  63250. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  63251. var sphere = new BABYLON.Mesh(name, scene);
  63252. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63253. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63254. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  63255. vertexData.applyToMesh(sphere, options.updatable);
  63256. return sphere;
  63257. };
  63258. ;
  63259. /**
  63260. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63261. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  63262. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  63263. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  63264. * * 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
  63265. * * 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
  63266. * * 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
  63267. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63268. * * 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
  63269. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63270. * * 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
  63271. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  63272. * * 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
  63273. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  63274. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63275. * @param name defines the name of the mesh
  63276. * @param options defines the options used to create the mesh
  63277. * @param scene defines the hosting scene
  63278. * @returns the ribbon mesh
  63279. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  63280. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63281. */
  63282. MeshBuilder.CreateRibbon = function (name, options, scene) {
  63283. if (scene === void 0) { scene = null; }
  63284. var pathArray = options.pathArray;
  63285. var closeArray = options.closeArray;
  63286. var closePath = options.closePath;
  63287. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63288. var instance = options.instance;
  63289. var updatable = options.updatable;
  63290. if (instance) { // existing ribbon instance update
  63291. // positionFunction : ribbon case
  63292. // only pathArray and sideOrientation parameters are taken into account for positions update
  63293. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  63294. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  63295. var positionFunction = function (positions) {
  63296. var minlg = pathArray[0].length;
  63297. var i = 0;
  63298. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  63299. for (var si = 1; si <= ns; si++) {
  63300. for (var p = 0; p < pathArray.length; p++) {
  63301. var path = pathArray[p];
  63302. var l = path.length;
  63303. minlg = (minlg < l) ? minlg : l;
  63304. var j = 0;
  63305. while (j < minlg) {
  63306. positions[i] = path[j].x;
  63307. positions[i + 1] = path[j].y;
  63308. positions[i + 2] = path[j].z;
  63309. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  63310. BABYLON.Tmp.Vector3[0].x = path[j].x;
  63311. }
  63312. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  63313. BABYLON.Tmp.Vector3[1].x = path[j].x;
  63314. }
  63315. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  63316. BABYLON.Tmp.Vector3[0].y = path[j].y;
  63317. }
  63318. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  63319. BABYLON.Tmp.Vector3[1].y = path[j].y;
  63320. }
  63321. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  63322. BABYLON.Tmp.Vector3[0].z = path[j].z;
  63323. }
  63324. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  63325. BABYLON.Tmp.Vector3[1].z = path[j].z;
  63326. }
  63327. j++;
  63328. i += 3;
  63329. }
  63330. if (instance._closePath) {
  63331. positions[i] = path[0].x;
  63332. positions[i + 1] = path[0].y;
  63333. positions[i + 2] = path[0].z;
  63334. i += 3;
  63335. }
  63336. }
  63337. }
  63338. };
  63339. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63340. positionFunction(positions);
  63341. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  63342. instance._boundingInfo.update(instance._worldMatrix);
  63343. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63344. if (options.colors) {
  63345. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63346. for (var c = 0; c < options.colors.length; c++) {
  63347. colors[c * 4] = options.colors[c].r;
  63348. colors[c * 4 + 1] = options.colors[c].g;
  63349. colors[c * 4 + 2] = options.colors[c].b;
  63350. colors[c * 4 + 3] = options.colors[c].a;
  63351. }
  63352. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  63353. }
  63354. if (options.uvs) {
  63355. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63356. for (var i = 0; i < options.uvs.length; i++) {
  63357. uvs[i * 2] = options.uvs[i].x;
  63358. uvs[i * 2 + 1] = options.uvs[i].y;
  63359. }
  63360. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  63361. }
  63362. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  63363. var indices = instance.getIndices();
  63364. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63365. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  63366. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  63367. if (instance._closePath) {
  63368. var indexFirst = 0;
  63369. var indexLast = 0;
  63370. for (var p = 0; p < pathArray.length; p++) {
  63371. indexFirst = instance._idx[p] * 3;
  63372. if (p + 1 < pathArray.length) {
  63373. indexLast = (instance._idx[p + 1] - 1) * 3;
  63374. }
  63375. else {
  63376. indexLast = normals.length - 3;
  63377. }
  63378. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  63379. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  63380. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  63381. normals[indexLast] = normals[indexFirst];
  63382. normals[indexLast + 1] = normals[indexFirst + 1];
  63383. normals[indexLast + 2] = normals[indexFirst + 2];
  63384. }
  63385. }
  63386. if (!(instance.areNormalsFrozen)) {
  63387. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  63388. }
  63389. }
  63390. return instance;
  63391. }
  63392. else { // new ribbon creation
  63393. var ribbon = new BABYLON.Mesh(name, scene);
  63394. ribbon._originalBuilderSideOrientation = sideOrientation;
  63395. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  63396. if (closePath) {
  63397. ribbon._idx = vertexData._idx;
  63398. }
  63399. ribbon._closePath = closePath;
  63400. ribbon._closeArray = closeArray;
  63401. vertexData.applyToMesh(ribbon, updatable);
  63402. return ribbon;
  63403. }
  63404. };
  63405. /**
  63406. * Creates a cylinder or a cone mesh
  63407. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  63408. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  63409. * * 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.
  63410. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  63411. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  63412. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  63413. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  63414. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  63415. * * 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).
  63416. * * 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
  63417. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  63418. * * 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
  63419. * * 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.
  63420. * * If `enclose` is false, a ring surface is one element.
  63421. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  63422. * * 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
  63423. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63424. * * 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
  63425. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63426. * @param name defines the name of the mesh
  63427. * @param options defines the options used to create the mesh
  63428. * @param scene defines the hosting scene
  63429. * @returns the cylinder mesh
  63430. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  63431. */
  63432. MeshBuilder.CreateCylinder = function (name, options, scene) {
  63433. var cylinder = new BABYLON.Mesh(name, scene);
  63434. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63435. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  63436. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  63437. vertexData.applyToMesh(cylinder, options.updatable);
  63438. return cylinder;
  63439. };
  63440. /**
  63441. * Creates a torus mesh
  63442. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  63443. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  63444. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  63445. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63446. * * 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
  63447. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63448. * @param name defines the name of the mesh
  63449. * @param options defines the options used to create the mesh
  63450. * @param scene defines the hosting scene
  63451. * @returns the torus mesh
  63452. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  63453. */
  63454. MeshBuilder.CreateTorus = function (name, options, scene) {
  63455. var torus = new BABYLON.Mesh(name, scene);
  63456. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63457. torus._originalBuilderSideOrientation = options.sideOrientation;
  63458. var vertexData = BABYLON.VertexData.CreateTorus(options);
  63459. vertexData.applyToMesh(torus, options.updatable);
  63460. return torus;
  63461. };
  63462. /**
  63463. * Creates a torus knot mesh
  63464. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  63465. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  63466. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  63467. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  63468. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63469. * * 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
  63470. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63471. * @param name defines the name of the mesh
  63472. * @param options defines the options used to create the mesh
  63473. * @param scene defines the hosting scene
  63474. * @returns the torus knot mesh
  63475. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  63476. */
  63477. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  63478. var torusKnot = new BABYLON.Mesh(name, scene);
  63479. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63480. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  63481. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  63482. vertexData.applyToMesh(torusKnot, options.updatable);
  63483. return torusKnot;
  63484. };
  63485. /**
  63486. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  63487. * * 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
  63488. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  63489. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  63490. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  63491. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  63492. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  63493. * * 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
  63494. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  63495. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63496. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  63497. * @param name defines the name of the new line system
  63498. * @param options defines the options used to create the line system
  63499. * @param scene defines the hosting scene
  63500. * @returns a new line system mesh
  63501. */
  63502. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  63503. var instance = options.instance;
  63504. var lines = options.lines;
  63505. var colors = options.colors;
  63506. if (instance) { // lines update
  63507. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63508. var vertexColor;
  63509. var lineColors;
  63510. if (colors) {
  63511. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63512. }
  63513. var i = 0;
  63514. var c = 0;
  63515. for (var l = 0; l < lines.length; l++) {
  63516. var points = lines[l];
  63517. for (var p = 0; p < points.length; p++) {
  63518. positions[i] = points[p].x;
  63519. positions[i + 1] = points[p].y;
  63520. positions[i + 2] = points[p].z;
  63521. if (colors && vertexColor) {
  63522. lineColors = colors[l];
  63523. vertexColor[c] = lineColors[p].r;
  63524. vertexColor[c + 1] = lineColors[p].g;
  63525. vertexColor[c + 2] = lineColors[p].b;
  63526. vertexColor[c + 3] = lineColors[p].a;
  63527. c += 4;
  63528. }
  63529. i += 3;
  63530. }
  63531. }
  63532. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63533. if (colors && vertexColor) {
  63534. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  63535. }
  63536. return instance;
  63537. }
  63538. // line system creation
  63539. var useVertexColor = (colors) ? true : false;
  63540. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  63541. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  63542. vertexData.applyToMesh(lineSystem, options.updatable);
  63543. return lineSystem;
  63544. };
  63545. /**
  63546. * Creates a line mesh
  63547. * 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
  63548. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63549. * * The parameter `points` is an array successive Vector3
  63550. * * 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
  63551. * * The optional parameter `colors` is an array of successive Color4, one per line point
  63552. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  63553. * * When updating an instance, remember that only point positions can change, not the number of points
  63554. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63555. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  63556. * @param name defines the name of the new line system
  63557. * @param options defines the options used to create the line system
  63558. * @param scene defines the hosting scene
  63559. * @returns a new line mesh
  63560. */
  63561. MeshBuilder.CreateLines = function (name, options, scene) {
  63562. if (scene === void 0) { scene = null; }
  63563. var colors = (options.colors) ? [options.colors] : null;
  63564. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  63565. return lines;
  63566. };
  63567. /**
  63568. * Creates a dashed line mesh
  63569. * * 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
  63570. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63571. * * The parameter `points` is an array successive Vector3
  63572. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  63573. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  63574. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  63575. * * 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
  63576. * * When updating an instance, remember that only point positions can change, not the number of points
  63577. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63578. * @param name defines the name of the mesh
  63579. * @param options defines the options used to create the mesh
  63580. * @param scene defines the hosting scene
  63581. * @returns the dashed line mesh
  63582. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  63583. */
  63584. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  63585. if (scene === void 0) { scene = null; }
  63586. var points = options.points;
  63587. var instance = options.instance;
  63588. var gapSize = options.gapSize || 1;
  63589. var dashSize = options.dashSize || 3;
  63590. if (instance) { // dashed lines update
  63591. var positionFunction = function (positions) {
  63592. var curvect = BABYLON.Vector3.Zero();
  63593. var nbSeg = positions.length / 6;
  63594. var lg = 0;
  63595. var nb = 0;
  63596. var shft = 0;
  63597. var dashshft = 0;
  63598. var curshft = 0;
  63599. var p = 0;
  63600. var i = 0;
  63601. var j = 0;
  63602. for (i = 0; i < points.length - 1; i++) {
  63603. points[i + 1].subtractToRef(points[i], curvect);
  63604. lg += curvect.length();
  63605. }
  63606. shft = lg / nbSeg;
  63607. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  63608. for (i = 0; i < points.length - 1; i++) {
  63609. points[i + 1].subtractToRef(points[i], curvect);
  63610. nb = Math.floor(curvect.length() / shft);
  63611. curvect.normalize();
  63612. j = 0;
  63613. while (j < nb && p < positions.length) {
  63614. curshft = shft * j;
  63615. positions[p] = points[i].x + curshft * curvect.x;
  63616. positions[p + 1] = points[i].y + curshft * curvect.y;
  63617. positions[p + 2] = points[i].z + curshft * curvect.z;
  63618. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  63619. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  63620. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  63621. p += 6;
  63622. j++;
  63623. }
  63624. }
  63625. while (p < positions.length) {
  63626. positions[p] = points[i].x;
  63627. positions[p + 1] = points[i].y;
  63628. positions[p + 2] = points[i].z;
  63629. p += 3;
  63630. }
  63631. };
  63632. instance.updateMeshPositions(positionFunction, false);
  63633. return instance;
  63634. }
  63635. // dashed lines creation
  63636. var dashedLines = new BABYLON.LinesMesh(name, scene);
  63637. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  63638. vertexData.applyToMesh(dashedLines, options.updatable);
  63639. dashedLines.dashSize = dashSize;
  63640. dashedLines.gapSize = gapSize;
  63641. return dashedLines;
  63642. };
  63643. /**
  63644. * 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.
  63645. * * 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.
  63646. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63647. * * 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.
  63648. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  63649. * * 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
  63650. * * 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
  63651. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  63652. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63653. * * 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
  63654. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  63655. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63656. * @param name defines the name of the mesh
  63657. * @param options defines the options used to create the mesh
  63658. * @param scene defines the hosting scene
  63659. * @returns the extruded shape mesh
  63660. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63661. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63662. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63663. */
  63664. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  63665. if (scene === void 0) { scene = null; }
  63666. var path = options.path;
  63667. var shape = options.shape;
  63668. var scale = options.scale || 1;
  63669. var rotation = options.rotation || 0;
  63670. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63671. var updatable = options.updatable;
  63672. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63673. var instance = options.instance || null;
  63674. var invertUV = options.invertUV || false;
  63675. 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);
  63676. };
  63677. /**
  63678. * Creates an custom extruded shape mesh.
  63679. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  63680. * * 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.
  63681. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63682. * * 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
  63683. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  63684. * * 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
  63685. * * It must returns a float value that will be the scale value applied to the shape on each path point
  63686. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  63687. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  63688. * * 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
  63689. * * 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
  63690. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  63691. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63692. * * 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
  63693. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63694. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63695. * @param name defines the name of the mesh
  63696. * @param options defines the options used to create the mesh
  63697. * @param scene defines the hosting scene
  63698. * @returns the custom extruded shape mesh
  63699. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  63700. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63701. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63702. */
  63703. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  63704. var path = options.path;
  63705. var shape = options.shape;
  63706. var scaleFunction = options.scaleFunction || (function () { return 1; });
  63707. var rotationFunction = options.rotationFunction || (function () { return 0; });
  63708. var ribbonCloseArray = options.ribbonCloseArray || false;
  63709. var ribbonClosePath = options.ribbonClosePath || false;
  63710. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63711. var updatable = options.updatable;
  63712. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63713. var instance = options.instance;
  63714. var invertUV = options.invertUV || false;
  63715. 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);
  63716. };
  63717. /**
  63718. * Creates lathe mesh.
  63719. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  63720. * * 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
  63721. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  63722. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  63723. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  63724. * * 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
  63725. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  63726. * * 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
  63727. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63728. * * 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
  63729. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63730. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63731. * @param name defines the name of the mesh
  63732. * @param options defines the options used to create the mesh
  63733. * @param scene defines the hosting scene
  63734. * @returns the lathe mesh
  63735. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  63736. */
  63737. MeshBuilder.CreateLathe = function (name, options, scene) {
  63738. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  63739. var closed = (options.closed === undefined) ? true : options.closed;
  63740. var shape = options.shape;
  63741. var radius = options.radius || 1;
  63742. var tessellation = options.tessellation || 64;
  63743. var clip = options.clip || 0;
  63744. var updatable = options.updatable;
  63745. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63746. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63747. var pi2 = Math.PI * 2;
  63748. var paths = new Array();
  63749. var invertUV = options.invertUV || false;
  63750. var i = 0;
  63751. var p = 0;
  63752. var step = pi2 / tessellation * arc;
  63753. var rotated;
  63754. var path = new Array();
  63755. for (i = 0; i <= tessellation - clip; i++) {
  63756. var path = [];
  63757. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  63758. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  63759. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  63760. }
  63761. for (p = 0; p < shape.length; p++) {
  63762. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  63763. path.push(rotated);
  63764. }
  63765. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  63766. 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));
  63767. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  63768. }
  63769. paths.push(path);
  63770. }
  63771. // lathe ribbon
  63772. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63773. return lathe;
  63774. };
  63775. /**
  63776. * Creates a plane mesh
  63777. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  63778. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  63779. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  63780. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63781. * * 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
  63782. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63783. * @param name defines the name of the mesh
  63784. * @param options defines the options used to create the mesh
  63785. * @param scene defines the hosting scene
  63786. * @returns the plane mesh
  63787. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63788. */
  63789. MeshBuilder.CreatePlane = function (name, options, scene) {
  63790. var plane = new BABYLON.Mesh(name, scene);
  63791. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63792. plane._originalBuilderSideOrientation = options.sideOrientation;
  63793. var vertexData = BABYLON.VertexData.CreatePlane(options);
  63794. vertexData.applyToMesh(plane, options.updatable);
  63795. if (options.sourcePlane) {
  63796. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  63797. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  63798. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  63799. plane.rotate(vectorProduct, product);
  63800. }
  63801. return plane;
  63802. };
  63803. /**
  63804. * Creates a ground mesh
  63805. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  63806. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  63807. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63808. * @param name defines the name of the mesh
  63809. * @param options defines the options used to create the mesh
  63810. * @param scene defines the hosting scene
  63811. * @returns the ground mesh
  63812. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63813. */
  63814. MeshBuilder.CreateGround = function (name, options, scene) {
  63815. var ground = new BABYLON.GroundMesh(name, scene);
  63816. ground._setReady(false);
  63817. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  63818. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  63819. ground._width = options.width || 1;
  63820. ground._height = options.height || 1;
  63821. ground._maxX = ground._width / 2;
  63822. ground._maxZ = ground._height / 2;
  63823. ground._minX = -ground._maxX;
  63824. ground._minZ = -ground._maxZ;
  63825. var vertexData = BABYLON.VertexData.CreateGround(options);
  63826. vertexData.applyToMesh(ground, options.updatable);
  63827. ground._setReady(true);
  63828. return ground;
  63829. };
  63830. /**
  63831. * Creates a tiled ground mesh
  63832. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  63833. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  63834. * * 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
  63835. * * 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
  63836. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63837. * @param name defines the name of the mesh
  63838. * @param options defines the options used to create the mesh
  63839. * @param scene defines the hosting scene
  63840. * @returns the tiled ground mesh
  63841. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  63842. */
  63843. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  63844. var tiledGround = new BABYLON.Mesh(name, scene);
  63845. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  63846. vertexData.applyToMesh(tiledGround, options.updatable);
  63847. return tiledGround;
  63848. };
  63849. /**
  63850. * Creates a ground mesh from a height map
  63851. * * The parameter `url` sets the URL of the height map image resource.
  63852. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  63853. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  63854. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  63855. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  63856. * * 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.
  63857. * * 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).
  63858. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63859. * @param name defines the name of the mesh
  63860. * @param url defines the url to the height map
  63861. * @param options defines the options used to create the mesh
  63862. * @param scene defines the hosting scene
  63863. * @returns the ground mesh
  63864. * @see http://doc.babylonjs.com/babylon101/height_map
  63865. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  63866. */
  63867. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  63868. var width = options.width || 10.0;
  63869. var height = options.height || 10.0;
  63870. var subdivisions = options.subdivisions || 1 | 0;
  63871. var minHeight = options.minHeight || 0.0;
  63872. var maxHeight = options.maxHeight || 1.0;
  63873. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  63874. var updatable = options.updatable;
  63875. var onReady = options.onReady;
  63876. var ground = new BABYLON.GroundMesh(name, scene);
  63877. ground._subdivisionsX = subdivisions;
  63878. ground._subdivisionsY = subdivisions;
  63879. ground._width = width;
  63880. ground._height = height;
  63881. ground._maxX = ground._width / 2.0;
  63882. ground._maxZ = ground._height / 2.0;
  63883. ground._minX = -ground._maxX;
  63884. ground._minZ = -ground._maxZ;
  63885. ground._setReady(false);
  63886. var onload = function (img) {
  63887. // Getting height map data
  63888. var canvas = document.createElement("canvas");
  63889. var context = canvas.getContext("2d");
  63890. if (!context) {
  63891. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  63892. }
  63893. if (scene.isDisposed) {
  63894. return;
  63895. }
  63896. var bufferWidth = img.width;
  63897. var bufferHeight = img.height;
  63898. canvas.width = bufferWidth;
  63899. canvas.height = bufferHeight;
  63900. context.drawImage(img, 0, 0);
  63901. // Create VertexData from map data
  63902. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  63903. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  63904. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  63905. width: width, height: height,
  63906. subdivisions: subdivisions,
  63907. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  63908. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  63909. });
  63910. vertexData.applyToMesh(ground, updatable);
  63911. //execute ready callback, if set
  63912. if (onReady) {
  63913. onReady(ground);
  63914. }
  63915. ground._setReady(true);
  63916. };
  63917. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  63918. return ground;
  63919. };
  63920. /**
  63921. * Creates a polygon mesh
  63922. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  63923. * * 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
  63924. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63925. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63926. * * 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)
  63927. * * Remember you can only change the shape positions, not their number when updating a polygon
  63928. * @param name defines the name of the mesh
  63929. * @param options defines the options used to create the mesh
  63930. * @param scene defines the hosting scene
  63931. * @returns the polygon mesh
  63932. */
  63933. MeshBuilder.CreatePolygon = function (name, options, scene) {
  63934. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63935. var shape = options.shape;
  63936. var holes = options.holes || [];
  63937. var depth = options.depth || 0;
  63938. var contours = [];
  63939. var hole = [];
  63940. for (var i = 0; i < shape.length; i++) {
  63941. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  63942. }
  63943. var epsilon = 0.00000001;
  63944. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  63945. contours.pop();
  63946. }
  63947. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  63948. for (var hNb = 0; hNb < holes.length; hNb++) {
  63949. hole = [];
  63950. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  63951. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  63952. }
  63953. polygonTriangulation.addHole(hole);
  63954. }
  63955. var polygon = polygonTriangulation.build(options.updatable, depth);
  63956. polygon._originalBuilderSideOrientation = options.sideOrientation;
  63957. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  63958. vertexData.applyToMesh(polygon, options.updatable);
  63959. return polygon;
  63960. };
  63961. ;
  63962. /**
  63963. * Creates an extruded polygon mesh, with depth in the Y direction.
  63964. * * 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)
  63965. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63966. * @param name defines the name of the mesh
  63967. * @param options defines the options used to create the mesh
  63968. * @param scene defines the hosting scene
  63969. * @returns the polygon mesh
  63970. */
  63971. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  63972. return MeshBuilder.CreatePolygon(name, options, scene);
  63973. };
  63974. ;
  63975. /**
  63976. * Creates a tube mesh.
  63977. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63978. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  63979. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  63980. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  63981. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  63982. * * 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)
  63983. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  63984. * * 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
  63985. * * 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
  63986. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63987. * * 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
  63988. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63989. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63990. * @param name defines the name of the mesh
  63991. * @param options defines the options used to create the mesh
  63992. * @param scene defines the hosting scene
  63993. * @returns the tube mesh
  63994. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63995. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  63996. */
  63997. MeshBuilder.CreateTube = function (name, options, scene) {
  63998. var path = options.path;
  63999. var instance = options.instance;
  64000. var radius = 1.0;
  64001. if (instance) {
  64002. radius = instance.radius;
  64003. }
  64004. if (options.radius !== undefined) {
  64005. radius = options.radius;
  64006. }
  64007. ;
  64008. var tessellation = options.tessellation || 64 | 0;
  64009. var radiusFunction = options.radiusFunction || null;
  64010. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64011. var invertUV = options.invertUV || false;
  64012. var updatable = options.updatable;
  64013. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64014. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  64015. // tube geometry
  64016. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  64017. var tangents = path3D.getTangents();
  64018. var normals = path3D.getNormals();
  64019. var distances = path3D.getDistances();
  64020. var pi2 = Math.PI * 2;
  64021. var step = pi2 / tessellation * arc;
  64022. var returnRadius = function () { return radius; };
  64023. var radiusFunctionFinal = radiusFunction || returnRadius;
  64024. var circlePath;
  64025. var rad;
  64026. var normal;
  64027. var rotated;
  64028. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64029. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64030. for (var i = 0; i < path.length; i++) {
  64031. rad = radiusFunctionFinal(i, distances[i]); // current radius
  64032. circlePath = Array(); // current circle array
  64033. normal = normals[i]; // current normal
  64034. for (var t = 0; t < tessellation; t++) {
  64035. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  64036. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  64037. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  64038. rotated.scaleInPlace(rad).addInPlace(path[i]);
  64039. circlePath[t] = rotated;
  64040. }
  64041. circlePaths[index] = circlePath;
  64042. index++;
  64043. }
  64044. // cap
  64045. var capPath = function (nbPoints, pathIndex) {
  64046. var pointCap = Array();
  64047. for (var i = 0; i < nbPoints; i++) {
  64048. pointCap.push(path[pathIndex]);
  64049. }
  64050. return pointCap;
  64051. };
  64052. switch (cap) {
  64053. case BABYLON.Mesh.NO_CAP:
  64054. break;
  64055. case BABYLON.Mesh.CAP_START:
  64056. circlePaths[0] = capPath(tessellation, 0);
  64057. circlePaths[1] = circlePaths[2].slice(0);
  64058. break;
  64059. case BABYLON.Mesh.CAP_END:
  64060. circlePaths[index] = circlePaths[index - 1].slice(0);
  64061. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64062. break;
  64063. case BABYLON.Mesh.CAP_ALL:
  64064. circlePaths[0] = capPath(tessellation, 0);
  64065. circlePaths[1] = circlePaths[2].slice(0);
  64066. circlePaths[index] = circlePaths[index - 1].slice(0);
  64067. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64068. break;
  64069. default:
  64070. break;
  64071. }
  64072. return circlePaths;
  64073. };
  64074. var path3D;
  64075. var pathArray;
  64076. if (instance) { // tube update
  64077. var arc = options.arc || instance.arc;
  64078. path3D = (instance.path3D).update(path);
  64079. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  64080. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  64081. instance.path3D = path3D;
  64082. instance.pathArray = pathArray;
  64083. instance.arc = arc;
  64084. instance.radius = radius;
  64085. return instance;
  64086. }
  64087. // tube creation
  64088. path3D = new BABYLON.Path3D(path);
  64089. var newPathArray = new Array();
  64090. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64091. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  64092. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64093. tube.pathArray = pathArray;
  64094. tube.path3D = path3D;
  64095. tube.tessellation = tessellation;
  64096. tube.cap = cap;
  64097. tube.arc = options.arc;
  64098. tube.radius = radius;
  64099. return tube;
  64100. };
  64101. /**
  64102. * Creates a polyhedron mesh
  64103. * * 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
  64104. * * The parameter `size` (positive float, default 1) sets the polygon size
  64105. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  64106. * * 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`
  64107. * * 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
  64108. * * 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)`)
  64109. * * 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
  64110. * * 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
  64111. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64112. * * 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
  64113. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64114. * @param name defines the name of the mesh
  64115. * @param options defines the options used to create the mesh
  64116. * @param scene defines the hosting scene
  64117. * @returns the polyhedron mesh
  64118. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  64119. */
  64120. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  64121. var polyhedron = new BABYLON.Mesh(name, scene);
  64122. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64123. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  64124. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  64125. vertexData.applyToMesh(polyhedron, options.updatable);
  64126. return polyhedron;
  64127. };
  64128. /**
  64129. * Creates a decal mesh.
  64130. * 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
  64131. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  64132. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  64133. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  64134. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  64135. * @param name defines the name of the mesh
  64136. * @param sourceMesh defines the mesh where the decal must be applied
  64137. * @param options defines the options used to create the mesh
  64138. * @param scene defines the hosting scene
  64139. * @returns the decal mesh
  64140. * @see http://doc.babylonjs.com/how_to/decals
  64141. */
  64142. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  64143. var indices = sourceMesh.getIndices();
  64144. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64145. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64146. var position = options.position || BABYLON.Vector3.Zero();
  64147. var normal = options.normal || BABYLON.Vector3.Up();
  64148. var size = options.size || BABYLON.Vector3.One();
  64149. var angle = options.angle || 0;
  64150. // Getting correct rotation
  64151. if (!normal) {
  64152. var target = new BABYLON.Vector3(0, 0, 1);
  64153. var camera = sourceMesh.getScene().activeCamera;
  64154. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  64155. normal = camera.globalPosition.subtract(cameraWorldTarget);
  64156. }
  64157. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  64158. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  64159. var pitch = Math.atan2(normal.y, len);
  64160. // Matrix
  64161. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  64162. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  64163. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  64164. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  64165. var vertexData = new BABYLON.VertexData();
  64166. vertexData.indices = [];
  64167. vertexData.positions = [];
  64168. vertexData.normals = [];
  64169. vertexData.uvs = [];
  64170. var currentVertexDataIndex = 0;
  64171. var extractDecalVector3 = function (indexId) {
  64172. var result = new BABYLON.PositionNormalVertex();
  64173. if (!indices || !positions || !normals) {
  64174. return result;
  64175. }
  64176. var vertexId = indices[indexId];
  64177. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  64178. // Send vector to decal local world
  64179. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  64180. // Get normal
  64181. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  64182. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  64183. return result;
  64184. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  64185. var clip = function (vertices, axis) {
  64186. if (vertices.length === 0) {
  64187. return vertices;
  64188. }
  64189. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  64190. var clipVertices = function (v0, v1) {
  64191. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  64192. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  64193. };
  64194. var result = new Array();
  64195. for (var index = 0; index < vertices.length; index += 3) {
  64196. var v1Out;
  64197. var v2Out;
  64198. var v3Out;
  64199. var total = 0;
  64200. var nV1 = null;
  64201. var nV2 = null;
  64202. var nV3 = null;
  64203. var nV4 = null;
  64204. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  64205. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  64206. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  64207. v1Out = d1 > 0;
  64208. v2Out = d2 > 0;
  64209. v3Out = d3 > 0;
  64210. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  64211. switch (total) {
  64212. case 0:
  64213. result.push(vertices[index]);
  64214. result.push(vertices[index + 1]);
  64215. result.push(vertices[index + 2]);
  64216. break;
  64217. case 1:
  64218. if (v1Out) {
  64219. nV1 = vertices[index + 1];
  64220. nV2 = vertices[index + 2];
  64221. nV3 = clipVertices(vertices[index], nV1);
  64222. nV4 = clipVertices(vertices[index], nV2);
  64223. }
  64224. if (v2Out) {
  64225. nV1 = vertices[index];
  64226. nV2 = vertices[index + 2];
  64227. nV3 = clipVertices(vertices[index + 1], nV1);
  64228. nV4 = clipVertices(vertices[index + 1], nV2);
  64229. result.push(nV3);
  64230. result.push(nV2.clone());
  64231. result.push(nV1.clone());
  64232. result.push(nV2.clone());
  64233. result.push(nV3.clone());
  64234. result.push(nV4);
  64235. break;
  64236. }
  64237. if (v3Out) {
  64238. nV1 = vertices[index];
  64239. nV2 = vertices[index + 1];
  64240. nV3 = clipVertices(vertices[index + 2], nV1);
  64241. nV4 = clipVertices(vertices[index + 2], nV2);
  64242. }
  64243. if (nV1 && nV2 && nV3 && nV4) {
  64244. result.push(nV1.clone());
  64245. result.push(nV2.clone());
  64246. result.push(nV3);
  64247. result.push(nV4);
  64248. result.push(nV3.clone());
  64249. result.push(nV2.clone());
  64250. }
  64251. break;
  64252. case 2:
  64253. if (!v1Out) {
  64254. nV1 = vertices[index].clone();
  64255. nV2 = clipVertices(nV1, vertices[index + 1]);
  64256. nV3 = clipVertices(nV1, vertices[index + 2]);
  64257. result.push(nV1);
  64258. result.push(nV2);
  64259. result.push(nV3);
  64260. }
  64261. if (!v2Out) {
  64262. nV1 = vertices[index + 1].clone();
  64263. nV2 = clipVertices(nV1, vertices[index + 2]);
  64264. nV3 = clipVertices(nV1, vertices[index]);
  64265. result.push(nV1);
  64266. result.push(nV2);
  64267. result.push(nV3);
  64268. }
  64269. if (!v3Out) {
  64270. nV1 = vertices[index + 2].clone();
  64271. nV2 = clipVertices(nV1, vertices[index]);
  64272. nV3 = clipVertices(nV1, vertices[index + 1]);
  64273. result.push(nV1);
  64274. result.push(nV2);
  64275. result.push(nV3);
  64276. }
  64277. break;
  64278. case 3:
  64279. break;
  64280. }
  64281. }
  64282. return result;
  64283. };
  64284. for (var index = 0; index < indices.length; index += 3) {
  64285. var faceVertices = new Array();
  64286. faceVertices.push(extractDecalVector3(index));
  64287. faceVertices.push(extractDecalVector3(index + 1));
  64288. faceVertices.push(extractDecalVector3(index + 2));
  64289. // Clip
  64290. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  64291. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  64292. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  64293. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  64294. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  64295. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  64296. if (faceVertices.length === 0) {
  64297. continue;
  64298. }
  64299. // Add UVs and get back to world
  64300. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  64301. var vertex = faceVertices[vIndex];
  64302. //TODO check for Int32Array | Uint32Array | Uint16Array
  64303. vertexData.indices.push(currentVertexDataIndex);
  64304. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  64305. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  64306. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  64307. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  64308. currentVertexDataIndex++;
  64309. }
  64310. }
  64311. // Return mesh
  64312. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  64313. vertexData.applyToMesh(decal);
  64314. decal.position = position.clone();
  64315. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  64316. return decal;
  64317. };
  64318. // Privates
  64319. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  64320. // extrusion geometry
  64321. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  64322. var tangents = path3D.getTangents();
  64323. var normals = path3D.getNormals();
  64324. var binormals = path3D.getBinormals();
  64325. var distances = path3D.getDistances();
  64326. var angle = 0;
  64327. var returnScale = function () { return scale !== null ? scale : 1; };
  64328. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  64329. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  64330. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  64331. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64332. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64333. for (var i = 0; i < curve.length; i++) {
  64334. var shapePath = new Array();
  64335. var angleStep = rotate(i, distances[i]);
  64336. var scaleRatio = scl(i, distances[i]);
  64337. for (var p = 0; p < shape.length; p++) {
  64338. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  64339. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  64340. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  64341. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  64342. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  64343. shapePath[p] = rotated;
  64344. }
  64345. shapePaths[index] = shapePath;
  64346. angle += angleStep;
  64347. index++;
  64348. }
  64349. // cap
  64350. var capPath = function (shapePath) {
  64351. var pointCap = Array();
  64352. var barycenter = BABYLON.Vector3.Zero();
  64353. var i;
  64354. for (i = 0; i < shapePath.length; i++) {
  64355. barycenter.addInPlace(shapePath[i]);
  64356. }
  64357. barycenter.scaleInPlace(1.0 / shapePath.length);
  64358. for (i = 0; i < shapePath.length; i++) {
  64359. pointCap.push(barycenter);
  64360. }
  64361. return pointCap;
  64362. };
  64363. switch (cap) {
  64364. case BABYLON.Mesh.NO_CAP:
  64365. break;
  64366. case BABYLON.Mesh.CAP_START:
  64367. shapePaths[0] = capPath(shapePaths[2]);
  64368. shapePaths[1] = shapePaths[2];
  64369. break;
  64370. case BABYLON.Mesh.CAP_END:
  64371. shapePaths[index] = shapePaths[index - 1];
  64372. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64373. break;
  64374. case BABYLON.Mesh.CAP_ALL:
  64375. shapePaths[0] = capPath(shapePaths[2]);
  64376. shapePaths[1] = shapePaths[2];
  64377. shapePaths[index] = shapePaths[index - 1];
  64378. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64379. break;
  64380. default:
  64381. break;
  64382. }
  64383. return shapePaths;
  64384. };
  64385. var path3D;
  64386. var pathArray;
  64387. if (instance) { // instance update
  64388. path3D = (instance.path3D).update(curve);
  64389. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  64390. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  64391. return instance;
  64392. }
  64393. // extruded shape creation
  64394. path3D = new BABYLON.Path3D(curve);
  64395. var newShapePaths = new Array();
  64396. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64397. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  64398. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  64399. extrudedGeneric.pathArray = pathArray;
  64400. extrudedGeneric.path3D = path3D;
  64401. extrudedGeneric.cap = cap;
  64402. return extrudedGeneric;
  64403. };
  64404. return MeshBuilder;
  64405. }());
  64406. BABYLON.MeshBuilder = MeshBuilder;
  64407. })(BABYLON || (BABYLON = {}));
  64408. //# sourceMappingURL=babylon.meshBuilder.js.map
  64409. var BABYLON;
  64410. (function (BABYLON) {
  64411. /**
  64412. * Draco compression (https://google.github.io/draco/)
  64413. *
  64414. * This class wraps the Draco module.
  64415. *
  64416. * **Encoder**
  64417. *
  64418. * The encoder is not currently implemented.
  64419. *
  64420. * **Decoder**
  64421. *
  64422. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  64423. *
  64424. * To update the configuration, use the following code:
  64425. * ```javascript
  64426. * BABYLON.DracoCompression.Configuration = {
  64427. * decoder: {
  64428. * wasmUrl: "<url to the WebAssembly library>",
  64429. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  64430. * fallbackUrl: "<url to the fallback JavaScript library>",
  64431. * }
  64432. * };
  64433. * ```
  64434. *
  64435. * 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.
  64436. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  64437. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  64438. *
  64439. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  64440. * ```javascript
  64441. * var dracoCompression = new BABYLON.DracoCompression();
  64442. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  64443. * [BABYLON.VertexBuffer.PositionKind]: 0
  64444. * });
  64445. * ```
  64446. *
  64447. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  64448. */
  64449. var DracoCompression = /** @class */ (function () {
  64450. /**
  64451. * Constructor
  64452. */
  64453. function DracoCompression() {
  64454. }
  64455. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  64456. /**
  64457. * Returns true if the decoder is available.
  64458. */
  64459. get: function () {
  64460. if (typeof DracoDecoderModule !== "undefined") {
  64461. return true;
  64462. }
  64463. var decoder = DracoCompression.Configuration.decoder;
  64464. if (decoder) {
  64465. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64466. return true;
  64467. }
  64468. if (decoder.fallbackUrl) {
  64469. return true;
  64470. }
  64471. }
  64472. return false;
  64473. },
  64474. enumerable: true,
  64475. configurable: true
  64476. });
  64477. /**
  64478. * Stop all async operations and release resources.
  64479. */
  64480. DracoCompression.prototype.dispose = function () {
  64481. };
  64482. /**
  64483. * Decode Draco compressed mesh data to vertex data.
  64484. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  64485. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  64486. * @returns A promise that resolves with the decoded vertex data
  64487. */
  64488. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  64489. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  64490. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  64491. var module = wrappedModule.module;
  64492. var vertexData = new BABYLON.VertexData();
  64493. var buffer = new module.DecoderBuffer();
  64494. buffer.Init(dataView, dataView.byteLength);
  64495. var decoder = new module.Decoder();
  64496. var geometry;
  64497. var status;
  64498. try {
  64499. var type = decoder.GetEncodedGeometryType(buffer);
  64500. switch (type) {
  64501. case module.TRIANGULAR_MESH:
  64502. geometry = new module.Mesh();
  64503. status = decoder.DecodeBufferToMesh(buffer, geometry);
  64504. break;
  64505. case module.POINT_CLOUD:
  64506. geometry = new module.PointCloud();
  64507. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  64508. break;
  64509. default:
  64510. throw new Error("Invalid geometry type " + type);
  64511. }
  64512. if (!status.ok() || !geometry.ptr) {
  64513. throw new Error(status.error_msg());
  64514. }
  64515. var numPoints = geometry.num_points();
  64516. if (type === module.TRIANGULAR_MESH) {
  64517. var numFaces = geometry.num_faces();
  64518. var faceIndices = new module.DracoInt32Array();
  64519. try {
  64520. var indices = new Uint32Array(numFaces * 3);
  64521. for (var i = 0; i < numFaces; i++) {
  64522. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  64523. var offset = i * 3;
  64524. indices[offset + 0] = faceIndices.GetValue(0);
  64525. indices[offset + 1] = faceIndices.GetValue(1);
  64526. indices[offset + 2] = faceIndices.GetValue(2);
  64527. }
  64528. vertexData.indices = indices;
  64529. }
  64530. finally {
  64531. module.destroy(faceIndices);
  64532. }
  64533. }
  64534. for (var kind in attributes) {
  64535. var uniqueId = attributes[kind];
  64536. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  64537. var dracoData = new module.DracoFloat32Array();
  64538. try {
  64539. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  64540. var babylonData = new Float32Array(numPoints * attribute.num_components());
  64541. for (var i = 0; i < babylonData.length; i++) {
  64542. babylonData[i] = dracoData.GetValue(i);
  64543. }
  64544. vertexData.set(babylonData, kind);
  64545. }
  64546. finally {
  64547. module.destroy(dracoData);
  64548. }
  64549. }
  64550. }
  64551. finally {
  64552. if (geometry) {
  64553. module.destroy(geometry);
  64554. }
  64555. module.destroy(decoder);
  64556. module.destroy(buffer);
  64557. }
  64558. return vertexData;
  64559. });
  64560. };
  64561. DracoCompression._GetDecoderModule = function () {
  64562. if (!DracoCompression._DecoderModulePromise) {
  64563. var promise = null;
  64564. var config_1 = {};
  64565. if (typeof DracoDecoderModule !== "undefined") {
  64566. promise = Promise.resolve();
  64567. }
  64568. else {
  64569. var decoder = DracoCompression.Configuration.decoder;
  64570. if (decoder) {
  64571. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64572. promise = Promise.all([
  64573. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  64574. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  64575. config_1.wasmBinary = data;
  64576. })
  64577. ]);
  64578. }
  64579. else if (decoder.fallbackUrl) {
  64580. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  64581. }
  64582. }
  64583. }
  64584. if (!promise) {
  64585. throw new Error("Draco decoder module is not available");
  64586. }
  64587. DracoCompression._DecoderModulePromise = promise.then(function () {
  64588. return new Promise(function (resolve) {
  64589. config_1.onModuleLoaded = function (decoderModule) {
  64590. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  64591. resolve({ module: decoderModule });
  64592. };
  64593. DracoDecoderModule(config_1);
  64594. });
  64595. });
  64596. }
  64597. return DracoCompression._DecoderModulePromise;
  64598. };
  64599. DracoCompression._LoadScriptAsync = function (url) {
  64600. return new Promise(function (resolve, reject) {
  64601. BABYLON.Tools.LoadScript(url, function () {
  64602. resolve();
  64603. }, function (message) {
  64604. reject(new Error(message));
  64605. });
  64606. });
  64607. };
  64608. DracoCompression._LoadFileAsync = function (url) {
  64609. return new Promise(function (resolve, reject) {
  64610. BABYLON.Tools.LoadFile(url, function (data) {
  64611. resolve(data);
  64612. }, undefined, undefined, true, function (request, exception) {
  64613. reject(exception);
  64614. });
  64615. });
  64616. };
  64617. /**
  64618. * The configuration. Defaults to the following urls:
  64619. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  64620. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  64621. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64622. */
  64623. DracoCompression.Configuration = {
  64624. decoder: {
  64625. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  64626. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  64627. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64628. }
  64629. };
  64630. return DracoCompression;
  64631. }());
  64632. BABYLON.DracoCompression = DracoCompression;
  64633. })(BABYLON || (BABYLON = {}));
  64634. //# sourceMappingURL=babylon.dracoCompression.js.map
  64635. var BABYLON;
  64636. (function (BABYLON) {
  64637. var AudioEngine = /** @class */ (function () {
  64638. function AudioEngine() {
  64639. this._audioContext = null;
  64640. this._audioContextInitialized = false;
  64641. this.canUseWebAudio = false;
  64642. this.WarnedWebAudioUnsupported = false;
  64643. this.unlocked = false;
  64644. this.isMP3supported = false;
  64645. this.isOGGsupported = false;
  64646. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  64647. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  64648. this.canUseWebAudio = true;
  64649. }
  64650. var audioElem = document.createElement('audio');
  64651. try {
  64652. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  64653. this.isMP3supported = true;
  64654. }
  64655. }
  64656. catch (e) {
  64657. // protect error during capability check.
  64658. }
  64659. try {
  64660. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  64661. this.isOGGsupported = true;
  64662. }
  64663. }
  64664. catch (e) {
  64665. // protect error during capability check.
  64666. }
  64667. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  64668. this._unlockiOSaudio();
  64669. }
  64670. else {
  64671. this.unlocked = true;
  64672. }
  64673. }
  64674. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  64675. get: function () {
  64676. if (!this._audioContextInitialized) {
  64677. this._initializeAudioContext();
  64678. }
  64679. return this._audioContext;
  64680. },
  64681. enumerable: true,
  64682. configurable: true
  64683. });
  64684. AudioEngine.prototype._unlockiOSaudio = function () {
  64685. var _this = this;
  64686. var unlockaudio = function () {
  64687. if (!_this.audioContext) {
  64688. return;
  64689. }
  64690. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  64691. var source = _this.audioContext.createBufferSource();
  64692. source.buffer = buffer;
  64693. source.connect(_this.audioContext.destination);
  64694. source.start(0);
  64695. setTimeout(function () {
  64696. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  64697. _this.unlocked = true;
  64698. window.removeEventListener('touchend', unlockaudio, false);
  64699. if (_this.onAudioUnlocked) {
  64700. _this.onAudioUnlocked();
  64701. }
  64702. }
  64703. }, 0);
  64704. };
  64705. window.addEventListener('touchend', unlockaudio, false);
  64706. };
  64707. AudioEngine.prototype._initializeAudioContext = function () {
  64708. try {
  64709. if (this.canUseWebAudio) {
  64710. this._audioContext = new AudioContext();
  64711. // create a global volume gain node
  64712. this.masterGain = this._audioContext.createGain();
  64713. this.masterGain.gain.value = 1;
  64714. this.masterGain.connect(this._audioContext.destination);
  64715. this._audioContextInitialized = true;
  64716. }
  64717. }
  64718. catch (e) {
  64719. this.canUseWebAudio = false;
  64720. BABYLON.Tools.Error("Web Audio: " + e.message);
  64721. }
  64722. };
  64723. AudioEngine.prototype.dispose = function () {
  64724. if (this.canUseWebAudio && this._audioContextInitialized) {
  64725. if (this._connectedAnalyser && this._audioContext) {
  64726. this._connectedAnalyser.stopDebugCanvas();
  64727. this._connectedAnalyser.dispose();
  64728. this.masterGain.disconnect();
  64729. this.masterGain.connect(this._audioContext.destination);
  64730. this._connectedAnalyser = null;
  64731. }
  64732. this.masterGain.gain.value = 1;
  64733. }
  64734. this.WarnedWebAudioUnsupported = false;
  64735. };
  64736. AudioEngine.prototype.getGlobalVolume = function () {
  64737. if (this.canUseWebAudio && this._audioContextInitialized) {
  64738. return this.masterGain.gain.value;
  64739. }
  64740. else {
  64741. return -1;
  64742. }
  64743. };
  64744. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  64745. if (this.canUseWebAudio && this._audioContextInitialized) {
  64746. this.masterGain.gain.value = newVolume;
  64747. }
  64748. };
  64749. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  64750. if (this._connectedAnalyser) {
  64751. this._connectedAnalyser.stopDebugCanvas();
  64752. }
  64753. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  64754. this._connectedAnalyser = analyser;
  64755. this.masterGain.disconnect();
  64756. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  64757. }
  64758. };
  64759. return AudioEngine;
  64760. }());
  64761. BABYLON.AudioEngine = AudioEngine;
  64762. })(BABYLON || (BABYLON = {}));
  64763. //# sourceMappingURL=babylon.audioEngine.js.map
  64764. var BABYLON;
  64765. (function (BABYLON) {
  64766. var Sound = /** @class */ (function () {
  64767. /**
  64768. * Create a sound and attach it to a scene
  64769. * @param name Name of your sound
  64770. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  64771. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  64772. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  64773. */
  64774. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  64775. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  64776. var _this = this;
  64777. this.autoplay = false;
  64778. this.loop = false;
  64779. this.useCustomAttenuation = false;
  64780. this.spatialSound = false;
  64781. this.refDistance = 1;
  64782. this.rolloffFactor = 1;
  64783. this.maxDistance = 100;
  64784. this.distanceModel = "linear";
  64785. this._panningModel = "equalpower";
  64786. /**
  64787. * Observable event when the current playing sound finishes.
  64788. */
  64789. this.onEndedObservable = new BABYLON.Observable();
  64790. this._playbackRate = 1;
  64791. this._streaming = false;
  64792. this._startTime = 0;
  64793. this._startOffset = 0;
  64794. this._position = BABYLON.Vector3.Zero();
  64795. /** @hidden */
  64796. this._positionInEmitterSpace = false;
  64797. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  64798. this._volume = 1;
  64799. this._isReadyToPlay = false;
  64800. this.isPlaying = false;
  64801. this.isPaused = false;
  64802. this._isDirectional = false;
  64803. // Used if you'd like to create a directional sound.
  64804. // If not set, the sound will be omnidirectional
  64805. this._coneInnerAngle = 360;
  64806. this._coneOuterAngle = 360;
  64807. this._coneOuterGain = 0;
  64808. this._isOutputConnected = false;
  64809. this._urlType = "Unknown";
  64810. this.name = name;
  64811. this._scene = scene;
  64812. this._readyToPlayCallback = readyToPlayCallback;
  64813. // Default custom attenuation function is a linear attenuation
  64814. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  64815. if (currentDistance < maxDistance) {
  64816. return currentVolume * (1 - currentDistance / maxDistance);
  64817. }
  64818. else {
  64819. return 0;
  64820. }
  64821. };
  64822. if (options) {
  64823. this.autoplay = options.autoplay || false;
  64824. this.loop = options.loop || false;
  64825. // if volume === 0, we need another way to check this option
  64826. if (options.volume !== undefined) {
  64827. this._volume = options.volume;
  64828. }
  64829. this.spatialSound = options.spatialSound || false;
  64830. this.maxDistance = options.maxDistance || 100;
  64831. this.useCustomAttenuation = options.useCustomAttenuation || false;
  64832. this.rolloffFactor = options.rolloffFactor || 1;
  64833. this.refDistance = options.refDistance || 1;
  64834. this.distanceModel = options.distanceModel || "linear";
  64835. this._playbackRate = options.playbackRate || 1;
  64836. this._streaming = options.streaming || false;
  64837. }
  64838. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64839. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  64840. this._soundGain.gain.value = this._volume;
  64841. this._inputAudioNode = this._soundGain;
  64842. this._outputAudioNode = this._soundGain;
  64843. if (this.spatialSound) {
  64844. this._createSpatialParameters();
  64845. }
  64846. this._scene.mainSoundTrack.AddSound(this);
  64847. var validParameter = true;
  64848. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  64849. if (urlOrArrayBuffer) {
  64850. try {
  64851. if (typeof (urlOrArrayBuffer) === "string") {
  64852. this._urlType = "String";
  64853. }
  64854. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  64855. this._urlType = "ArrayBuffer";
  64856. }
  64857. else if (urlOrArrayBuffer instanceof MediaStream) {
  64858. this._urlType = "MediaStream";
  64859. }
  64860. else if (Array.isArray(urlOrArrayBuffer)) {
  64861. this._urlType = "Array";
  64862. }
  64863. var urls = [];
  64864. var codecSupportedFound = false;
  64865. switch (this._urlType) {
  64866. case "MediaStream":
  64867. this._streaming = true;
  64868. this._isReadyToPlay = true;
  64869. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  64870. if (this.autoplay) {
  64871. this.play();
  64872. }
  64873. if (this._readyToPlayCallback) {
  64874. this._readyToPlayCallback();
  64875. }
  64876. break;
  64877. case "ArrayBuffer":
  64878. if (urlOrArrayBuffer.byteLength > 0) {
  64879. codecSupportedFound = true;
  64880. this._soundLoaded(urlOrArrayBuffer);
  64881. }
  64882. break;
  64883. case "String":
  64884. urls.push(urlOrArrayBuffer);
  64885. case "Array":
  64886. if (urls.length === 0)
  64887. urls = urlOrArrayBuffer;
  64888. // If we found a supported format, we load it immediately and stop the loop
  64889. for (var i = 0; i < urls.length; i++) {
  64890. var url = urls[i];
  64891. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  64892. codecSupportedFound = true;
  64893. }
  64894. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  64895. codecSupportedFound = true;
  64896. }
  64897. if (url.indexOf(".wav", url.length - 4) !== -1) {
  64898. codecSupportedFound = true;
  64899. }
  64900. if (url.indexOf("blob:") !== -1) {
  64901. codecSupportedFound = true;
  64902. }
  64903. if (codecSupportedFound) {
  64904. // Loading sound using XHR2
  64905. if (!this._streaming) {
  64906. this._scene._loadFile(url, function (data) {
  64907. _this._soundLoaded(data);
  64908. }, undefined, true, true, function (exception) {
  64909. if (exception) {
  64910. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  64911. }
  64912. BABYLON.Tools.Error("Sound creation aborted.");
  64913. _this._scene.mainSoundTrack.RemoveSound(_this);
  64914. });
  64915. }
  64916. // Streaming sound using HTML5 Audio tag
  64917. else {
  64918. this._htmlAudioElement = new Audio(url);
  64919. this._htmlAudioElement.controls = false;
  64920. this._htmlAudioElement.loop = this.loop;
  64921. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  64922. this._htmlAudioElement.preload = "auto";
  64923. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  64924. _this._isReadyToPlay = true;
  64925. if (_this.autoplay) {
  64926. _this.play();
  64927. }
  64928. if (_this._readyToPlayCallback) {
  64929. _this._readyToPlayCallback();
  64930. }
  64931. });
  64932. document.body.appendChild(this._htmlAudioElement);
  64933. }
  64934. break;
  64935. }
  64936. }
  64937. break;
  64938. default:
  64939. validParameter = false;
  64940. break;
  64941. }
  64942. if (!validParameter) {
  64943. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  64944. }
  64945. else {
  64946. if (!codecSupportedFound) {
  64947. this._isReadyToPlay = true;
  64948. // Simulating a ready to play event to avoid breaking code path
  64949. if (this._readyToPlayCallback) {
  64950. window.setTimeout(function () {
  64951. if (_this._readyToPlayCallback) {
  64952. _this._readyToPlayCallback();
  64953. }
  64954. }, 1000);
  64955. }
  64956. }
  64957. }
  64958. }
  64959. catch (ex) {
  64960. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  64961. this._scene.mainSoundTrack.RemoveSound(this);
  64962. }
  64963. }
  64964. }
  64965. else {
  64966. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  64967. this._scene.mainSoundTrack.AddSound(this);
  64968. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  64969. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  64970. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  64971. }
  64972. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  64973. if (this._readyToPlayCallback) {
  64974. window.setTimeout(function () {
  64975. if (_this._readyToPlayCallback) {
  64976. _this._readyToPlayCallback();
  64977. }
  64978. }, 1000);
  64979. }
  64980. }
  64981. }
  64982. Sound.prototype.dispose = function () {
  64983. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64984. if (this.isPlaying) {
  64985. this.stop();
  64986. }
  64987. this._isReadyToPlay = false;
  64988. if (this.soundTrackId === -1) {
  64989. this._scene.mainSoundTrack.RemoveSound(this);
  64990. }
  64991. else {
  64992. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  64993. }
  64994. if (this._soundGain) {
  64995. this._soundGain.disconnect();
  64996. this._soundGain = null;
  64997. }
  64998. if (this._soundPanner) {
  64999. this._soundPanner.disconnect();
  65000. this._soundPanner = null;
  65001. }
  65002. if (this._soundSource) {
  65003. this._soundSource.disconnect();
  65004. this._soundSource = null;
  65005. }
  65006. this._audioBuffer = null;
  65007. if (this._htmlAudioElement) {
  65008. this._htmlAudioElement.pause();
  65009. this._htmlAudioElement.src = "";
  65010. document.body.removeChild(this._htmlAudioElement);
  65011. }
  65012. if (this._streamingSource) {
  65013. this._streamingSource.disconnect();
  65014. }
  65015. if (this._connectedMesh && this._registerFunc) {
  65016. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65017. this._connectedMesh = null;
  65018. }
  65019. }
  65020. };
  65021. Sound.prototype.isReady = function () {
  65022. return this._isReadyToPlay;
  65023. };
  65024. Sound.prototype._soundLoaded = function (audioData) {
  65025. var _this = this;
  65026. if (!BABYLON.Engine.audioEngine.audioContext) {
  65027. return;
  65028. }
  65029. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  65030. _this._audioBuffer = buffer;
  65031. _this._isReadyToPlay = true;
  65032. if (_this.autoplay) {
  65033. _this.play();
  65034. }
  65035. if (_this._readyToPlayCallback) {
  65036. _this._readyToPlayCallback();
  65037. }
  65038. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  65039. };
  65040. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  65041. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65042. this._audioBuffer = audioBuffer;
  65043. this._isReadyToPlay = true;
  65044. }
  65045. };
  65046. Sound.prototype.updateOptions = function (options) {
  65047. if (options) {
  65048. this.loop = options.loop || this.loop;
  65049. this.maxDistance = options.maxDistance || this.maxDistance;
  65050. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  65051. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  65052. this.refDistance = options.refDistance || this.refDistance;
  65053. this.distanceModel = options.distanceModel || this.distanceModel;
  65054. this._playbackRate = options.playbackRate || this._playbackRate;
  65055. this._updateSpatialParameters();
  65056. if (this.isPlaying) {
  65057. if (this._streaming && this._htmlAudioElement) {
  65058. this._htmlAudioElement.playbackRate = this._playbackRate;
  65059. }
  65060. else {
  65061. if (this._soundSource) {
  65062. this._soundSource.playbackRate.value = this._playbackRate;
  65063. }
  65064. }
  65065. }
  65066. }
  65067. };
  65068. Sound.prototype._createSpatialParameters = function () {
  65069. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65070. if (this._scene.headphone) {
  65071. this._panningModel = "HRTF";
  65072. }
  65073. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  65074. this._updateSpatialParameters();
  65075. this._soundPanner.connect(this._outputAudioNode);
  65076. this._inputAudioNode = this._soundPanner;
  65077. }
  65078. };
  65079. Sound.prototype._updateSpatialParameters = function () {
  65080. if (this.spatialSound && this._soundPanner) {
  65081. if (this.useCustomAttenuation) {
  65082. // Tricks to disable in a way embedded Web Audio attenuation
  65083. this._soundPanner.distanceModel = "linear";
  65084. this._soundPanner.maxDistance = Number.MAX_VALUE;
  65085. this._soundPanner.refDistance = 1;
  65086. this._soundPanner.rolloffFactor = 1;
  65087. this._soundPanner.panningModel = this._panningModel;
  65088. }
  65089. else {
  65090. this._soundPanner.distanceModel = this.distanceModel;
  65091. this._soundPanner.maxDistance = this.maxDistance;
  65092. this._soundPanner.refDistance = this.refDistance;
  65093. this._soundPanner.rolloffFactor = this.rolloffFactor;
  65094. this._soundPanner.panningModel = this._panningModel;
  65095. }
  65096. }
  65097. };
  65098. Sound.prototype.switchPanningModelToHRTF = function () {
  65099. this._panningModel = "HRTF";
  65100. this._switchPanningModel();
  65101. };
  65102. Sound.prototype.switchPanningModelToEqualPower = function () {
  65103. this._panningModel = "equalpower";
  65104. this._switchPanningModel();
  65105. };
  65106. Sound.prototype._switchPanningModel = function () {
  65107. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65108. this._soundPanner.panningModel = this._panningModel;
  65109. }
  65110. };
  65111. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  65112. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65113. if (this._isOutputConnected) {
  65114. this._outputAudioNode.disconnect();
  65115. }
  65116. this._outputAudioNode.connect(soundTrackAudioNode);
  65117. this._isOutputConnected = true;
  65118. }
  65119. };
  65120. /**
  65121. * Transform this sound into a directional source
  65122. * @param coneInnerAngle Size of the inner cone in degree
  65123. * @param coneOuterAngle Size of the outer cone in degree
  65124. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  65125. */
  65126. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  65127. if (coneOuterAngle < coneInnerAngle) {
  65128. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  65129. return;
  65130. }
  65131. this._coneInnerAngle = coneInnerAngle;
  65132. this._coneOuterAngle = coneOuterAngle;
  65133. this._coneOuterGain = coneOuterGain;
  65134. this._isDirectional = true;
  65135. if (this.isPlaying && this.loop) {
  65136. this.stop();
  65137. this.play();
  65138. }
  65139. };
  65140. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  65141. /**
  65142. * Gets or sets the inner angle for the directional cone.
  65143. */
  65144. get: function () {
  65145. return this._coneInnerAngle;
  65146. },
  65147. /**
  65148. * Gets or sets the inner angle for the directional cone.
  65149. */
  65150. set: function (value) {
  65151. if (value != this._coneInnerAngle) {
  65152. if (this._coneOuterAngle < value) {
  65153. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65154. return;
  65155. }
  65156. this._coneInnerAngle = value;
  65157. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65158. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65159. }
  65160. }
  65161. },
  65162. enumerable: true,
  65163. configurable: true
  65164. });
  65165. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  65166. /**
  65167. * Gets or sets the outer angle for the directional cone.
  65168. */
  65169. get: function () {
  65170. return this._coneOuterAngle;
  65171. },
  65172. /**
  65173. * Gets or sets the outer angle for the directional cone.
  65174. */
  65175. set: function (value) {
  65176. if (value != this._coneOuterAngle) {
  65177. if (value < this._coneInnerAngle) {
  65178. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65179. return;
  65180. }
  65181. this._coneOuterAngle = value;
  65182. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65183. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65184. }
  65185. }
  65186. },
  65187. enumerable: true,
  65188. configurable: true
  65189. });
  65190. Sound.prototype.setPosition = function (newPosition) {
  65191. this._position = newPosition;
  65192. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65193. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65194. }
  65195. };
  65196. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  65197. this._localDirection = newLocalDirection;
  65198. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  65199. this._updateDirection();
  65200. }
  65201. };
  65202. Sound.prototype._updateDirection = function () {
  65203. if (!this._connectedMesh || !this._soundPanner) {
  65204. return;
  65205. }
  65206. var mat = this._connectedMesh.getWorldMatrix();
  65207. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  65208. direction.normalize();
  65209. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  65210. };
  65211. Sound.prototype.updateDistanceFromListener = function () {
  65212. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  65213. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  65214. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  65215. }
  65216. };
  65217. Sound.prototype.setAttenuationFunction = function (callback) {
  65218. this._customAttenuationFunction = callback;
  65219. };
  65220. /**
  65221. * Play the sound
  65222. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  65223. * @param offset (optional) Start the sound setting it at a specific time
  65224. */
  65225. Sound.prototype.play = function (time, offset) {
  65226. var _this = this;
  65227. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  65228. try {
  65229. if (this._startOffset < 0) {
  65230. time = -this._startOffset;
  65231. this._startOffset = 0;
  65232. }
  65233. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65234. if (!this._soundSource || !this._streamingSource) {
  65235. if (this.spatialSound && this._soundPanner) {
  65236. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65237. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65238. }
  65239. if (this._isDirectional) {
  65240. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65241. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65242. this._soundPanner.coneOuterGain = this._coneOuterGain;
  65243. if (this._connectedMesh) {
  65244. this._updateDirection();
  65245. }
  65246. else {
  65247. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  65248. }
  65249. }
  65250. }
  65251. }
  65252. if (this._streaming) {
  65253. if (!this._streamingSource) {
  65254. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  65255. this._htmlAudioElement.onended = function () { _this._onended(); };
  65256. this._htmlAudioElement.playbackRate = this._playbackRate;
  65257. }
  65258. this._streamingSource.disconnect();
  65259. this._streamingSource.connect(this._inputAudioNode);
  65260. if (this._htmlAudioElement) {
  65261. this._htmlAudioElement.play();
  65262. }
  65263. }
  65264. else {
  65265. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  65266. this._soundSource.buffer = this._audioBuffer;
  65267. this._soundSource.connect(this._inputAudioNode);
  65268. this._soundSource.loop = this.loop;
  65269. this._soundSource.playbackRate.value = this._playbackRate;
  65270. this._soundSource.onended = function () { _this._onended(); };
  65271. if (this._soundSource.buffer) {
  65272. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  65273. }
  65274. }
  65275. this._startTime = startTime;
  65276. this.isPlaying = true;
  65277. this.isPaused = false;
  65278. }
  65279. catch (ex) {
  65280. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  65281. }
  65282. }
  65283. };
  65284. Sound.prototype._onended = function () {
  65285. this.isPlaying = false;
  65286. if (this.onended) {
  65287. this.onended();
  65288. }
  65289. this.onEndedObservable.notifyObservers(this);
  65290. };
  65291. /**
  65292. * Stop the sound
  65293. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  65294. */
  65295. Sound.prototype.stop = function (time) {
  65296. if (this.isPlaying) {
  65297. if (this._streaming) {
  65298. if (this._htmlAudioElement) {
  65299. this._htmlAudioElement.pause();
  65300. // Test needed for Firefox or it will generate an Invalid State Error
  65301. if (this._htmlAudioElement.currentTime > 0) {
  65302. this._htmlAudioElement.currentTime = 0;
  65303. }
  65304. }
  65305. else {
  65306. this._streamingSource.disconnect();
  65307. }
  65308. }
  65309. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  65310. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65311. this._soundSource.stop(stopTime);
  65312. this._soundSource.onended = function () { };
  65313. if (!this.isPaused) {
  65314. this._startOffset = 0;
  65315. }
  65316. }
  65317. this.isPlaying = false;
  65318. }
  65319. };
  65320. Sound.prototype.pause = function () {
  65321. if (this.isPlaying) {
  65322. this.isPaused = true;
  65323. if (this._streaming) {
  65324. if (this._htmlAudioElement) {
  65325. this._htmlAudioElement.pause();
  65326. }
  65327. else {
  65328. this._streamingSource.disconnect();
  65329. }
  65330. }
  65331. else if (BABYLON.Engine.audioEngine.audioContext) {
  65332. this.stop(0);
  65333. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  65334. }
  65335. }
  65336. };
  65337. Sound.prototype.setVolume = function (newVolume, time) {
  65338. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  65339. if (time && BABYLON.Engine.audioEngine.audioContext) {
  65340. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  65341. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  65342. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  65343. }
  65344. else {
  65345. this._soundGain.gain.value = newVolume;
  65346. }
  65347. }
  65348. this._volume = newVolume;
  65349. };
  65350. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  65351. this._playbackRate = newPlaybackRate;
  65352. if (this.isPlaying) {
  65353. if (this._streaming && this._htmlAudioElement) {
  65354. this._htmlAudioElement.playbackRate = this._playbackRate;
  65355. }
  65356. else if (this._soundSource) {
  65357. this._soundSource.playbackRate.value = this._playbackRate;
  65358. }
  65359. }
  65360. };
  65361. Sound.prototype.getVolume = function () {
  65362. return this._volume;
  65363. };
  65364. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  65365. var _this = this;
  65366. if (this._connectedMesh && this._registerFunc) {
  65367. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65368. this._registerFunc = null;
  65369. }
  65370. this._connectedMesh = meshToConnectTo;
  65371. if (!this.spatialSound) {
  65372. this.spatialSound = true;
  65373. this._createSpatialParameters();
  65374. if (this.isPlaying && this.loop) {
  65375. this.stop();
  65376. this.play();
  65377. }
  65378. }
  65379. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  65380. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  65381. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  65382. };
  65383. Sound.prototype.detachFromMesh = function () {
  65384. if (this._connectedMesh && this._registerFunc) {
  65385. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65386. this._registerFunc = null;
  65387. this._connectedMesh = null;
  65388. }
  65389. };
  65390. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  65391. if (!node.getBoundingInfo) {
  65392. return;
  65393. }
  65394. var mesh = node;
  65395. if (this._positionInEmitterSpace) {
  65396. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  65397. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  65398. }
  65399. else {
  65400. var boundingInfo = mesh.getBoundingInfo();
  65401. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  65402. }
  65403. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  65404. this._updateDirection();
  65405. }
  65406. };
  65407. Sound.prototype.clone = function () {
  65408. var _this = this;
  65409. if (!this._streaming) {
  65410. var setBufferAndRun = function () {
  65411. if (_this._isReadyToPlay) {
  65412. clonedSound._audioBuffer = _this.getAudioBuffer();
  65413. clonedSound._isReadyToPlay = true;
  65414. if (clonedSound.autoplay) {
  65415. clonedSound.play();
  65416. }
  65417. }
  65418. else {
  65419. window.setTimeout(setBufferAndRun, 300);
  65420. }
  65421. };
  65422. var currentOptions = {
  65423. autoplay: this.autoplay, loop: this.loop,
  65424. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  65425. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  65426. refDistance: this.refDistance, distanceModel: this.distanceModel
  65427. };
  65428. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  65429. if (this.useCustomAttenuation) {
  65430. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  65431. }
  65432. clonedSound.setPosition(this._position);
  65433. clonedSound.setPlaybackRate(this._playbackRate);
  65434. setBufferAndRun();
  65435. return clonedSound;
  65436. }
  65437. // Can't clone a streaming sound
  65438. else {
  65439. return null;
  65440. }
  65441. };
  65442. Sound.prototype.getAudioBuffer = function () {
  65443. return this._audioBuffer;
  65444. };
  65445. Sound.prototype.serialize = function () {
  65446. var serializationObject = {
  65447. name: this.name,
  65448. url: this.name,
  65449. autoplay: this.autoplay,
  65450. loop: this.loop,
  65451. volume: this._volume,
  65452. spatialSound: this.spatialSound,
  65453. maxDistance: this.maxDistance,
  65454. rolloffFactor: this.rolloffFactor,
  65455. refDistance: this.refDistance,
  65456. distanceModel: this.distanceModel,
  65457. playbackRate: this._playbackRate,
  65458. panningModel: this._panningModel,
  65459. soundTrackId: this.soundTrackId
  65460. };
  65461. if (this.spatialSound) {
  65462. if (this._connectedMesh)
  65463. serializationObject.connectedMeshId = this._connectedMesh.id;
  65464. serializationObject.position = this._position.asArray();
  65465. serializationObject.refDistance = this.refDistance;
  65466. serializationObject.distanceModel = this.distanceModel;
  65467. serializationObject.isDirectional = this._isDirectional;
  65468. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  65469. serializationObject.coneInnerAngle = this._coneInnerAngle;
  65470. serializationObject.coneOuterAngle = this._coneOuterAngle;
  65471. serializationObject.coneOuterGain = this._coneOuterGain;
  65472. }
  65473. return serializationObject;
  65474. };
  65475. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  65476. var soundName = parsedSound.name;
  65477. var soundUrl;
  65478. if (parsedSound.url) {
  65479. soundUrl = rootUrl + parsedSound.url;
  65480. }
  65481. else {
  65482. soundUrl = rootUrl + soundName;
  65483. }
  65484. var options = {
  65485. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  65486. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  65487. rolloffFactor: parsedSound.rolloffFactor,
  65488. refDistance: parsedSound.refDistance,
  65489. distanceModel: parsedSound.distanceModel,
  65490. playbackRate: parsedSound.playbackRate
  65491. };
  65492. var newSound;
  65493. if (!sourceSound) {
  65494. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  65495. scene._addPendingData(newSound);
  65496. }
  65497. else {
  65498. var setBufferAndRun = function () {
  65499. if (sourceSound._isReadyToPlay) {
  65500. newSound._audioBuffer = sourceSound.getAudioBuffer();
  65501. newSound._isReadyToPlay = true;
  65502. if (newSound.autoplay) {
  65503. newSound.play();
  65504. }
  65505. }
  65506. else {
  65507. window.setTimeout(setBufferAndRun, 300);
  65508. }
  65509. };
  65510. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  65511. setBufferAndRun();
  65512. }
  65513. if (parsedSound.position) {
  65514. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  65515. newSound.setPosition(soundPosition);
  65516. }
  65517. if (parsedSound.isDirectional) {
  65518. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  65519. if (parsedSound.localDirectionToMesh) {
  65520. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  65521. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  65522. }
  65523. }
  65524. if (parsedSound.connectedMeshId) {
  65525. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  65526. if (connectedMesh) {
  65527. newSound.attachToMesh(connectedMesh);
  65528. }
  65529. }
  65530. return newSound;
  65531. };
  65532. return Sound;
  65533. }());
  65534. BABYLON.Sound = Sound;
  65535. })(BABYLON || (BABYLON = {}));
  65536. //# sourceMappingURL=babylon.sound.js.map
  65537. var BABYLON;
  65538. (function (BABYLON) {
  65539. var SoundTrack = /** @class */ (function () {
  65540. function SoundTrack(scene, options) {
  65541. this.id = -1;
  65542. this._isMainTrack = false;
  65543. this._isInitialized = false;
  65544. this._scene = scene;
  65545. this.soundCollection = new Array();
  65546. this._options = options;
  65547. if (!this._isMainTrack) {
  65548. this._scene.soundTracks.push(this);
  65549. this.id = this._scene.soundTracks.length - 1;
  65550. }
  65551. }
  65552. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  65553. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65554. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  65555. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  65556. if (this._options) {
  65557. if (this._options.volume) {
  65558. this._outputAudioNode.gain.value = this._options.volume;
  65559. }
  65560. if (this._options.mainTrack) {
  65561. this._isMainTrack = this._options.mainTrack;
  65562. }
  65563. }
  65564. this._isInitialized = true;
  65565. }
  65566. };
  65567. SoundTrack.prototype.dispose = function () {
  65568. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  65569. if (this._connectedAnalyser) {
  65570. this._connectedAnalyser.stopDebugCanvas();
  65571. }
  65572. while (this.soundCollection.length) {
  65573. this.soundCollection[0].dispose();
  65574. }
  65575. if (this._outputAudioNode) {
  65576. this._outputAudioNode.disconnect();
  65577. }
  65578. this._outputAudioNode = null;
  65579. }
  65580. };
  65581. SoundTrack.prototype.AddSound = function (sound) {
  65582. if (!this._isInitialized) {
  65583. this._initializeSoundTrackAudioGraph();
  65584. }
  65585. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65586. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  65587. }
  65588. if (sound.soundTrackId) {
  65589. if (sound.soundTrackId === -1) {
  65590. this._scene.mainSoundTrack.RemoveSound(sound);
  65591. }
  65592. else {
  65593. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  65594. }
  65595. }
  65596. this.soundCollection.push(sound);
  65597. sound.soundTrackId = this.id;
  65598. };
  65599. SoundTrack.prototype.RemoveSound = function (sound) {
  65600. var index = this.soundCollection.indexOf(sound);
  65601. if (index !== -1) {
  65602. this.soundCollection.splice(index, 1);
  65603. }
  65604. };
  65605. SoundTrack.prototype.setVolume = function (newVolume) {
  65606. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65607. this._outputAudioNode.gain.value = newVolume;
  65608. }
  65609. };
  65610. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  65611. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65612. for (var i = 0; i < this.soundCollection.length; i++) {
  65613. this.soundCollection[i].switchPanningModelToHRTF();
  65614. }
  65615. }
  65616. };
  65617. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  65618. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65619. for (var i = 0; i < this.soundCollection.length; i++) {
  65620. this.soundCollection[i].switchPanningModelToEqualPower();
  65621. }
  65622. }
  65623. };
  65624. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  65625. if (this._connectedAnalyser) {
  65626. this._connectedAnalyser.stopDebugCanvas();
  65627. }
  65628. this._connectedAnalyser = analyser;
  65629. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65630. this._outputAudioNode.disconnect();
  65631. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  65632. }
  65633. };
  65634. return SoundTrack;
  65635. }());
  65636. BABYLON.SoundTrack = SoundTrack;
  65637. })(BABYLON || (BABYLON = {}));
  65638. //# sourceMappingURL=babylon.soundtrack.js.map
  65639. var BABYLON;
  65640. (function (BABYLON) {
  65641. /**
  65642. * Class used to work with sound analyzer using fast fourier transform (FFT)
  65643. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  65644. */
  65645. var Analyser = /** @class */ (function () {
  65646. /**
  65647. * Creates a new analyser
  65648. * @param scene defines hosting scene
  65649. */
  65650. function Analyser(scene) {
  65651. /**
  65652. * Gets or sets the smoothing
  65653. * @ignorenaming
  65654. */
  65655. this.SMOOTHING = 0.75;
  65656. /**
  65657. * Gets or sets the FFT table size
  65658. * @ignorenaming
  65659. */
  65660. this.FFT_SIZE = 512;
  65661. /**
  65662. * Gets or sets the bar graph amplitude
  65663. * @ignorenaming
  65664. */
  65665. this.BARGRAPHAMPLITUDE = 256;
  65666. /**
  65667. * Gets or sets the position of the debug canvas
  65668. * @ignorenaming
  65669. */
  65670. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  65671. /**
  65672. * Gets or sets the debug canvas size
  65673. * @ignorenaming
  65674. */
  65675. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  65676. this._scene = scene;
  65677. this._audioEngine = BABYLON.Engine.audioEngine;
  65678. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  65679. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  65680. this._webAudioAnalyser.minDecibels = -140;
  65681. this._webAudioAnalyser.maxDecibels = 0;
  65682. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65683. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65684. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  65685. }
  65686. }
  65687. /**
  65688. * Get the number of data values you will have to play with for the visualization
  65689. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  65690. * @returns a number
  65691. */
  65692. Analyser.prototype.getFrequencyBinCount = function () {
  65693. if (this._audioEngine.canUseWebAudio) {
  65694. return this._webAudioAnalyser.frequencyBinCount;
  65695. }
  65696. else {
  65697. return 0;
  65698. }
  65699. };
  65700. /**
  65701. * Gets the current frequency data as a byte array
  65702. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65703. * @returns a Uint8Array
  65704. */
  65705. Analyser.prototype.getByteFrequencyData = function () {
  65706. if (this._audioEngine.canUseWebAudio) {
  65707. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65708. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65709. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  65710. }
  65711. return this._byteFreqs;
  65712. };
  65713. /**
  65714. * Gets the current waveform as a byte array
  65715. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  65716. * @returns a Uint8Array
  65717. */
  65718. Analyser.prototype.getByteTimeDomainData = function () {
  65719. if (this._audioEngine.canUseWebAudio) {
  65720. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65721. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65722. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  65723. }
  65724. return this._byteTime;
  65725. };
  65726. /**
  65727. * Gets the current frequency data as a float array
  65728. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65729. * @returns a Float32Array
  65730. */
  65731. Analyser.prototype.getFloatFrequencyData = function () {
  65732. if (this._audioEngine.canUseWebAudio) {
  65733. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65734. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65735. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  65736. }
  65737. return this._floatFreqs;
  65738. };
  65739. /**
  65740. * Renders the debug canvas
  65741. */
  65742. Analyser.prototype.drawDebugCanvas = function () {
  65743. var _this = this;
  65744. if (this._audioEngine.canUseWebAudio) {
  65745. if (!this._debugCanvas) {
  65746. this._debugCanvas = document.createElement("canvas");
  65747. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  65748. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  65749. this._debugCanvas.style.position = "absolute";
  65750. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  65751. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  65752. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  65753. document.body.appendChild(this._debugCanvas);
  65754. this._registerFunc = function () {
  65755. _this.drawDebugCanvas();
  65756. };
  65757. this._scene.registerBeforeRender(this._registerFunc);
  65758. }
  65759. if (this._registerFunc && this._debugCanvasContext) {
  65760. var workingArray = this.getByteFrequencyData();
  65761. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  65762. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  65763. // Draw the frequency domain chart.
  65764. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  65765. var value = workingArray[i];
  65766. var percent = value / this.BARGRAPHAMPLITUDE;
  65767. var height = this.DEBUGCANVASSIZE.height * percent;
  65768. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  65769. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  65770. var hue = i / this.getFrequencyBinCount() * 360;
  65771. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  65772. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  65773. }
  65774. }
  65775. }
  65776. };
  65777. /**
  65778. * Stops rendering the debug canvas and removes it
  65779. */
  65780. Analyser.prototype.stopDebugCanvas = function () {
  65781. if (this._debugCanvas) {
  65782. if (this._registerFunc) {
  65783. this._scene.unregisterBeforeRender(this._registerFunc);
  65784. this._registerFunc = null;
  65785. }
  65786. document.body.removeChild(this._debugCanvas);
  65787. this._debugCanvas = null;
  65788. this._debugCanvasContext = null;
  65789. }
  65790. };
  65791. /**
  65792. * Connects two audio nodes
  65793. * @param inputAudioNode defines first node to connect
  65794. * @param outputAudioNode defines second node to connect
  65795. */
  65796. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  65797. if (this._audioEngine.canUseWebAudio) {
  65798. inputAudioNode.connect(this._webAudioAnalyser);
  65799. this._webAudioAnalyser.connect(outputAudioNode);
  65800. }
  65801. };
  65802. /**
  65803. * Releases all associated resources
  65804. */
  65805. Analyser.prototype.dispose = function () {
  65806. if (this._audioEngine.canUseWebAudio) {
  65807. this._webAudioAnalyser.disconnect();
  65808. }
  65809. };
  65810. return Analyser;
  65811. }());
  65812. BABYLON.Analyser = Analyser;
  65813. })(BABYLON || (BABYLON = {}));
  65814. //# sourceMappingURL=babylon.analyser.js.map
  65815. var BABYLON;
  65816. (function (BABYLON) {
  65817. /**
  65818. * Wraps one or more Sound objects and selects one with random weight for playback.
  65819. */
  65820. var WeightedSound = /** @class */ (function () {
  65821. /**
  65822. * Creates a new WeightedSound from the list of sounds given.
  65823. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  65824. * @param sounds Array of Sounds that will be selected from.
  65825. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  65826. */
  65827. function WeightedSound(loop, sounds, weights) {
  65828. var _this = this;
  65829. /** When true a Sound will be selected and played when the current playing Sound completes. */
  65830. this.loop = false;
  65831. this._coneInnerAngle = 360;
  65832. this._coneOuterAngle = 360;
  65833. this._volume = 1;
  65834. /** A Sound is currently playing. */
  65835. this.isPlaying = false;
  65836. /** A Sound is currently paused. */
  65837. this.isPaused = false;
  65838. this._sounds = [];
  65839. this._weights = [];
  65840. if (sounds.length !== weights.length) {
  65841. throw new Error('Sounds length does not equal weights length');
  65842. }
  65843. this.loop = loop;
  65844. this._weights = weights;
  65845. // Normalize the weights
  65846. var weightSum = 0;
  65847. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  65848. var weight = weights_1[_i];
  65849. weightSum += weight;
  65850. }
  65851. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  65852. for (var i = 0; i < this._weights.length; i++) {
  65853. this._weights[i] *= invWeightSum;
  65854. }
  65855. this._sounds = sounds;
  65856. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  65857. var sound = _b[_a];
  65858. sound.onEndedObservable.add(function () { _this._onended(); });
  65859. }
  65860. }
  65861. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  65862. /**
  65863. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  65864. */
  65865. get: function () {
  65866. return this._coneInnerAngle;
  65867. },
  65868. /**
  65869. * The size of cone in degress for a directional sound in which there will be no attenuation.
  65870. */
  65871. set: function (value) {
  65872. if (value !== this._coneInnerAngle) {
  65873. if (this._coneOuterAngle < value) {
  65874. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65875. return;
  65876. }
  65877. this._coneInnerAngle = value;
  65878. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65879. var sound = _a[_i];
  65880. sound.directionalConeInnerAngle = value;
  65881. }
  65882. }
  65883. },
  65884. enumerable: true,
  65885. configurable: true
  65886. });
  65887. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  65888. /**
  65889. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65890. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65891. */
  65892. get: function () {
  65893. return this._coneOuterAngle;
  65894. },
  65895. /**
  65896. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65897. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65898. */
  65899. set: function (value) {
  65900. if (value !== this._coneOuterAngle) {
  65901. if (value < this._coneInnerAngle) {
  65902. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65903. return;
  65904. }
  65905. this._coneOuterAngle = value;
  65906. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65907. var sound = _a[_i];
  65908. sound.directionalConeOuterAngle = value;
  65909. }
  65910. }
  65911. },
  65912. enumerable: true,
  65913. configurable: true
  65914. });
  65915. Object.defineProperty(WeightedSound.prototype, "volume", {
  65916. /**
  65917. * Playback volume.
  65918. */
  65919. get: function () {
  65920. return this._volume;
  65921. },
  65922. /**
  65923. * Playback volume.
  65924. */
  65925. set: function (value) {
  65926. if (value !== this._volume) {
  65927. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65928. var sound = _a[_i];
  65929. sound.setVolume(value);
  65930. }
  65931. }
  65932. },
  65933. enumerable: true,
  65934. configurable: true
  65935. });
  65936. WeightedSound.prototype._onended = function () {
  65937. if (this._currentIndex !== undefined) {
  65938. this._sounds[this._currentIndex].autoplay = false;
  65939. }
  65940. if (this.loop && this.isPlaying) {
  65941. this.play();
  65942. }
  65943. else {
  65944. this.isPlaying = false;
  65945. }
  65946. };
  65947. /**
  65948. * Suspend playback
  65949. */
  65950. WeightedSound.prototype.pause = function () {
  65951. this.isPaused = true;
  65952. if (this._currentIndex !== undefined) {
  65953. this._sounds[this._currentIndex].pause();
  65954. }
  65955. };
  65956. /**
  65957. * Stop playback
  65958. */
  65959. WeightedSound.prototype.stop = function () {
  65960. this.isPlaying = false;
  65961. if (this._currentIndex !== undefined) {
  65962. this._sounds[this._currentIndex].stop();
  65963. }
  65964. };
  65965. /**
  65966. * Start playback.
  65967. * @param startOffset Position the clip head at a specific time in seconds.
  65968. */
  65969. WeightedSound.prototype.play = function (startOffset) {
  65970. if (!this.isPaused) {
  65971. this.stop();
  65972. var randomValue = Math.random();
  65973. var total = 0;
  65974. for (var i = 0; i < this._weights.length; i++) {
  65975. total += this._weights[i];
  65976. if (randomValue <= total) {
  65977. this._currentIndex = i;
  65978. break;
  65979. }
  65980. }
  65981. }
  65982. var sound = this._sounds[this._currentIndex];
  65983. if (sound.isReady()) {
  65984. sound.play(0, this.isPaused ? undefined : startOffset);
  65985. }
  65986. else {
  65987. sound.autoplay = true;
  65988. }
  65989. this.isPlaying = true;
  65990. this.isPaused = false;
  65991. };
  65992. return WeightedSound;
  65993. }());
  65994. BABYLON.WeightedSound = WeightedSound;
  65995. })(BABYLON || (BABYLON = {}));
  65996. //# sourceMappingURL=babylon.weightedsound.js.map
  65997. var BABYLON;
  65998. (function (BABYLON) {
  65999. var CubeTexture = /** @class */ (function (_super) {
  66000. __extends(CubeTexture, _super);
  66001. /**
  66002. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  66003. * as prefiltered data.
  66004. * @param rootUrl defines the url of the texture or the root name of the six images
  66005. * @param scene defines the scene the texture is attached to
  66006. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  66007. * @param noMipmap defines if mipmaps should be created or not
  66008. * @param files defines the six files to load for the different faces
  66009. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  66010. * @param onError defines a callback triggered in case of error during load
  66011. * @param format defines the internal format to use for the texture once loaded
  66012. * @param prefiltered defines whether or not the texture is created from prefiltered data
  66013. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  66014. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66015. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66016. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66017. * @return the cube texture
  66018. */
  66019. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  66020. if (extensions === void 0) { extensions = null; }
  66021. if (noMipmap === void 0) { noMipmap = false; }
  66022. if (files === void 0) { files = null; }
  66023. if (onLoad === void 0) { onLoad = null; }
  66024. if (onError === void 0) { onError = null; }
  66025. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66026. if (prefiltered === void 0) { prefiltered = false; }
  66027. if (forcedExtension === void 0) { forcedExtension = null; }
  66028. if (createPolynomials === void 0) { createPolynomials = false; }
  66029. if (lodScale === void 0) { lodScale = 0.8; }
  66030. if (lodOffset === void 0) { lodOffset = 0; }
  66031. var _this = _super.call(this, scene) || this;
  66032. /**
  66033. * Gets or sets the center of the bounding box associated with the cube texture
  66034. * It must define where the camera used to render the texture was set
  66035. */
  66036. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66037. _this._rotationY = 0;
  66038. /** @hidden */
  66039. _this._prefiltered = false;
  66040. _this.name = rootUrl;
  66041. _this.url = rootUrl;
  66042. _this._noMipmap = noMipmap;
  66043. _this.hasAlpha = false;
  66044. _this._format = format;
  66045. _this.isCube = true;
  66046. _this._textureMatrix = BABYLON.Matrix.Identity();
  66047. _this._createPolynomials = createPolynomials;
  66048. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  66049. if (!rootUrl && !files) {
  66050. return _this;
  66051. }
  66052. var lastDot = rootUrl.lastIndexOf(".");
  66053. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  66054. var isDDS = (extension === ".dds");
  66055. var isEnv = (extension === ".env");
  66056. if (isEnv) {
  66057. _this.gammaSpace = false;
  66058. _this._prefiltered = false;
  66059. }
  66060. else {
  66061. _this._prefiltered = prefiltered;
  66062. if (prefiltered) {
  66063. _this.gammaSpace = false;
  66064. }
  66065. }
  66066. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  66067. if (!files) {
  66068. if (!isEnv && !isDDS && !extensions) {
  66069. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  66070. }
  66071. files = [];
  66072. if (extensions) {
  66073. for (var index = 0; index < extensions.length; index++) {
  66074. files.push(rootUrl + extensions[index]);
  66075. }
  66076. }
  66077. }
  66078. _this._files = files;
  66079. if (!_this._texture) {
  66080. if (!scene.useDelayedTextureLoading) {
  66081. if (prefiltered) {
  66082. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  66083. }
  66084. else {
  66085. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  66086. }
  66087. }
  66088. else {
  66089. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  66090. }
  66091. }
  66092. else if (onLoad) {
  66093. if (_this._texture.isReady) {
  66094. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  66095. }
  66096. else {
  66097. _this._texture.onLoadedObservable.add(onLoad);
  66098. }
  66099. }
  66100. return _this;
  66101. }
  66102. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  66103. get: function () {
  66104. return this._boundingBoxSize;
  66105. },
  66106. /**
  66107. * Gets or sets the size of the bounding box associated with the cube texture
  66108. * When defined, the cubemap will switch to local mode
  66109. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66110. * @example https://www.babylonjs-playground.com/#RNASML
  66111. */
  66112. set: function (value) {
  66113. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66114. return;
  66115. }
  66116. this._boundingBoxSize = value;
  66117. var scene = this.getScene();
  66118. if (scene) {
  66119. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66120. }
  66121. },
  66122. enumerable: true,
  66123. configurable: true
  66124. });
  66125. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  66126. /**
  66127. * Gets texture matrix rotation angle around Y axis radians.
  66128. */
  66129. get: function () {
  66130. return this._rotationY;
  66131. },
  66132. /**
  66133. * Sets texture matrix rotation angle around Y axis in radians.
  66134. */
  66135. set: function (value) {
  66136. this._rotationY = value;
  66137. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  66138. },
  66139. enumerable: true,
  66140. configurable: true
  66141. });
  66142. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  66143. var rootUrlKey = "";
  66144. files.forEach(function (url) { return rootUrlKey += url; });
  66145. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  66146. };
  66147. /**
  66148. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  66149. * @param url defines the url of the prefiltered texture
  66150. * @param scene defines the scene the texture is attached to
  66151. * @param forcedExtension defines the extension of the file if different from the url
  66152. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66153. * @return the prefiltered texture
  66154. */
  66155. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  66156. if (forcedExtension === void 0) { forcedExtension = null; }
  66157. if (createPolynomials === void 0) { createPolynomials = true; }
  66158. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  66159. };
  66160. // Methods
  66161. CubeTexture.prototype.delayLoad = function () {
  66162. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  66163. return;
  66164. }
  66165. var scene = this.getScene();
  66166. if (!scene) {
  66167. return;
  66168. }
  66169. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66170. this._texture = this._getFromCache(this.url, this._noMipmap);
  66171. if (!this._texture) {
  66172. if (this._prefiltered) {
  66173. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  66174. }
  66175. else {
  66176. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  66177. }
  66178. }
  66179. };
  66180. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  66181. return this._textureMatrix;
  66182. };
  66183. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66184. this._textureMatrix = value;
  66185. };
  66186. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66187. var texture = BABYLON.SerializationHelper.Parse(function () {
  66188. var prefiltered = false;
  66189. if (parsedTexture.prefiltered) {
  66190. prefiltered = parsedTexture.prefiltered;
  66191. }
  66192. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  66193. }, parsedTexture, scene);
  66194. // Local Cubemaps
  66195. if (parsedTexture.boundingBoxPosition) {
  66196. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  66197. }
  66198. if (parsedTexture.boundingBoxSize) {
  66199. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  66200. }
  66201. // Animations
  66202. if (parsedTexture.animations) {
  66203. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  66204. var parsedAnimation = parsedTexture.animations[animationIndex];
  66205. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  66206. }
  66207. }
  66208. return texture;
  66209. };
  66210. CubeTexture.prototype.clone = function () {
  66211. var _this = this;
  66212. return BABYLON.SerializationHelper.Clone(function () {
  66213. var scene = _this.getScene();
  66214. if (!scene) {
  66215. return _this;
  66216. }
  66217. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  66218. }, this);
  66219. };
  66220. __decorate([
  66221. BABYLON.serialize("rotationY")
  66222. ], CubeTexture.prototype, "rotationY", null);
  66223. return CubeTexture;
  66224. }(BABYLON.BaseTexture));
  66225. BABYLON.CubeTexture = CubeTexture;
  66226. })(BABYLON || (BABYLON = {}));
  66227. //# sourceMappingURL=babylon.cubeTexture.js.map
  66228. var BABYLON;
  66229. (function (BABYLON) {
  66230. /**
  66231. * Raw cube texture where the raw buffers are passed in
  66232. */
  66233. var RawCubeTexture = /** @class */ (function (_super) {
  66234. __extends(RawCubeTexture, _super);
  66235. /**
  66236. * Creates a cube texture where the raw buffers are passed in.
  66237. * @param scene defines the scene the texture is attached to
  66238. * @param data defines the array of data to use to create each face
  66239. * @param size defines the size of the textures
  66240. * @param format defines the format of the data
  66241. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  66242. * @param generateMipMaps defines if the engine should generate the mip levels
  66243. * @param invertY defines if data must be stored with Y axis inverted
  66244. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  66245. * @param compression defines the compression used (null by default)
  66246. */
  66247. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  66248. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66249. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66250. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66251. if (invertY === void 0) { invertY = false; }
  66252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66253. if (compression === void 0) { compression = null; }
  66254. var _this = _super.call(this, "", scene) || this;
  66255. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  66256. return _this;
  66257. }
  66258. /**
  66259. * Updates the raw cube texture.
  66260. * @param data defines the data to store
  66261. * @param format defines the data format
  66262. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  66263. * @param invertY defines if data must be stored with Y axis inverted
  66264. * @param compression defines the compression used (null by default)
  66265. * @param level defines which level of the texture to update
  66266. */
  66267. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  66268. if (compression === void 0) { compression = null; }
  66269. if (level === void 0) { level = 0; }
  66270. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  66271. };
  66272. /**
  66273. * Updates a raw cube texture with RGBD encoded data.
  66274. * @param data defines the array of data [mipmap][face] to use to create each face
  66275. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  66276. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66277. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66278. * @returns a promsie that resolves when the operation is complete
  66279. */
  66280. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  66281. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  66282. if (lodScale === void 0) { lodScale = 0.8; }
  66283. if (lodOffset === void 0) { lodOffset = 0; }
  66284. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  66285. };
  66286. /**
  66287. * Clones the raw cube texture.
  66288. * @return a new cube texture
  66289. */
  66290. RawCubeTexture.prototype.clone = function () {
  66291. var _this = this;
  66292. return BABYLON.SerializationHelper.Clone(function () {
  66293. var scene = _this.getScene();
  66294. var internalTexture = _this._texture;
  66295. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  66296. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  66297. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  66298. }
  66299. return texture;
  66300. }, this);
  66301. };
  66302. /** @hidden */
  66303. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  66304. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  66305. internalTexture._bufferViewArrayArray = data;
  66306. internalTexture._lodGenerationScale = lodScale;
  66307. internalTexture._lodGenerationOffset = lodOffset;
  66308. internalTexture._sphericalPolynomial = sphericalPolynomial;
  66309. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  66310. internalTexture.isReady = true;
  66311. });
  66312. };
  66313. return RawCubeTexture;
  66314. }(BABYLON.CubeTexture));
  66315. BABYLON.RawCubeTexture = RawCubeTexture;
  66316. })(BABYLON || (BABYLON = {}));
  66317. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  66318. var BABYLON;
  66319. (function (BABYLON) {
  66320. var RenderTargetTexture = /** @class */ (function (_super) {
  66321. __extends(RenderTargetTexture, _super);
  66322. /**
  66323. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  66324. * or used a shadow, depth texture...
  66325. * @param name The friendly name of the texture
  66326. * @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)
  66327. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  66328. * @param generateMipMaps True if mip maps need to be generated after render.
  66329. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  66330. * @param type The type of the buffer in the RTT (int, half float, float...)
  66331. * @param isCube True if a cube texture needs to be created
  66332. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  66333. * @param generateDepthBuffer True to generate a depth buffer
  66334. * @param generateStencilBuffer True to generate a stencil buffer
  66335. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  66336. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  66337. */
  66338. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  66339. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  66340. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66341. if (isCube === void 0) { isCube = false; }
  66342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66343. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  66344. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  66345. if (isMulti === void 0) { isMulti = false; }
  66346. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66347. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  66348. _this.isCube = isCube;
  66349. _this.renderParticles = true;
  66350. _this.renderSprites = false;
  66351. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  66352. _this.ignoreCameraViewport = false;
  66353. // Events
  66354. /**
  66355. * An event triggered when the texture is unbind.
  66356. */
  66357. _this.onBeforeBindObservable = new BABYLON.Observable();
  66358. /**
  66359. * An event triggered when the texture is unbind.
  66360. */
  66361. _this.onAfterUnbindObservable = new BABYLON.Observable();
  66362. /**
  66363. * An event triggered before rendering the texture
  66364. */
  66365. _this.onBeforeRenderObservable = new BABYLON.Observable();
  66366. /**
  66367. * An event triggered after rendering the texture
  66368. */
  66369. _this.onAfterRenderObservable = new BABYLON.Observable();
  66370. /**
  66371. * An event triggered after the texture clear
  66372. */
  66373. _this.onClearObservable = new BABYLON.Observable();
  66374. _this._currentRefreshId = -1;
  66375. _this._refreshRate = 1;
  66376. _this._samples = 1;
  66377. /**
  66378. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  66379. * It must define where the camera used to render the texture is set
  66380. */
  66381. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66382. scene = _this.getScene();
  66383. if (!scene) {
  66384. return _this;
  66385. }
  66386. _this.renderList = new Array();
  66387. _this._engine = scene.getEngine();
  66388. _this.name = name;
  66389. _this.isRenderTarget = true;
  66390. _this._initialSizeParameter = size;
  66391. _this._processSizeParameter(size);
  66392. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  66393. });
  66394. _this._generateMipMaps = generateMipMaps ? true : false;
  66395. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  66396. // Rendering groups
  66397. _this._renderingManager = new BABYLON.RenderingManager(scene);
  66398. _this._renderingManager._useSceneAutoClearSetup = true;
  66399. if (isMulti) {
  66400. return _this;
  66401. }
  66402. _this._renderTargetOptions = {
  66403. generateMipMaps: generateMipMaps,
  66404. type: type,
  66405. format: format,
  66406. samplingMode: samplingMode,
  66407. generateDepthBuffer: generateDepthBuffer,
  66408. generateStencilBuffer: generateStencilBuffer
  66409. };
  66410. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  66411. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66412. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66413. }
  66414. if (isCube) {
  66415. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  66416. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  66417. _this._textureMatrix = BABYLON.Matrix.Identity();
  66418. }
  66419. else {
  66420. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  66421. }
  66422. return _this;
  66423. }
  66424. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  66425. get: function () {
  66426. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  66427. },
  66428. enumerable: true,
  66429. configurable: true
  66430. });
  66431. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  66432. get: function () {
  66433. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  66434. },
  66435. enumerable: true,
  66436. configurable: true
  66437. });
  66438. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  66439. get: function () {
  66440. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  66441. },
  66442. enumerable: true,
  66443. configurable: true
  66444. });
  66445. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  66446. /**
  66447. * Use this list to define the list of mesh you want to render.
  66448. */
  66449. get: function () {
  66450. return this._renderList;
  66451. },
  66452. set: function (value) {
  66453. this._renderList = value;
  66454. if (this._renderList) {
  66455. this._hookArray(this._renderList);
  66456. }
  66457. },
  66458. enumerable: true,
  66459. configurable: true
  66460. });
  66461. RenderTargetTexture.prototype._hookArray = function (array) {
  66462. var _this = this;
  66463. var oldPush = array.push;
  66464. array.push = function () {
  66465. var items = [];
  66466. for (var _i = 0; _i < arguments.length; _i++) {
  66467. items[_i] = arguments[_i];
  66468. }
  66469. var result = oldPush.apply(array, items);
  66470. _this.getScene().meshes.forEach(function (mesh) {
  66471. mesh._markSubMeshesAsLightDirty();
  66472. });
  66473. return result;
  66474. };
  66475. var oldSplice = array.splice;
  66476. array.splice = function (index, deleteCount) {
  66477. var deleted = oldSplice.apply(array, [index, deleteCount]);
  66478. _this.getScene().meshes.forEach(function (mesh) {
  66479. mesh._markSubMeshesAsLightDirty();
  66480. });
  66481. return deleted;
  66482. };
  66483. };
  66484. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  66485. set: function (callback) {
  66486. if (this._onAfterUnbindObserver) {
  66487. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  66488. }
  66489. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  66490. },
  66491. enumerable: true,
  66492. configurable: true
  66493. });
  66494. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  66495. set: function (callback) {
  66496. if (this._onBeforeRenderObserver) {
  66497. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  66498. }
  66499. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  66500. },
  66501. enumerable: true,
  66502. configurable: true
  66503. });
  66504. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  66505. set: function (callback) {
  66506. if (this._onAfterRenderObserver) {
  66507. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  66508. }
  66509. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  66510. },
  66511. enumerable: true,
  66512. configurable: true
  66513. });
  66514. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  66515. set: function (callback) {
  66516. if (this._onClearObserver) {
  66517. this.onClearObservable.remove(this._onClearObserver);
  66518. }
  66519. this._onClearObserver = this.onClearObservable.add(callback);
  66520. },
  66521. enumerable: true,
  66522. configurable: true
  66523. });
  66524. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  66525. get: function () {
  66526. return this._renderTargetOptions;
  66527. },
  66528. enumerable: true,
  66529. configurable: true
  66530. });
  66531. RenderTargetTexture.prototype._onRatioRescale = function () {
  66532. if (this._sizeRatio) {
  66533. this.resize(this._initialSizeParameter);
  66534. }
  66535. };
  66536. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  66537. get: function () {
  66538. return this._boundingBoxSize;
  66539. },
  66540. /**
  66541. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  66542. * When defined, the cubemap will switch to local mode
  66543. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66544. * @example https://www.babylonjs-playground.com/#RNASML
  66545. */
  66546. set: function (value) {
  66547. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66548. return;
  66549. }
  66550. this._boundingBoxSize = value;
  66551. var scene = this.getScene();
  66552. if (scene) {
  66553. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66554. }
  66555. },
  66556. enumerable: true,
  66557. configurable: true
  66558. });
  66559. /**
  66560. * Creates a depth stencil texture.
  66561. * This is only available in WebGL 2 or with the depth texture extension available.
  66562. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  66563. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  66564. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  66565. */
  66566. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  66567. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  66568. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  66569. if (generateStencil === void 0) { generateStencil = false; }
  66570. if (!this.getScene()) {
  66571. return;
  66572. }
  66573. var engine = this.getScene().getEngine();
  66574. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  66575. bilinearFiltering: bilinearFiltering,
  66576. comparisonFunction: comparisonFunction,
  66577. generateStencil: generateStencil,
  66578. isCube: this.isCube
  66579. });
  66580. engine.setFrameBufferDepthStencilTexture(this);
  66581. };
  66582. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  66583. if (size.ratio) {
  66584. this._sizeRatio = size.ratio;
  66585. this._size = {
  66586. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  66587. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  66588. };
  66589. }
  66590. else {
  66591. this._size = size;
  66592. }
  66593. };
  66594. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  66595. get: function () {
  66596. return this._samples;
  66597. },
  66598. set: function (value) {
  66599. if (this._samples === value) {
  66600. return;
  66601. }
  66602. var scene = this.getScene();
  66603. if (!scene) {
  66604. return;
  66605. }
  66606. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  66607. },
  66608. enumerable: true,
  66609. configurable: true
  66610. });
  66611. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  66612. this._currentRefreshId = -1;
  66613. };
  66614. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  66615. get: function () {
  66616. return this._refreshRate;
  66617. },
  66618. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  66619. set: function (value) {
  66620. this._refreshRate = value;
  66621. this.resetRefreshCounter();
  66622. },
  66623. enumerable: true,
  66624. configurable: true
  66625. });
  66626. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  66627. if (!this._postProcessManager) {
  66628. var scene = this.getScene();
  66629. if (!scene) {
  66630. return;
  66631. }
  66632. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  66633. this._postProcesses = new Array();
  66634. }
  66635. this._postProcesses.push(postProcess);
  66636. this._postProcesses[0].autoClear = false;
  66637. };
  66638. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  66639. if (!this._postProcesses) {
  66640. return;
  66641. }
  66642. if (dispose) {
  66643. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  66644. var postProcess = _a[_i];
  66645. postProcess.dispose();
  66646. }
  66647. }
  66648. this._postProcesses = [];
  66649. };
  66650. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  66651. if (!this._postProcesses) {
  66652. return;
  66653. }
  66654. var index = this._postProcesses.indexOf(postProcess);
  66655. if (index === -1) {
  66656. return;
  66657. }
  66658. this._postProcesses.splice(index, 1);
  66659. if (this._postProcesses.length > 0) {
  66660. this._postProcesses[0].autoClear = false;
  66661. }
  66662. };
  66663. /** @hidden */
  66664. RenderTargetTexture.prototype._shouldRender = function () {
  66665. if (this._currentRefreshId === -1) { // At least render once
  66666. this._currentRefreshId = 1;
  66667. return true;
  66668. }
  66669. if (this.refreshRate === this._currentRefreshId) {
  66670. this._currentRefreshId = 1;
  66671. return true;
  66672. }
  66673. this._currentRefreshId++;
  66674. return false;
  66675. };
  66676. RenderTargetTexture.prototype.getRenderSize = function () {
  66677. if (this._size.width) {
  66678. return this._size.width;
  66679. }
  66680. return this._size;
  66681. };
  66682. RenderTargetTexture.prototype.getRenderWidth = function () {
  66683. if (this._size.width) {
  66684. return this._size.width;
  66685. }
  66686. return this._size;
  66687. };
  66688. RenderTargetTexture.prototype.getRenderHeight = function () {
  66689. if (this._size.width) {
  66690. return this._size.height;
  66691. }
  66692. return this._size;
  66693. };
  66694. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  66695. get: function () {
  66696. return true;
  66697. },
  66698. enumerable: true,
  66699. configurable: true
  66700. });
  66701. RenderTargetTexture.prototype.scale = function (ratio) {
  66702. var newSize = this.getRenderSize() * ratio;
  66703. this.resize(newSize);
  66704. };
  66705. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  66706. if (this.isCube) {
  66707. return this._textureMatrix;
  66708. }
  66709. return _super.prototype.getReflectionTextureMatrix.call(this);
  66710. };
  66711. RenderTargetTexture.prototype.resize = function (size) {
  66712. this.releaseInternalTexture();
  66713. var scene = this.getScene();
  66714. if (!scene) {
  66715. return;
  66716. }
  66717. this._processSizeParameter(size);
  66718. if (this.isCube) {
  66719. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  66720. }
  66721. else {
  66722. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  66723. }
  66724. };
  66725. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  66726. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  66727. if (dumpForDebug === void 0) { dumpForDebug = false; }
  66728. var scene = this.getScene();
  66729. if (!scene) {
  66730. return;
  66731. }
  66732. var engine = scene.getEngine();
  66733. if (this.useCameraPostProcesses !== undefined) {
  66734. useCameraPostProcess = this.useCameraPostProcesses;
  66735. }
  66736. if (this._waitingRenderList) {
  66737. this.renderList = [];
  66738. for (var index = 0; index < this._waitingRenderList.length; index++) {
  66739. var id = this._waitingRenderList[index];
  66740. var mesh_1 = scene.getMeshByID(id);
  66741. if (mesh_1) {
  66742. this.renderList.push(mesh_1);
  66743. }
  66744. }
  66745. delete this._waitingRenderList;
  66746. }
  66747. // Is predicate defined?
  66748. if (this.renderListPredicate) {
  66749. if (this.renderList) {
  66750. this.renderList.splice(0); // Clear previous renderList
  66751. }
  66752. else {
  66753. this.renderList = [];
  66754. }
  66755. var scene = this.getScene();
  66756. if (!scene) {
  66757. return;
  66758. }
  66759. var sceneMeshes = scene.meshes;
  66760. for (var index = 0; index < sceneMeshes.length; index++) {
  66761. var mesh = sceneMeshes[index];
  66762. if (this.renderListPredicate(mesh)) {
  66763. this.renderList.push(mesh);
  66764. }
  66765. }
  66766. }
  66767. this.onBeforeBindObservable.notifyObservers(this);
  66768. // Set custom projection.
  66769. // Needs to be before binding to prevent changing the aspect ratio.
  66770. var camera;
  66771. if (this.activeCamera) {
  66772. camera = this.activeCamera;
  66773. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66774. if (this.activeCamera !== scene.activeCamera) {
  66775. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  66776. }
  66777. }
  66778. else {
  66779. camera = scene.activeCamera;
  66780. if (camera) {
  66781. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66782. }
  66783. }
  66784. // Prepare renderingManager
  66785. this._renderingManager.reset();
  66786. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  66787. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  66788. var sceneRenderId = scene.getRenderId();
  66789. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  66790. var mesh = currentRenderList[meshIndex];
  66791. if (mesh) {
  66792. if (!mesh.isReady(this.refreshRate === 0)) {
  66793. this.resetRefreshCounter();
  66794. continue;
  66795. }
  66796. mesh._preActivateForIntermediateRendering(sceneRenderId);
  66797. var isMasked = void 0;
  66798. if (!this.renderList && camera) {
  66799. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  66800. }
  66801. else {
  66802. isMasked = false;
  66803. }
  66804. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  66805. mesh._activate(sceneRenderId);
  66806. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  66807. var subMesh = mesh.subMeshes[subIndex];
  66808. scene._activeIndices.addCount(subMesh.indexCount, false);
  66809. this._renderingManager.dispatch(subMesh, mesh);
  66810. }
  66811. }
  66812. }
  66813. }
  66814. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  66815. var particleSystem = scene.particleSystems[particleIndex];
  66816. var emitter = particleSystem.emitter;
  66817. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  66818. continue;
  66819. }
  66820. if (currentRenderList.indexOf(emitter) >= 0) {
  66821. this._renderingManager.dispatchParticles(particleSystem);
  66822. }
  66823. }
  66824. if (this.isCube) {
  66825. for (var face = 0; face < 6; face++) {
  66826. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  66827. scene.incrementRenderId();
  66828. scene.resetCachedMaterial();
  66829. }
  66830. }
  66831. else {
  66832. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  66833. }
  66834. this.onAfterUnbindObservable.notifyObservers(this);
  66835. if (scene.activeCamera) {
  66836. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  66837. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  66838. }
  66839. engine.setViewport(scene.activeCamera.viewport);
  66840. }
  66841. scene.resetCachedMaterial();
  66842. };
  66843. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  66844. var minimum = 128;
  66845. var x = renderDimension * scale;
  66846. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  66847. // Ensure we don't exceed the render dimension (while staying POT)
  66848. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  66849. };
  66850. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  66851. var _this = this;
  66852. if (!this._texture) {
  66853. return;
  66854. }
  66855. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  66856. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  66857. });
  66858. };
  66859. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  66860. var scene = this.getScene();
  66861. if (!scene) {
  66862. return;
  66863. }
  66864. var engine = scene.getEngine();
  66865. if (!this._texture) {
  66866. return;
  66867. }
  66868. // Bind
  66869. if (this._postProcessManager) {
  66870. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  66871. }
  66872. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  66873. if (this._texture) {
  66874. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  66875. }
  66876. }
  66877. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  66878. // Clear
  66879. if (this.onClearObservable.hasObservers()) {
  66880. this.onClearObservable.notifyObservers(engine);
  66881. }
  66882. else {
  66883. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  66884. }
  66885. if (!this._doNotChangeAspectRatio) {
  66886. scene.updateTransformMatrix(true);
  66887. }
  66888. // Render
  66889. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  66890. if (this._postProcessManager) {
  66891. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  66892. }
  66893. else if (useCameraPostProcess) {
  66894. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  66895. }
  66896. if (!this._doNotChangeAspectRatio) {
  66897. scene.updateTransformMatrix(true);
  66898. }
  66899. // Dump ?
  66900. if (dumpForDebug) {
  66901. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  66902. }
  66903. // Unbind
  66904. if (!this.isCube || faceIndex === 5) {
  66905. if (this.isCube) {
  66906. if (faceIndex === 5) {
  66907. engine.generateMipMapsForCubemap(this._texture);
  66908. }
  66909. }
  66910. this.unbindFrameBuffer(engine, faceIndex);
  66911. }
  66912. else {
  66913. this.onAfterRenderObservable.notifyObservers(faceIndex);
  66914. }
  66915. };
  66916. /**
  66917. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  66918. * This allowed control for front to back rendering or reversly depending of the special needs.
  66919. *
  66920. * @param renderingGroupId The rendering group id corresponding to its index
  66921. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  66922. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  66923. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  66924. */
  66925. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  66926. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  66927. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  66928. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  66929. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  66930. };
  66931. /**
  66932. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  66933. *
  66934. * @param renderingGroupId The rendering group id corresponding to its index
  66935. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  66936. */
  66937. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  66938. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  66939. this._renderingManager._useSceneAutoClearSetup = false;
  66940. };
  66941. RenderTargetTexture.prototype.clone = function () {
  66942. var textureSize = this.getSize();
  66943. 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);
  66944. // Base texture
  66945. newTexture.hasAlpha = this.hasAlpha;
  66946. newTexture.level = this.level;
  66947. // RenderTarget Texture
  66948. newTexture.coordinatesMode = this.coordinatesMode;
  66949. if (this.renderList) {
  66950. newTexture.renderList = this.renderList.slice(0);
  66951. }
  66952. return newTexture;
  66953. };
  66954. RenderTargetTexture.prototype.serialize = function () {
  66955. if (!this.name) {
  66956. return null;
  66957. }
  66958. var serializationObject = _super.prototype.serialize.call(this);
  66959. serializationObject.renderTargetSize = this.getRenderSize();
  66960. serializationObject.renderList = [];
  66961. if (this.renderList) {
  66962. for (var index = 0; index < this.renderList.length; index++) {
  66963. serializationObject.renderList.push(this.renderList[index].id);
  66964. }
  66965. }
  66966. return serializationObject;
  66967. };
  66968. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  66969. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  66970. var objBuffer = this.getInternalTexture();
  66971. var scene = this.getScene();
  66972. if (objBuffer && scene) {
  66973. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  66974. }
  66975. };
  66976. RenderTargetTexture.prototype.dispose = function () {
  66977. if (this._postProcessManager) {
  66978. this._postProcessManager.dispose();
  66979. this._postProcessManager = null;
  66980. }
  66981. this.clearPostProcesses(true);
  66982. if (this._resizeObserver) {
  66983. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  66984. this._resizeObserver = null;
  66985. }
  66986. this.renderList = null;
  66987. // Remove from custom render targets
  66988. var scene = this.getScene();
  66989. if (!scene) {
  66990. return;
  66991. }
  66992. var index = scene.customRenderTargets.indexOf(this);
  66993. if (index >= 0) {
  66994. scene.customRenderTargets.splice(index, 1);
  66995. }
  66996. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  66997. var camera = _a[_i];
  66998. index = camera.customRenderTargets.indexOf(this);
  66999. if (index >= 0) {
  67000. camera.customRenderTargets.splice(index, 1);
  67001. }
  67002. }
  67003. _super.prototype.dispose.call(this);
  67004. };
  67005. /** @hidden */
  67006. RenderTargetTexture.prototype._rebuild = function () {
  67007. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  67008. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  67009. }
  67010. if (this._postProcessManager) {
  67011. this._postProcessManager._rebuild();
  67012. }
  67013. };
  67014. /**
  67015. * Clear the info related to rendering groups preventing retention point in material dispose.
  67016. */
  67017. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  67018. if (this._renderingManager) {
  67019. this._renderingManager.freeRenderingGroups();
  67020. }
  67021. };
  67022. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  67023. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  67024. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  67025. return RenderTargetTexture;
  67026. }(BABYLON.Texture));
  67027. BABYLON.RenderTargetTexture = RenderTargetTexture;
  67028. })(BABYLON || (BABYLON = {}));
  67029. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  67030. var BABYLON;
  67031. (function (BABYLON) {
  67032. ;
  67033. var MultiRenderTarget = /** @class */ (function (_super) {
  67034. __extends(MultiRenderTarget, _super);
  67035. function MultiRenderTarget(name, size, count, scene, options) {
  67036. var _this = this;
  67037. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  67038. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  67039. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  67040. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  67041. _this._engine = scene.getEngine();
  67042. if (!_this.isSupported) {
  67043. _this.dispose();
  67044. return;
  67045. }
  67046. var types = [];
  67047. var samplingModes = [];
  67048. for (var i = 0; i < count; i++) {
  67049. if (options && options.types && options.types[i] !== undefined) {
  67050. types.push(options.types[i]);
  67051. }
  67052. else {
  67053. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67054. }
  67055. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  67056. samplingModes.push(options.samplingModes[i]);
  67057. }
  67058. else {
  67059. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67060. }
  67061. }
  67062. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  67063. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  67064. _this._size = size;
  67065. _this._multiRenderTargetOptions = {
  67066. samplingModes: samplingModes,
  67067. generateMipMaps: generateMipMaps,
  67068. generateDepthBuffer: generateDepthBuffer,
  67069. generateStencilBuffer: generateStencilBuffer,
  67070. generateDepthTexture: generateDepthTexture,
  67071. types: types,
  67072. textureCount: count
  67073. };
  67074. _this._createInternalTextures();
  67075. _this._createTextures();
  67076. return _this;
  67077. }
  67078. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  67079. get: function () {
  67080. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  67081. },
  67082. enumerable: true,
  67083. configurable: true
  67084. });
  67085. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  67086. get: function () {
  67087. return this._textures;
  67088. },
  67089. enumerable: true,
  67090. configurable: true
  67091. });
  67092. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  67093. get: function () {
  67094. return this._textures[this._textures.length - 1];
  67095. },
  67096. enumerable: true,
  67097. configurable: true
  67098. });
  67099. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  67100. set: function (wrap) {
  67101. if (this._textures) {
  67102. for (var i = 0; i < this._textures.length; i++) {
  67103. this._textures[i].wrapU = wrap;
  67104. }
  67105. }
  67106. },
  67107. enumerable: true,
  67108. configurable: true
  67109. });
  67110. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  67111. set: function (wrap) {
  67112. if (this._textures) {
  67113. for (var i = 0; i < this._textures.length; i++) {
  67114. this._textures[i].wrapV = wrap;
  67115. }
  67116. }
  67117. },
  67118. enumerable: true,
  67119. configurable: true
  67120. });
  67121. /** @hidden */
  67122. MultiRenderTarget.prototype._rebuild = function () {
  67123. this.releaseInternalTextures();
  67124. this._createInternalTextures();
  67125. for (var i = 0; i < this._internalTextures.length; i++) {
  67126. var texture = this._textures[i];
  67127. texture._texture = this._internalTextures[i];
  67128. }
  67129. // Keeps references to frame buffer and stencil/depth buffer
  67130. this._texture = this._internalTextures[0];
  67131. };
  67132. MultiRenderTarget.prototype._createInternalTextures = function () {
  67133. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  67134. };
  67135. MultiRenderTarget.prototype._createTextures = function () {
  67136. this._textures = [];
  67137. for (var i = 0; i < this._internalTextures.length; i++) {
  67138. var texture = new BABYLON.Texture(null, this.getScene());
  67139. texture._texture = this._internalTextures[i];
  67140. this._textures.push(texture);
  67141. }
  67142. // Keeps references to frame buffer and stencil/depth buffer
  67143. this._texture = this._internalTextures[0];
  67144. };
  67145. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  67146. get: function () {
  67147. return this._samples;
  67148. },
  67149. set: function (value) {
  67150. if (this._samples === value) {
  67151. return;
  67152. }
  67153. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  67154. },
  67155. enumerable: true,
  67156. configurable: true
  67157. });
  67158. MultiRenderTarget.prototype.resize = function (size) {
  67159. this.releaseInternalTextures();
  67160. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  67161. this._createInternalTextures();
  67162. };
  67163. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67164. var _this = this;
  67165. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  67166. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67167. });
  67168. };
  67169. MultiRenderTarget.prototype.dispose = function () {
  67170. this.releaseInternalTextures();
  67171. _super.prototype.dispose.call(this);
  67172. };
  67173. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  67174. if (!this._internalTextures) {
  67175. return;
  67176. }
  67177. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  67178. if (this._internalTextures[i] !== undefined) {
  67179. this._internalTextures[i].dispose();
  67180. this._internalTextures.splice(i, 1);
  67181. }
  67182. }
  67183. };
  67184. return MultiRenderTarget;
  67185. }(BABYLON.RenderTargetTexture));
  67186. BABYLON.MultiRenderTarget = MultiRenderTarget;
  67187. })(BABYLON || (BABYLON = {}));
  67188. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  67189. var BABYLON;
  67190. (function (BABYLON) {
  67191. var MirrorTexture = /** @class */ (function (_super) {
  67192. __extends(MirrorTexture, _super);
  67193. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  67194. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67195. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67196. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67197. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  67198. _this.scene = scene;
  67199. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  67200. _this._transformMatrix = BABYLON.Matrix.Zero();
  67201. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  67202. _this._adaptiveBlurKernel = 0;
  67203. _this._blurKernelX = 0;
  67204. _this._blurKernelY = 0;
  67205. _this._blurRatio = 1.0;
  67206. _this.ignoreCameraViewport = true;
  67207. _this._updateGammaSpace();
  67208. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  67209. _this._updateGammaSpace;
  67210. });
  67211. _this.onBeforeRenderObservable.add(function () {
  67212. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  67213. _this._savedViewMatrix = scene.getViewMatrix();
  67214. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  67215. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  67216. scene.clipPlane = _this.mirrorPlane;
  67217. scene.getEngine().cullBackFaces = false;
  67218. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  67219. });
  67220. _this.onAfterRenderObservable.add(function () {
  67221. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  67222. scene.getEngine().cullBackFaces = true;
  67223. scene._mirroredCameraPosition = null;
  67224. delete scene.clipPlane;
  67225. });
  67226. return _this;
  67227. }
  67228. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  67229. get: function () {
  67230. return this._blurRatio;
  67231. },
  67232. set: function (value) {
  67233. if (this._blurRatio === value) {
  67234. return;
  67235. }
  67236. this._blurRatio = value;
  67237. this._preparePostProcesses();
  67238. },
  67239. enumerable: true,
  67240. configurable: true
  67241. });
  67242. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  67243. set: function (value) {
  67244. this._adaptiveBlurKernel = value;
  67245. this._autoComputeBlurKernel();
  67246. },
  67247. enumerable: true,
  67248. configurable: true
  67249. });
  67250. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  67251. set: function (value) {
  67252. this.blurKernelX = value;
  67253. this.blurKernelY = value;
  67254. },
  67255. enumerable: true,
  67256. configurable: true
  67257. });
  67258. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  67259. get: function () {
  67260. return this._blurKernelX;
  67261. },
  67262. set: function (value) {
  67263. if (this._blurKernelX === value) {
  67264. return;
  67265. }
  67266. this._blurKernelX = value;
  67267. this._preparePostProcesses();
  67268. },
  67269. enumerable: true,
  67270. configurable: true
  67271. });
  67272. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  67273. get: function () {
  67274. return this._blurKernelY;
  67275. },
  67276. set: function (value) {
  67277. if (this._blurKernelY === value) {
  67278. return;
  67279. }
  67280. this._blurKernelY = value;
  67281. this._preparePostProcesses();
  67282. },
  67283. enumerable: true,
  67284. configurable: true
  67285. });
  67286. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  67287. var engine = this.getScene().getEngine();
  67288. var dw = this.getRenderWidth() / engine.getRenderWidth();
  67289. var dh = this.getRenderHeight() / engine.getRenderHeight();
  67290. this.blurKernelX = this._adaptiveBlurKernel * dw;
  67291. this.blurKernelY = this._adaptiveBlurKernel * dh;
  67292. };
  67293. MirrorTexture.prototype._onRatioRescale = function () {
  67294. if (this._sizeRatio) {
  67295. this.resize(this._initialSizeParameter);
  67296. if (!this._adaptiveBlurKernel) {
  67297. this._preparePostProcesses();
  67298. }
  67299. }
  67300. if (this._adaptiveBlurKernel) {
  67301. this._autoComputeBlurKernel();
  67302. }
  67303. };
  67304. MirrorTexture.prototype._updateGammaSpace = function () {
  67305. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  67306. };
  67307. MirrorTexture.prototype._preparePostProcesses = function () {
  67308. this.clearPostProcesses(true);
  67309. if (this._blurKernelX && this._blurKernelY) {
  67310. var engine = this.getScene().getEngine();
  67311. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67312. 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);
  67313. this._blurX.autoClear = false;
  67314. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  67315. this._blurX.inputTexture = this._texture;
  67316. }
  67317. else {
  67318. this._blurX.alwaysForcePOT = true;
  67319. }
  67320. 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);
  67321. this._blurY.autoClear = false;
  67322. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  67323. this.addPostProcess(this._blurX);
  67324. this.addPostProcess(this._blurY);
  67325. }
  67326. else {
  67327. if (this._blurY) {
  67328. this.removePostProcess(this._blurY);
  67329. this._blurY.dispose();
  67330. this._blurY = null;
  67331. }
  67332. if (this._blurX) {
  67333. this.removePostProcess(this._blurX);
  67334. this._blurX.dispose();
  67335. this._blurX = null;
  67336. }
  67337. }
  67338. };
  67339. MirrorTexture.prototype.clone = function () {
  67340. var scene = this.getScene();
  67341. if (!scene) {
  67342. return this;
  67343. }
  67344. var textureSize = this.getSize();
  67345. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  67346. // Base texture
  67347. newTexture.hasAlpha = this.hasAlpha;
  67348. newTexture.level = this.level;
  67349. // Mirror Texture
  67350. newTexture.mirrorPlane = this.mirrorPlane.clone();
  67351. if (this.renderList) {
  67352. newTexture.renderList = this.renderList.slice(0);
  67353. }
  67354. return newTexture;
  67355. };
  67356. MirrorTexture.prototype.serialize = function () {
  67357. if (!this.name) {
  67358. return null;
  67359. }
  67360. var serializationObject = _super.prototype.serialize.call(this);
  67361. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  67362. return serializationObject;
  67363. };
  67364. MirrorTexture.prototype.dispose = function () {
  67365. _super.prototype.dispose.call(this);
  67366. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  67367. };
  67368. return MirrorTexture;
  67369. }(BABYLON.RenderTargetTexture));
  67370. BABYLON.MirrorTexture = MirrorTexture;
  67371. })(BABYLON || (BABYLON = {}));
  67372. //# sourceMappingURL=babylon.mirrorTexture.js.map
  67373. var BABYLON;
  67374. (function (BABYLON) {
  67375. /**
  67376. * Creates a refraction texture used by refraction channel of the standard material.
  67377. * @param name the texture name
  67378. * @param size size of the underlying texture
  67379. * @param scene root scene
  67380. */
  67381. var RefractionTexture = /** @class */ (function (_super) {
  67382. __extends(RefractionTexture, _super);
  67383. function RefractionTexture(name, size, scene, generateMipMaps) {
  67384. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  67385. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  67386. _this.depth = 2.0;
  67387. _this.onBeforeRenderObservable.add(function () {
  67388. scene.clipPlane = _this.refractionPlane;
  67389. });
  67390. _this.onAfterRenderObservable.add(function () {
  67391. delete scene.clipPlane;
  67392. });
  67393. return _this;
  67394. }
  67395. RefractionTexture.prototype.clone = function () {
  67396. var scene = this.getScene();
  67397. if (!scene) {
  67398. return this;
  67399. }
  67400. var textureSize = this.getSize();
  67401. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  67402. // Base texture
  67403. newTexture.hasAlpha = this.hasAlpha;
  67404. newTexture.level = this.level;
  67405. // Refraction Texture
  67406. newTexture.refractionPlane = this.refractionPlane.clone();
  67407. if (this.renderList) {
  67408. newTexture.renderList = this.renderList.slice(0);
  67409. }
  67410. newTexture.depth = this.depth;
  67411. return newTexture;
  67412. };
  67413. RefractionTexture.prototype.serialize = function () {
  67414. if (!this.name) {
  67415. return null;
  67416. }
  67417. var serializationObject = _super.prototype.serialize.call(this);
  67418. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  67419. serializationObject.depth = this.depth;
  67420. return serializationObject;
  67421. };
  67422. return RefractionTexture;
  67423. }(BABYLON.RenderTargetTexture));
  67424. BABYLON.RefractionTexture = RefractionTexture;
  67425. })(BABYLON || (BABYLON = {}));
  67426. //# sourceMappingURL=babylon.refractionTexture.js.map
  67427. var BABYLON;
  67428. (function (BABYLON) {
  67429. /**
  67430. * A class extending {BABYLON.Texture} allowing drawing on a texture
  67431. * @see http://doc.babylonjs.com/how_to/dynamictexture
  67432. */
  67433. var DynamicTexture = /** @class */ (function (_super) {
  67434. __extends(DynamicTexture, _super);
  67435. /**
  67436. * Creates a {BABYLON.DynamicTexture}
  67437. * @param name defines the name of the texture
  67438. * @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
  67439. * @param scene defines the scene where you want the texture
  67440. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  67441. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  67442. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  67443. */
  67444. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  67445. if (scene === void 0) { scene = null; }
  67446. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67447. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67448. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  67449. _this.name = name;
  67450. _this._engine = _this.getScene().getEngine();
  67451. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67452. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67453. _this._generateMipMaps = generateMipMaps;
  67454. if (options.getContext) {
  67455. _this._canvas = options;
  67456. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67457. }
  67458. else {
  67459. _this._canvas = document.createElement("canvas");
  67460. if (options.width || options.width === 0) {
  67461. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67462. }
  67463. else {
  67464. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  67465. }
  67466. }
  67467. var textureSize = _this.getSize();
  67468. _this._canvas.width = textureSize.width;
  67469. _this._canvas.height = textureSize.height;
  67470. _this._context = _this._canvas.getContext("2d");
  67471. return _this;
  67472. }
  67473. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  67474. /**
  67475. * Gets the current state of canRescale
  67476. */
  67477. get: function () {
  67478. return true;
  67479. },
  67480. enumerable: true,
  67481. configurable: true
  67482. });
  67483. DynamicTexture.prototype._recreate = function (textureSize) {
  67484. this._canvas.width = textureSize.width;
  67485. this._canvas.height = textureSize.height;
  67486. this.releaseInternalTexture();
  67487. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  67488. };
  67489. /**
  67490. * Scales the texture
  67491. * @param ratio the scale factor to apply to both width and height
  67492. */
  67493. DynamicTexture.prototype.scale = function (ratio) {
  67494. var textureSize = this.getSize();
  67495. textureSize.width *= ratio;
  67496. textureSize.height *= ratio;
  67497. this._recreate(textureSize);
  67498. };
  67499. /**
  67500. * Resizes the texture
  67501. * @param width the new width
  67502. * @param height the new height
  67503. */
  67504. DynamicTexture.prototype.scaleTo = function (width, height) {
  67505. var textureSize = this.getSize();
  67506. textureSize.width = width;
  67507. textureSize.height = height;
  67508. this._recreate(textureSize);
  67509. };
  67510. /**
  67511. * Gets the context of the canvas used by the texture
  67512. * @returns the canvas context of the dynamic texture
  67513. */
  67514. DynamicTexture.prototype.getContext = function () {
  67515. return this._context;
  67516. };
  67517. /**
  67518. * Clears the texture
  67519. */
  67520. DynamicTexture.prototype.clear = function () {
  67521. var size = this.getSize();
  67522. this._context.fillRect(0, 0, size.width, size.height);
  67523. };
  67524. /**
  67525. * Updates the texture
  67526. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67527. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  67528. */
  67529. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  67530. if (premulAlpha === void 0) { premulAlpha = false; }
  67531. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  67532. };
  67533. /**
  67534. * Draws text onto the texture
  67535. * @param text defines the text to be drawn
  67536. * @param x defines the placement of the text from the left
  67537. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  67538. * @param font defines the font to be used with font-style, font-size, font-name
  67539. * @param color defines the color used for the text
  67540. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  67541. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67542. * @param update defines whether texture is immediately update (default is true)
  67543. */
  67544. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  67545. if (update === void 0) { update = true; }
  67546. var size = this.getSize();
  67547. if (clearColor) {
  67548. this._context.fillStyle = clearColor;
  67549. this._context.fillRect(0, 0, size.width, size.height);
  67550. }
  67551. this._context.font = font;
  67552. if (x === null || x === undefined) {
  67553. var textSize = this._context.measureText(text);
  67554. x = (size.width - textSize.width) / 2;
  67555. }
  67556. if (y === null || y === undefined) {
  67557. var fontSize = parseInt((font.replace(/\D/g, '')));
  67558. y = (size.height / 2) + (fontSize / 3.65);
  67559. }
  67560. this._context.fillStyle = color;
  67561. this._context.fillText(text, x, y);
  67562. if (update) {
  67563. this.update(invertY);
  67564. }
  67565. };
  67566. /**
  67567. * Clones the texture
  67568. * @returns the clone of the texture.
  67569. */
  67570. DynamicTexture.prototype.clone = function () {
  67571. var scene = this.getScene();
  67572. if (!scene) {
  67573. return this;
  67574. }
  67575. var textureSize = this.getSize();
  67576. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  67577. // Base texture
  67578. newTexture.hasAlpha = this.hasAlpha;
  67579. newTexture.level = this.level;
  67580. // Dynamic Texture
  67581. newTexture.wrapU = this.wrapU;
  67582. newTexture.wrapV = this.wrapV;
  67583. return newTexture;
  67584. };
  67585. /**
  67586. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  67587. * @returns a serialized dynamic texture object
  67588. */
  67589. DynamicTexture.prototype.serialize = function () {
  67590. var scene = this.getScene();
  67591. if (scene && !scene.isReady()) {
  67592. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  67593. }
  67594. var serializationObject = _super.prototype.serialize.call(this);
  67595. serializationObject.base64String = this._canvas.toDataURL();
  67596. serializationObject.invertY = this._invertY;
  67597. serializationObject.samplingMode = this.samplingMode;
  67598. return serializationObject;
  67599. };
  67600. /** @hidden */
  67601. DynamicTexture.prototype._rebuild = function () {
  67602. this.update();
  67603. };
  67604. return DynamicTexture;
  67605. }(BABYLON.Texture));
  67606. BABYLON.DynamicTexture = DynamicTexture;
  67607. })(BABYLON || (BABYLON = {}));
  67608. //# sourceMappingURL=babylon.dynamicTexture.js.map
  67609. var BABYLON;
  67610. (function (BABYLON) {
  67611. var VideoTexture = /** @class */ (function (_super) {
  67612. __extends(VideoTexture, _super);
  67613. /**
  67614. * Creates a video texture.
  67615. * Sample : https://doc.babylonjs.com/how_to/video_texture
  67616. * @param {string | null} name optional name, will detect from video source, if not defined
  67617. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  67618. * @param {BABYLON.Scene} scene is obviously the current scene.
  67619. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  67620. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  67621. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  67622. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  67623. */
  67624. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  67625. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67626. if (invertY === void 0) { invertY = false; }
  67627. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67628. if (settings === void 0) { settings = {
  67629. autoPlay: true,
  67630. loop: true,
  67631. autoUpdateTexture: true,
  67632. }; }
  67633. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67634. _this._onUserActionRequestedObservable = null;
  67635. _this._stillImageCaptured = false;
  67636. _this._poster = false;
  67637. _this._createInternalTexture = function () {
  67638. if (_this._texture != null) {
  67639. if (_this._poster) {
  67640. _this._texture.dispose();
  67641. _this._poster = false;
  67642. }
  67643. else {
  67644. return;
  67645. }
  67646. }
  67647. if (!_this._engine.needPOTTextures ||
  67648. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  67649. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67650. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67651. }
  67652. else {
  67653. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67654. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67655. _this._generateMipMaps = false;
  67656. }
  67657. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  67658. if (!_this.video.autoplay) {
  67659. var oldHandler_1 = _this.video.onplaying;
  67660. var error_1 = false;
  67661. _this.video.onplaying = function () {
  67662. _this.video.onplaying = oldHandler_1;
  67663. _this._texture.isReady = true;
  67664. _this._updateInternalTexture();
  67665. if (!error_1) {
  67666. _this.video.pause();
  67667. }
  67668. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67669. _this.onLoadObservable.notifyObservers(_this);
  67670. }
  67671. };
  67672. var playing = _this.video.play();
  67673. if (playing) {
  67674. playing.then(function () {
  67675. // Everything is good.
  67676. })
  67677. .catch(function () {
  67678. error_1 = true;
  67679. // On Chrome for instance, new policies might prevent playing without user interaction.
  67680. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  67681. _this._onUserActionRequestedObservable.notifyObservers(_this);
  67682. }
  67683. });
  67684. }
  67685. else {
  67686. _this.video.onplaying = oldHandler_1;
  67687. _this._texture.isReady = true;
  67688. _this._updateInternalTexture();
  67689. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67690. _this.onLoadObservable.notifyObservers(_this);
  67691. }
  67692. }
  67693. }
  67694. else {
  67695. _this._texture.isReady = true;
  67696. _this._updateInternalTexture();
  67697. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67698. _this.onLoadObservable.notifyObservers(_this);
  67699. }
  67700. }
  67701. };
  67702. _this.reset = function () {
  67703. if (_this._texture == null) {
  67704. return;
  67705. }
  67706. if (!_this._poster) {
  67707. _this._texture.dispose();
  67708. _this._texture = null;
  67709. }
  67710. };
  67711. _this._updateInternalTexture = function (e) {
  67712. if (_this._texture == null || !_this._texture.isReady) {
  67713. return;
  67714. }
  67715. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  67716. return;
  67717. }
  67718. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  67719. };
  67720. _this._engine = _this.getScene().getEngine();
  67721. _this._generateMipMaps = generateMipMaps;
  67722. _this._samplingMode = samplingMode;
  67723. _this.autoUpdateTexture = settings.autoUpdateTexture;
  67724. _this.name = name || _this._getName(src);
  67725. _this.video = _this._getVideo(src);
  67726. if (settings.poster) {
  67727. _this.video.poster = settings.poster;
  67728. }
  67729. if (settings.autoPlay !== undefined) {
  67730. _this.video.autoplay = settings.autoPlay;
  67731. }
  67732. if (settings.loop !== undefined) {
  67733. _this.video.loop = settings.loop;
  67734. }
  67735. _this.video.setAttribute("playsinline", "");
  67736. _this.video.addEventListener("canplay", _this._createInternalTexture);
  67737. _this.video.addEventListener("paused", _this._updateInternalTexture);
  67738. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  67739. _this.video.addEventListener("emptied", _this.reset);
  67740. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  67741. _this._createInternalTexture();
  67742. }
  67743. if (settings.poster) {
  67744. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  67745. _this._poster = true;
  67746. }
  67747. return _this;
  67748. }
  67749. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  67750. get: function () {
  67751. if (!this._onUserActionRequestedObservable) {
  67752. this._onUserActionRequestedObservable = new BABYLON.Observable();
  67753. }
  67754. return this._onUserActionRequestedObservable;
  67755. },
  67756. enumerable: true,
  67757. configurable: true
  67758. });
  67759. VideoTexture.prototype._getName = function (src) {
  67760. if (src instanceof HTMLVideoElement) {
  67761. return src.currentSrc;
  67762. }
  67763. if (typeof src === "object") {
  67764. return src.toString();
  67765. }
  67766. return src;
  67767. };
  67768. ;
  67769. VideoTexture.prototype._getVideo = function (src) {
  67770. if (src instanceof HTMLVideoElement) {
  67771. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  67772. return src;
  67773. }
  67774. var video = document.createElement("video");
  67775. if (typeof src === "string") {
  67776. BABYLON.Tools.SetCorsBehavior(src, video);
  67777. video.src = src;
  67778. }
  67779. else {
  67780. BABYLON.Tools.SetCorsBehavior(src[0], video);
  67781. src.forEach(function (url) {
  67782. var source = document.createElement("source");
  67783. source.src = url;
  67784. video.appendChild(source);
  67785. });
  67786. }
  67787. return video;
  67788. };
  67789. ;
  67790. /**
  67791. * @hidden Internal method to initiate `update`.
  67792. */
  67793. VideoTexture.prototype._rebuild = function () {
  67794. this.update();
  67795. };
  67796. /**
  67797. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  67798. */
  67799. VideoTexture.prototype.update = function () {
  67800. if (!this.autoUpdateTexture) {
  67801. // Expecting user to call `updateTexture` manually
  67802. return;
  67803. }
  67804. this.updateTexture(true);
  67805. };
  67806. /**
  67807. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  67808. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  67809. */
  67810. VideoTexture.prototype.updateTexture = function (isVisible) {
  67811. if (!isVisible) {
  67812. return;
  67813. }
  67814. if (this.video.paused && this._stillImageCaptured) {
  67815. return;
  67816. }
  67817. this._stillImageCaptured = true;
  67818. this._updateInternalTexture();
  67819. };
  67820. /**
  67821. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  67822. * @param url New url.
  67823. */
  67824. VideoTexture.prototype.updateURL = function (url) {
  67825. this.video.src = url;
  67826. };
  67827. VideoTexture.prototype.dispose = function () {
  67828. _super.prototype.dispose.call(this);
  67829. if (this._onUserActionRequestedObservable) {
  67830. this._onUserActionRequestedObservable.clear();
  67831. this._onUserActionRequestedObservable = null;
  67832. }
  67833. this.video.removeEventListener("canplay", this._createInternalTexture);
  67834. this.video.removeEventListener("paused", this._updateInternalTexture);
  67835. this.video.removeEventListener("seeked", this._updateInternalTexture);
  67836. this.video.removeEventListener("emptied", this.reset);
  67837. this.video.pause();
  67838. };
  67839. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  67840. var video = document.createElement("video");
  67841. video.setAttribute('autoplay', '');
  67842. video.setAttribute('muted', '');
  67843. video.setAttribute('playsinline', '');
  67844. var constraintsDeviceId;
  67845. if (constraints && constraints.deviceId) {
  67846. constraintsDeviceId = {
  67847. exact: constraints.deviceId,
  67848. };
  67849. }
  67850. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  67851. if (navigator.mediaDevices) {
  67852. navigator.mediaDevices.getUserMedia({ video: constraints })
  67853. .then(function (stream) {
  67854. if (video.mozSrcObject !== undefined) {
  67855. // hack for Firefox < 19
  67856. video.mozSrcObject = stream;
  67857. }
  67858. else {
  67859. video.srcObject = stream;
  67860. }
  67861. var onPlaying = function () {
  67862. if (onReady) {
  67863. onReady(new VideoTexture("video", video, scene, true, true));
  67864. }
  67865. video.removeEventListener("playing", onPlaying);
  67866. };
  67867. video.addEventListener("playing", onPlaying);
  67868. video.play();
  67869. })
  67870. .catch(function (err) {
  67871. BABYLON.Tools.Error(err.name);
  67872. });
  67873. }
  67874. else {
  67875. navigator.getUserMedia =
  67876. navigator.getUserMedia ||
  67877. navigator.webkitGetUserMedia ||
  67878. navigator.mozGetUserMedia ||
  67879. navigator.msGetUserMedia;
  67880. if (navigator.getUserMedia) {
  67881. navigator.getUserMedia({
  67882. video: {
  67883. deviceId: constraintsDeviceId,
  67884. width: {
  67885. min: (constraints && constraints.minWidth) || 256,
  67886. max: (constraints && constraints.maxWidth) || 640,
  67887. },
  67888. height: {
  67889. min: (constraints && constraints.minHeight) || 256,
  67890. max: (constraints && constraints.maxHeight) || 480,
  67891. },
  67892. },
  67893. }, function (stream) {
  67894. if (video.mozSrcObject !== undefined) {
  67895. // hack for Firefox < 19
  67896. video.mozSrcObject = stream;
  67897. }
  67898. else {
  67899. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  67900. }
  67901. video.play();
  67902. if (onReady) {
  67903. onReady(new VideoTexture("video", video, scene, true, true));
  67904. }
  67905. }, function (e) {
  67906. BABYLON.Tools.Error(e.name);
  67907. });
  67908. }
  67909. }
  67910. };
  67911. return VideoTexture;
  67912. }(BABYLON.Texture));
  67913. BABYLON.VideoTexture = VideoTexture;
  67914. })(BABYLON || (BABYLON = {}));
  67915. //# sourceMappingURL=babylon.videoTexture.js.map
  67916. var BABYLON;
  67917. (function (BABYLON) {
  67918. var RawTexture = /** @class */ (function (_super) {
  67919. __extends(RawTexture, _super);
  67920. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  67921. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67922. if (invertY === void 0) { invertY = false; }
  67923. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67924. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67925. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67926. _this.format = format;
  67927. _this._engine = scene.getEngine();
  67928. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  67929. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67930. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67931. return _this;
  67932. }
  67933. RawTexture.prototype.update = function (data) {
  67934. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  67935. };
  67936. // Statics
  67937. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67938. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67939. if (invertY === void 0) { invertY = false; }
  67940. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67941. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  67942. };
  67943. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67944. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67945. if (invertY === void 0) { invertY = false; }
  67946. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67947. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  67948. };
  67949. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67950. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67951. if (invertY === void 0) { invertY = false; }
  67952. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67953. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  67954. };
  67955. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67956. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67957. if (invertY === void 0) { invertY = false; }
  67958. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67959. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67960. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  67961. };
  67962. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67963. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67964. if (invertY === void 0) { invertY = false; }
  67965. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67966. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67967. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  67968. };
  67969. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67970. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67971. if (invertY === void 0) { invertY = false; }
  67972. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67973. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67974. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  67975. };
  67976. return RawTexture;
  67977. }(BABYLON.Texture));
  67978. BABYLON.RawTexture = RawTexture;
  67979. })(BABYLON || (BABYLON = {}));
  67980. //# sourceMappingURL=babylon.rawTexture.js.map
  67981. var BABYLON;
  67982. (function (BABYLON) {
  67983. /**
  67984. * Class used to store 3D textures containing user data
  67985. */
  67986. var RawTexture3D = /** @class */ (function (_super) {
  67987. __extends(RawTexture3D, _super);
  67988. /**
  67989. * Create a new RawTexture3D
  67990. * @param data defines the data of the texture
  67991. * @param width defines the width of the texture
  67992. * @param height defines the height of the texture
  67993. * @param depth defines the depth of the texture
  67994. * @param format defines the texture format to use
  67995. * @param scene defines the hosting scene
  67996. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  67997. * @param invertY defines if texture must be stored with Y axis inverted
  67998. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  67999. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  68000. */
  68001. function RawTexture3D(data, width, height, depth,
  68002. /** Gets or sets the texture format to use */
  68003. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  68004. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68005. if (invertY === void 0) { invertY = false; }
  68006. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68007. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68008. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68009. _this.format = format;
  68010. _this._engine = scene.getEngine();
  68011. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  68012. _this.is3D = true;
  68013. return _this;
  68014. }
  68015. /**
  68016. * Update the texture with new data
  68017. * @param data defines the data to store in the texture
  68018. */
  68019. RawTexture3D.prototype.update = function (data) {
  68020. if (!this._texture) {
  68021. return;
  68022. }
  68023. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68024. };
  68025. return RawTexture3D;
  68026. }(BABYLON.Texture));
  68027. BABYLON.RawTexture3D = RawTexture3D;
  68028. })(BABYLON || (BABYLON = {}));
  68029. //# sourceMappingURL=babylon.rawTexture3D.js.map
  68030. var BABYLON;
  68031. (function (BABYLON) {
  68032. /**
  68033. * PostProcessManager is used to manage one or more post processes or post process pipelines
  68034. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68035. */
  68036. var PostProcessManager = /** @class */ (function () {
  68037. /**
  68038. * Creates a new instance PostProcess
  68039. * @param scene The scene that the post process is associated with.
  68040. */
  68041. function PostProcessManager(scene) {
  68042. this._vertexBuffers = {};
  68043. this._scene = scene;
  68044. }
  68045. PostProcessManager.prototype._prepareBuffers = function () {
  68046. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  68047. return;
  68048. }
  68049. // VBO
  68050. var vertices = [];
  68051. vertices.push(1, 1);
  68052. vertices.push(-1, 1);
  68053. vertices.push(-1, -1);
  68054. vertices.push(1, -1);
  68055. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68056. this._buildIndexBuffer();
  68057. };
  68058. PostProcessManager.prototype._buildIndexBuffer = function () {
  68059. // Indices
  68060. var indices = [];
  68061. indices.push(0);
  68062. indices.push(1);
  68063. indices.push(2);
  68064. indices.push(0);
  68065. indices.push(2);
  68066. indices.push(3);
  68067. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  68068. };
  68069. /**
  68070. * Rebuilds the vertex buffers of the manager.
  68071. * @hidden
  68072. */
  68073. PostProcessManager.prototype._rebuild = function () {
  68074. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68075. if (!vb) {
  68076. return;
  68077. }
  68078. vb._rebuild();
  68079. this._buildIndexBuffer();
  68080. };
  68081. // Methods
  68082. /**
  68083. * Prepares a frame to be run through a post process.
  68084. * @param sourceTexture The input texture to the post procesess. (default: null)
  68085. * @param postProcesses An array of post processes to be run. (default: null)
  68086. * @returns True if the post processes were able to be run.
  68087. * @hidden
  68088. */
  68089. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  68090. if (sourceTexture === void 0) { sourceTexture = null; }
  68091. if (postProcesses === void 0) { postProcesses = null; }
  68092. var camera = this._scene.activeCamera;
  68093. if (!camera) {
  68094. return false;
  68095. }
  68096. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  68097. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  68098. return false;
  68099. }
  68100. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  68101. return true;
  68102. };
  68103. /**
  68104. * Manually render a set of post processes to a texture.
  68105. * @param postProcesses An array of post processes to be run.
  68106. * @param targetTexture The target texture to render to.
  68107. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  68108. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  68109. * @param lodLevel defines which lod of the texture to render to
  68110. */
  68111. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  68112. if (targetTexture === void 0) { targetTexture = null; }
  68113. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  68114. if (faceIndex === void 0) { faceIndex = 0; }
  68115. if (lodLevel === void 0) { lodLevel = 0; }
  68116. var engine = this._scene.getEngine();
  68117. for (var index = 0; index < postProcesses.length; index++) {
  68118. if (index < postProcesses.length - 1) {
  68119. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  68120. }
  68121. else {
  68122. if (targetTexture) {
  68123. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  68124. }
  68125. else {
  68126. engine.restoreDefaultFramebuffer();
  68127. }
  68128. }
  68129. var pp = postProcesses[index];
  68130. var effect = pp.apply();
  68131. if (effect) {
  68132. pp.onBeforeRenderObservable.notifyObservers(effect);
  68133. // VBOs
  68134. this._prepareBuffers();
  68135. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68136. // Draw order
  68137. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68138. pp.onAfterRenderObservable.notifyObservers(effect);
  68139. }
  68140. }
  68141. // Restore depth buffer
  68142. engine.setDepthBuffer(true);
  68143. engine.setDepthWrite(true);
  68144. };
  68145. /**
  68146. * Finalize the result of the output of the postprocesses.
  68147. * @param doNotPresent If true the result will not be displayed to the screen.
  68148. * @param targetTexture The target texture to render to.
  68149. * @param faceIndex The index of the face to bind the target texture to.
  68150. * @param postProcesses The array of post processes to render.
  68151. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  68152. * @hidden
  68153. */
  68154. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  68155. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  68156. var camera = this._scene.activeCamera;
  68157. if (!camera) {
  68158. return;
  68159. }
  68160. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  68161. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  68162. return;
  68163. }
  68164. var engine = this._scene.getEngine();
  68165. for (var index = 0, len = postProcesses.length; index < len; index++) {
  68166. var pp = postProcesses[index];
  68167. if (index < len - 1) {
  68168. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  68169. }
  68170. else {
  68171. if (targetTexture) {
  68172. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  68173. pp._outputTexture = targetTexture;
  68174. }
  68175. else {
  68176. engine.restoreDefaultFramebuffer();
  68177. pp._outputTexture = null;
  68178. }
  68179. }
  68180. if (doNotPresent) {
  68181. break;
  68182. }
  68183. var effect = pp.apply();
  68184. if (effect) {
  68185. pp.onBeforeRenderObservable.notifyObservers(effect);
  68186. // VBOs
  68187. this._prepareBuffers();
  68188. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68189. // Draw order
  68190. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68191. pp.onAfterRenderObservable.notifyObservers(effect);
  68192. }
  68193. }
  68194. // Restore states
  68195. engine.setDepthBuffer(true);
  68196. engine.setDepthWrite(true);
  68197. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68198. };
  68199. /**
  68200. * Disposes of the post process manager.
  68201. */
  68202. PostProcessManager.prototype.dispose = function () {
  68203. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68204. if (buffer) {
  68205. buffer.dispose();
  68206. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68207. }
  68208. if (this._indexBuffer) {
  68209. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68210. this._indexBuffer = null;
  68211. }
  68212. };
  68213. return PostProcessManager;
  68214. }());
  68215. BABYLON.PostProcessManager = PostProcessManager;
  68216. })(BABYLON || (BABYLON = {}));
  68217. //# sourceMappingURL=babylon.postProcessManager.js.map
  68218. var BABYLON;
  68219. (function (BABYLON) {
  68220. /**
  68221. * PostProcess can be used to apply a shader to a texture after it has been rendered
  68222. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68223. */
  68224. var PostProcess = /** @class */ (function () {
  68225. /**
  68226. * Creates a new instance PostProcess
  68227. * @param name The name of the PostProcess.
  68228. * @param fragmentUrl The url of the fragment shader to be used.
  68229. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  68230. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  68231. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68232. * @param camera The camera to apply the render pass to.
  68233. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68234. * @param engine The engine which the post process will be applied. (default: current engine)
  68235. * @param reusable If the post process can be reused on the same frame. (default: false)
  68236. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  68237. * @param textureType Type of textures used when performing the post process. (default: 0)
  68238. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  68239. * @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
  68240. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  68241. */
  68242. function PostProcess(
  68243. /** Name of the PostProcess. */
  68244. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  68245. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  68246. if (defines === void 0) { defines = null; }
  68247. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68248. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  68249. if (blockCompilation === void 0) { blockCompilation = false; }
  68250. this.name = name;
  68251. /**
  68252. * Width of the texture to apply the post process on
  68253. */
  68254. this.width = -1;
  68255. /**
  68256. * Height of the texture to apply the post process on
  68257. */
  68258. this.height = -1;
  68259. /**
  68260. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  68261. * @hidden
  68262. */
  68263. this._outputTexture = null;
  68264. /**
  68265. * If the buffer needs to be cleared before applying the post process. (default: true)
  68266. * Should be set to false if shader will overwrite all previous pixels.
  68267. */
  68268. this.autoClear = true;
  68269. /**
  68270. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  68271. */
  68272. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  68273. /**
  68274. * Animations to be used for the post processing
  68275. */
  68276. this.animations = new Array();
  68277. /**
  68278. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  68279. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  68280. */
  68281. this.enablePixelPerfectMode = false;
  68282. /**
  68283. * Force the postprocess to be applied without taking in account viewport
  68284. */
  68285. this.forceFullscreenViewport = true;
  68286. /**
  68287. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  68288. *
  68289. * | Value | Type | Description |
  68290. * | ----- | ----------------------------------- | ----------- |
  68291. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  68292. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  68293. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  68294. *
  68295. */
  68296. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  68297. /**
  68298. * Force textures to be a power of two (default: false)
  68299. */
  68300. this.alwaysForcePOT = false;
  68301. this._samples = 1;
  68302. /**
  68303. * Modify the scale of the post process to be the same as the viewport (default: false)
  68304. */
  68305. this.adaptScaleToCurrentViewport = false;
  68306. this._reusable = false;
  68307. /**
  68308. * Smart array of input and output textures for the post process.
  68309. * @hidden
  68310. */
  68311. this._textures = new BABYLON.SmartArray(2);
  68312. /**
  68313. * The index in _textures that corresponds to the output texture.
  68314. * @hidden
  68315. */
  68316. this._currentRenderTextureInd = 0;
  68317. this._scaleRatio = new BABYLON.Vector2(1, 1);
  68318. this._texelSize = BABYLON.Vector2.Zero();
  68319. // Events
  68320. /**
  68321. * An event triggered when the postprocess is activated.
  68322. */
  68323. this.onActivateObservable = new BABYLON.Observable();
  68324. /**
  68325. * An event triggered when the postprocess changes its size.
  68326. */
  68327. this.onSizeChangedObservable = new BABYLON.Observable();
  68328. /**
  68329. * An event triggered when the postprocess applies its effect.
  68330. */
  68331. this.onApplyObservable = new BABYLON.Observable();
  68332. /**
  68333. * An event triggered before rendering the postprocess
  68334. */
  68335. this.onBeforeRenderObservable = new BABYLON.Observable();
  68336. /**
  68337. * An event triggered after rendering the postprocess
  68338. */
  68339. this.onAfterRenderObservable = new BABYLON.Observable();
  68340. if (camera != null) {
  68341. this._camera = camera;
  68342. this._scene = camera.getScene();
  68343. camera.attachPostProcess(this);
  68344. this._engine = this._scene.getEngine();
  68345. this._scene.postProcesses.push(this);
  68346. }
  68347. else if (engine) {
  68348. this._engine = engine;
  68349. this._engine.postProcesses.push(this);
  68350. }
  68351. this._options = options;
  68352. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  68353. this._reusable = reusable || false;
  68354. this._textureType = textureType;
  68355. this._samplers = samplers || [];
  68356. this._samplers.push("textureSampler");
  68357. this._fragmentUrl = fragmentUrl;
  68358. this._vertexUrl = vertexUrl;
  68359. this._parameters = parameters || [];
  68360. this._parameters.push("scale");
  68361. this._indexParameters = indexParameters;
  68362. if (!blockCompilation) {
  68363. this.updateEffect(defines);
  68364. }
  68365. }
  68366. Object.defineProperty(PostProcess.prototype, "samples", {
  68367. /**
  68368. * Number of sample textures (default: 1)
  68369. */
  68370. get: function () {
  68371. return this._samples;
  68372. },
  68373. set: function (n) {
  68374. var _this = this;
  68375. this._samples = n;
  68376. this._textures.forEach(function (texture) {
  68377. if (texture.samples !== _this._samples) {
  68378. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  68379. }
  68380. });
  68381. },
  68382. enumerable: true,
  68383. configurable: true
  68384. });
  68385. Object.defineProperty(PostProcess.prototype, "onActivate", {
  68386. /**
  68387. * A function that is added to the onActivateObservable
  68388. */
  68389. set: function (callback) {
  68390. if (this._onActivateObserver) {
  68391. this.onActivateObservable.remove(this._onActivateObserver);
  68392. }
  68393. if (callback) {
  68394. this._onActivateObserver = this.onActivateObservable.add(callback);
  68395. }
  68396. },
  68397. enumerable: true,
  68398. configurable: true
  68399. });
  68400. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  68401. /**
  68402. * A function that is added to the onSizeChangedObservable
  68403. */
  68404. set: function (callback) {
  68405. if (this._onSizeChangedObserver) {
  68406. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  68407. }
  68408. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  68409. },
  68410. enumerable: true,
  68411. configurable: true
  68412. });
  68413. Object.defineProperty(PostProcess.prototype, "onApply", {
  68414. /**
  68415. * A function that is added to the onApplyObservable
  68416. */
  68417. set: function (callback) {
  68418. if (this._onApplyObserver) {
  68419. this.onApplyObservable.remove(this._onApplyObserver);
  68420. }
  68421. this._onApplyObserver = this.onApplyObservable.add(callback);
  68422. },
  68423. enumerable: true,
  68424. configurable: true
  68425. });
  68426. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  68427. /**
  68428. * A function that is added to the onBeforeRenderObservable
  68429. */
  68430. set: function (callback) {
  68431. if (this._onBeforeRenderObserver) {
  68432. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  68433. }
  68434. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  68435. },
  68436. enumerable: true,
  68437. configurable: true
  68438. });
  68439. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  68440. /**
  68441. * A function that is added to the onAfterRenderObservable
  68442. */
  68443. set: function (callback) {
  68444. if (this._onAfterRenderObserver) {
  68445. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  68446. }
  68447. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  68448. },
  68449. enumerable: true,
  68450. configurable: true
  68451. });
  68452. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  68453. /**
  68454. * 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
  68455. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  68456. */
  68457. get: function () {
  68458. return this._textures.data[this._currentRenderTextureInd];
  68459. },
  68460. set: function (value) {
  68461. this._forcedOutputTexture = value;
  68462. },
  68463. enumerable: true,
  68464. configurable: true
  68465. });
  68466. /**
  68467. * Gets the camera which post process is applied to.
  68468. * @returns The camera the post process is applied to.
  68469. */
  68470. PostProcess.prototype.getCamera = function () {
  68471. return this._camera;
  68472. };
  68473. Object.defineProperty(PostProcess.prototype, "texelSize", {
  68474. /**
  68475. * Gets the texel size of the postprocess.
  68476. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  68477. */
  68478. get: function () {
  68479. if (this._shareOutputWithPostProcess) {
  68480. return this._shareOutputWithPostProcess.texelSize;
  68481. }
  68482. if (this._forcedOutputTexture) {
  68483. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  68484. }
  68485. return this._texelSize;
  68486. },
  68487. enumerable: true,
  68488. configurable: true
  68489. });
  68490. /**
  68491. * Gets the engine which this post process belongs to.
  68492. * @returns The engine the post process was enabled with.
  68493. */
  68494. PostProcess.prototype.getEngine = function () {
  68495. return this._engine;
  68496. };
  68497. /**
  68498. * The effect that is created when initializing the post process.
  68499. * @returns The created effect corrisponding the the postprocess.
  68500. */
  68501. PostProcess.prototype.getEffect = function () {
  68502. return this._effect;
  68503. };
  68504. /**
  68505. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  68506. * @param postProcess The post process to share the output with.
  68507. * @returns This post process.
  68508. */
  68509. PostProcess.prototype.shareOutputWith = function (postProcess) {
  68510. this._disposeTextures();
  68511. this._shareOutputWithPostProcess = postProcess;
  68512. return this;
  68513. };
  68514. /**
  68515. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  68516. * This should be called if the post process that shares output with this post process is disabled/disposed.
  68517. */
  68518. PostProcess.prototype.useOwnOutput = function () {
  68519. if (this._textures.length == 0) {
  68520. this._textures = new BABYLON.SmartArray(2);
  68521. }
  68522. this._shareOutputWithPostProcess = null;
  68523. };
  68524. /**
  68525. * Updates the effect with the current post process compile time values and recompiles the shader.
  68526. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68527. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68528. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68529. * @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
  68530. * @param onCompiled Called when the shader has been compiled.
  68531. * @param onError Called if there is an error when compiling a shader.
  68532. */
  68533. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68534. if (defines === void 0) { defines = null; }
  68535. if (uniforms === void 0) { uniforms = null; }
  68536. if (samplers === void 0) { samplers = null; }
  68537. 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);
  68538. };
  68539. /**
  68540. * The post process is reusable if it can be used multiple times within one frame.
  68541. * @returns If the post process is reusable
  68542. */
  68543. PostProcess.prototype.isReusable = function () {
  68544. return this._reusable;
  68545. };
  68546. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  68547. PostProcess.prototype.markTextureDirty = function () {
  68548. this.width = -1;
  68549. };
  68550. /**
  68551. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  68552. * 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.
  68553. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  68554. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  68555. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  68556. * @returns The target texture that was bound to be written to.
  68557. */
  68558. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  68559. var _this = this;
  68560. if (sourceTexture === void 0) { sourceTexture = null; }
  68561. camera = camera || this._camera;
  68562. var scene = camera.getScene();
  68563. var engine = scene.getEngine();
  68564. var maxSize = engine.getCaps().maxTextureSize;
  68565. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  68566. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  68567. // 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
  68568. var webVRCamera = camera.parent;
  68569. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  68570. requiredWidth /= 2;
  68571. }
  68572. var desiredWidth = (this._options.width || requiredWidth);
  68573. var desiredHeight = this._options.height || requiredHeight;
  68574. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  68575. if (this.adaptScaleToCurrentViewport) {
  68576. var currentViewport = engine.currentViewport;
  68577. if (currentViewport) {
  68578. desiredWidth *= currentViewport.width;
  68579. desiredHeight *= currentViewport.height;
  68580. }
  68581. }
  68582. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  68583. if (!this._options.width) {
  68584. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  68585. }
  68586. if (!this._options.height) {
  68587. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  68588. }
  68589. }
  68590. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  68591. if (this._textures.length > 0) {
  68592. for (var i = 0; i < this._textures.length; i++) {
  68593. this._engine._releaseTexture(this._textures.data[i]);
  68594. }
  68595. this._textures.reset();
  68596. }
  68597. this.width = desiredWidth;
  68598. this.height = desiredHeight;
  68599. var textureSize = { width: this.width, height: this.height };
  68600. var textureOptions = {
  68601. generateMipMaps: false,
  68602. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  68603. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  68604. samplingMode: this.renderTargetSamplingMode,
  68605. type: this._textureType
  68606. };
  68607. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68608. if (this._reusable) {
  68609. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68610. }
  68611. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  68612. this.onSizeChangedObservable.notifyObservers(this);
  68613. }
  68614. this._textures.forEach(function (texture) {
  68615. if (texture.samples !== _this.samples) {
  68616. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  68617. }
  68618. });
  68619. }
  68620. var target;
  68621. if (this._shareOutputWithPostProcess) {
  68622. target = this._shareOutputWithPostProcess.inputTexture;
  68623. }
  68624. else if (this._forcedOutputTexture) {
  68625. target = this._forcedOutputTexture;
  68626. this.width = this._forcedOutputTexture.width;
  68627. this.height = this._forcedOutputTexture.height;
  68628. }
  68629. else {
  68630. target = this.inputTexture;
  68631. }
  68632. // Bind the input of this post process to be used as the output of the previous post process.
  68633. if (this.enablePixelPerfectMode) {
  68634. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  68635. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  68636. }
  68637. else {
  68638. this._scaleRatio.copyFromFloats(1, 1);
  68639. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  68640. }
  68641. this.onActivateObservable.notifyObservers(camera);
  68642. // Clear
  68643. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  68644. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  68645. }
  68646. if (this._reusable) {
  68647. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  68648. }
  68649. return target;
  68650. };
  68651. Object.defineProperty(PostProcess.prototype, "isSupported", {
  68652. /**
  68653. * If the post process is supported.
  68654. */
  68655. get: function () {
  68656. return this._effect.isSupported;
  68657. },
  68658. enumerable: true,
  68659. configurable: true
  68660. });
  68661. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  68662. /**
  68663. * The aspect ratio of the output texture.
  68664. */
  68665. get: function () {
  68666. if (this._shareOutputWithPostProcess) {
  68667. return this._shareOutputWithPostProcess.aspectRatio;
  68668. }
  68669. if (this._forcedOutputTexture) {
  68670. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  68671. }
  68672. return this.width / this.height;
  68673. },
  68674. enumerable: true,
  68675. configurable: true
  68676. });
  68677. /**
  68678. * Get a value indicating if the post-process is ready to be used
  68679. * @returns true if the post-process is ready (shader is compiled)
  68680. */
  68681. PostProcess.prototype.isReady = function () {
  68682. return this._effect && this._effect.isReady();
  68683. };
  68684. /**
  68685. * Binds all textures and uniforms to the shader, this will be run on every pass.
  68686. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  68687. */
  68688. PostProcess.prototype.apply = function () {
  68689. // Check
  68690. if (!this._effect || !this._effect.isReady())
  68691. return null;
  68692. // States
  68693. this._engine.enableEffect(this._effect);
  68694. this._engine.setState(false);
  68695. this._engine.setDepthBuffer(false);
  68696. this._engine.setDepthWrite(false);
  68697. // Alpha
  68698. this._engine.setAlphaMode(this.alphaMode);
  68699. if (this.alphaConstants) {
  68700. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  68701. }
  68702. // Bind the output texture of the preivous post process as the input to this post process.
  68703. var source;
  68704. if (this._shareOutputWithPostProcess) {
  68705. source = this._shareOutputWithPostProcess.inputTexture;
  68706. }
  68707. else if (this._forcedOutputTexture) {
  68708. source = this._forcedOutputTexture;
  68709. }
  68710. else {
  68711. source = this.inputTexture;
  68712. }
  68713. this._effect._bindTexture("textureSampler", source);
  68714. // Parameters
  68715. this._effect.setVector2("scale", this._scaleRatio);
  68716. this.onApplyObservable.notifyObservers(this._effect);
  68717. return this._effect;
  68718. };
  68719. PostProcess.prototype._disposeTextures = function () {
  68720. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  68721. return;
  68722. }
  68723. if (this._textures.length > 0) {
  68724. for (var i = 0; i < this._textures.length; i++) {
  68725. this._engine._releaseTexture(this._textures.data[i]);
  68726. }
  68727. }
  68728. this._textures.dispose();
  68729. };
  68730. /**
  68731. * Disposes the post process.
  68732. * @param camera The camera to dispose the post process on.
  68733. */
  68734. PostProcess.prototype.dispose = function (camera) {
  68735. camera = camera || this._camera;
  68736. this._disposeTextures();
  68737. if (this._scene) {
  68738. var index_1 = this._scene.postProcesses.indexOf(this);
  68739. if (index_1 !== -1) {
  68740. this._scene.postProcesses.splice(index_1, 1);
  68741. }
  68742. }
  68743. else {
  68744. var index_2 = this._engine.postProcesses.indexOf(this);
  68745. if (index_2 !== -1) {
  68746. this._engine.postProcesses.splice(index_2, 1);
  68747. }
  68748. }
  68749. if (!camera) {
  68750. return;
  68751. }
  68752. camera.detachPostProcess(this);
  68753. var index = camera._postProcesses.indexOf(this);
  68754. if (index === 0 && camera._postProcesses.length > 0) {
  68755. var firstPostProcess = this._camera._getFirstPostProcess();
  68756. if (firstPostProcess) {
  68757. firstPostProcess.markTextureDirty();
  68758. }
  68759. }
  68760. this.onActivateObservable.clear();
  68761. this.onAfterRenderObservable.clear();
  68762. this.onApplyObservable.clear();
  68763. this.onBeforeRenderObservable.clear();
  68764. this.onSizeChangedObservable.clear();
  68765. };
  68766. return PostProcess;
  68767. }());
  68768. BABYLON.PostProcess = PostProcess;
  68769. })(BABYLON || (BABYLON = {}));
  68770. //# sourceMappingURL=babylon.postProcess.js.map
  68771. var BABYLON;
  68772. (function (BABYLON) {
  68773. var PassPostProcess = /** @class */ (function (_super) {
  68774. __extends(PassPostProcess, _super);
  68775. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68776. if (camera === void 0) { camera = null; }
  68777. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68778. if (blockCompilation === void 0) { blockCompilation = false; }
  68779. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  68780. }
  68781. return PassPostProcess;
  68782. }(BABYLON.PostProcess));
  68783. BABYLON.PassPostProcess = PassPostProcess;
  68784. })(BABYLON || (BABYLON = {}));
  68785. //# sourceMappingURL=babylon.passPostProcess.js.map
  68786. var __assign = (this && this.__assign) || function () {
  68787. __assign = Object.assign || function(t) {
  68788. for (var s, i = 1, n = arguments.length; i < n; i++) {
  68789. s = arguments[i];
  68790. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  68791. t[p] = s[p];
  68792. }
  68793. return t;
  68794. };
  68795. return __assign.apply(this, arguments);
  68796. };
  68797. var BABYLON;
  68798. (function (BABYLON) {
  68799. /**
  68800. * Default implementation IShadowGenerator.
  68801. * This is the main object responsible of generating shadows in the framework.
  68802. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  68803. */
  68804. var ShadowGenerator = /** @class */ (function () {
  68805. /**
  68806. * Creates a ShadowGenerator object.
  68807. * A ShadowGenerator is the required tool to use the shadows.
  68808. * Each light casting shadows needs to use its own ShadowGenerator.
  68809. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  68810. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  68811. * @param light The light object generating the shadows.
  68812. * @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.
  68813. */
  68814. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  68815. this._bias = 0.00005;
  68816. this._normalBias = 0;
  68817. this._blurBoxOffset = 1;
  68818. this._blurScale = 2;
  68819. this._blurKernel = 1;
  68820. this._useKernelBlur = false;
  68821. this._filter = ShadowGenerator.FILTER_NONE;
  68822. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  68823. this._contactHardeningLightSizeUVRatio = 0.1;
  68824. this._darkness = 0;
  68825. this._transparencyShadow = false;
  68826. /**
  68827. * Controls the extent to which the shadows fade out at the edge of the frustum
  68828. * Used only by directionals and spots
  68829. */
  68830. this.frustumEdgeFalloff = 0;
  68831. /**
  68832. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  68833. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  68834. * It might on the other hand introduce peter panning.
  68835. */
  68836. this.forceBackFacesOnly = false;
  68837. this._lightDirection = BABYLON.Vector3.Zero();
  68838. this._viewMatrix = BABYLON.Matrix.Zero();
  68839. this._projectionMatrix = BABYLON.Matrix.Zero();
  68840. this._transformMatrix = BABYLON.Matrix.Zero();
  68841. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68842. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68843. this._currentFaceIndex = 0;
  68844. this._currentFaceIndexCache = 0;
  68845. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  68846. this._mapSize = mapSize;
  68847. this._light = light;
  68848. this._scene = light.getScene();
  68849. light._shadowGenerator = this;
  68850. // Texture type fallback from float to int if not supported.
  68851. var caps = this._scene.getEngine().getCaps();
  68852. if (!useFullFloatFirst) {
  68853. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  68854. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68855. }
  68856. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  68857. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68858. }
  68859. else {
  68860. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68861. }
  68862. }
  68863. else {
  68864. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  68865. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68866. }
  68867. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  68868. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68869. }
  68870. else {
  68871. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68872. }
  68873. }
  68874. this._initializeGenerator();
  68875. this._applyFilterValues();
  68876. }
  68877. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  68878. /**
  68879. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  68880. */
  68881. get: function () {
  68882. return this._bias;
  68883. },
  68884. /**
  68885. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  68886. */
  68887. set: function (bias) {
  68888. this._bias = bias;
  68889. },
  68890. enumerable: true,
  68891. configurable: true
  68892. });
  68893. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  68894. /**
  68895. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68896. */
  68897. get: function () {
  68898. return this._normalBias;
  68899. },
  68900. /**
  68901. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68902. */
  68903. set: function (normalBias) {
  68904. this._normalBias = normalBias;
  68905. },
  68906. enumerable: true,
  68907. configurable: true
  68908. });
  68909. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  68910. /**
  68911. * Gets the blur box offset: offset applied during the blur pass.
  68912. * Only usefull if useKernelBlur = false
  68913. */
  68914. get: function () {
  68915. return this._blurBoxOffset;
  68916. },
  68917. /**
  68918. * Sets the blur box offset: offset applied during the blur pass.
  68919. * Only usefull if useKernelBlur = false
  68920. */
  68921. set: function (value) {
  68922. if (this._blurBoxOffset === value) {
  68923. return;
  68924. }
  68925. this._blurBoxOffset = value;
  68926. this._disposeBlurPostProcesses();
  68927. },
  68928. enumerable: true,
  68929. configurable: true
  68930. });
  68931. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  68932. /**
  68933. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  68934. * 2 means half of the size.
  68935. */
  68936. get: function () {
  68937. return this._blurScale;
  68938. },
  68939. /**
  68940. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  68941. * 2 means half of the size.
  68942. */
  68943. set: function (value) {
  68944. if (this._blurScale === value) {
  68945. return;
  68946. }
  68947. this._blurScale = value;
  68948. this._disposeBlurPostProcesses();
  68949. },
  68950. enumerable: true,
  68951. configurable: true
  68952. });
  68953. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  68954. /**
  68955. * Gets the blur kernel: kernel size of the blur pass.
  68956. * Only usefull if useKernelBlur = true
  68957. */
  68958. get: function () {
  68959. return this._blurKernel;
  68960. },
  68961. /**
  68962. * Sets the blur kernel: kernel size of the blur pass.
  68963. * Only usefull if useKernelBlur = true
  68964. */
  68965. set: function (value) {
  68966. if (this._blurKernel === value) {
  68967. return;
  68968. }
  68969. this._blurKernel = value;
  68970. this._disposeBlurPostProcesses();
  68971. },
  68972. enumerable: true,
  68973. configurable: true
  68974. });
  68975. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  68976. /**
  68977. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  68978. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  68979. */
  68980. get: function () {
  68981. return this._useKernelBlur;
  68982. },
  68983. /**
  68984. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  68985. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  68986. */
  68987. set: function (value) {
  68988. if (this._useKernelBlur === value) {
  68989. return;
  68990. }
  68991. this._useKernelBlur = value;
  68992. this._disposeBlurPostProcesses();
  68993. },
  68994. enumerable: true,
  68995. configurable: true
  68996. });
  68997. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  68998. /**
  68999. * Gets the depth scale used in ESM mode.
  69000. */
  69001. get: function () {
  69002. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  69003. },
  69004. /**
  69005. * Sets the depth scale used in ESM mode.
  69006. * This can override the scale stored on the light.
  69007. */
  69008. set: function (value) {
  69009. this._depthScale = value;
  69010. },
  69011. enumerable: true,
  69012. configurable: true
  69013. });
  69014. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  69015. /**
  69016. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  69017. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69018. */
  69019. get: function () {
  69020. return this._filter;
  69021. },
  69022. /**
  69023. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  69024. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69025. */
  69026. set: function (value) {
  69027. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  69028. if (this._light.needCube()) {
  69029. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69030. this.useExponentialShadowMap = true;
  69031. return;
  69032. }
  69033. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69034. this.useCloseExponentialShadowMap = true;
  69035. return;
  69036. }
  69037. // PCF on cubemap would also be expensive
  69038. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69039. this.usePoissonSampling = true;
  69040. return;
  69041. }
  69042. }
  69043. // Weblg1 fallback for PCF.
  69044. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69045. if (this._scene.getEngine().webGLVersion === 1) {
  69046. this.usePoissonSampling = true;
  69047. return;
  69048. }
  69049. }
  69050. if (this._filter === value) {
  69051. return;
  69052. }
  69053. this._filter = value;
  69054. this._disposeBlurPostProcesses();
  69055. this._applyFilterValues();
  69056. this._light._markMeshesAsLightDirty();
  69057. },
  69058. enumerable: true,
  69059. configurable: true
  69060. });
  69061. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  69062. /**
  69063. * Gets if the current filter is set to Poisson Sampling.
  69064. */
  69065. get: function () {
  69066. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  69067. },
  69068. /**
  69069. * Sets the current filter to Poisson Sampling.
  69070. */
  69071. set: function (value) {
  69072. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  69073. return;
  69074. }
  69075. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  69076. },
  69077. enumerable: true,
  69078. configurable: true
  69079. });
  69080. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  69081. /**
  69082. * Gets if the current filter is set to VSM.
  69083. * DEPRECATED. Should use useExponentialShadowMap instead.
  69084. */
  69085. get: function () {
  69086. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  69087. return this.useExponentialShadowMap;
  69088. },
  69089. /**
  69090. * Sets the current filter is to VSM.
  69091. * DEPRECATED. Should use useExponentialShadowMap instead.
  69092. */
  69093. set: function (value) {
  69094. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  69095. this.useExponentialShadowMap = value;
  69096. },
  69097. enumerable: true,
  69098. configurable: true
  69099. });
  69100. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  69101. /**
  69102. * Gets if the current filter is set to blurred VSM.
  69103. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  69104. */
  69105. get: function () {
  69106. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  69107. return this.useBlurExponentialShadowMap;
  69108. },
  69109. /**
  69110. * Sets the current filter is to blurred VSM.
  69111. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  69112. */
  69113. set: function (value) {
  69114. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  69115. this.useBlurExponentialShadowMap = value;
  69116. },
  69117. enumerable: true,
  69118. configurable: true
  69119. });
  69120. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  69121. /**
  69122. * Gets if the current filter is set to ESM.
  69123. */
  69124. get: function () {
  69125. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  69126. },
  69127. /**
  69128. * Sets the current filter is to ESM.
  69129. */
  69130. set: function (value) {
  69131. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  69132. return;
  69133. }
  69134. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69135. },
  69136. enumerable: true,
  69137. configurable: true
  69138. });
  69139. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  69140. /**
  69141. * Gets if the current filter is set to filtered ESM.
  69142. */
  69143. get: function () {
  69144. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  69145. },
  69146. /**
  69147. * Gets if the current filter is set to filtered ESM.
  69148. */
  69149. set: function (value) {
  69150. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69151. return;
  69152. }
  69153. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69154. },
  69155. enumerable: true,
  69156. configurable: true
  69157. });
  69158. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  69159. /**
  69160. * Gets if the current filter is set to "close ESM" (using the inverse of the
  69161. * exponential to prevent steep falloff artifacts).
  69162. */
  69163. get: function () {
  69164. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  69165. },
  69166. /**
  69167. * Sets the current filter to "close ESM" (using the inverse of the
  69168. * exponential to prevent steep falloff artifacts).
  69169. */
  69170. set: function (value) {
  69171. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  69172. return;
  69173. }
  69174. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69175. },
  69176. enumerable: true,
  69177. configurable: true
  69178. });
  69179. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  69180. /**
  69181. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  69182. * exponential to prevent steep falloff artifacts).
  69183. */
  69184. get: function () {
  69185. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  69186. },
  69187. /**
  69188. * Sets the current filter to filtered "close ESM" (using the inverse of the
  69189. * exponential to prevent steep falloff artifacts).
  69190. */
  69191. set: function (value) {
  69192. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69193. return;
  69194. }
  69195. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69196. },
  69197. enumerable: true,
  69198. configurable: true
  69199. });
  69200. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  69201. /**
  69202. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  69203. */
  69204. get: function () {
  69205. return this.filter === ShadowGenerator.FILTER_PCF;
  69206. },
  69207. /**
  69208. * Sets the current filter to "PCF" (percentage closer filtering).
  69209. */
  69210. set: function (value) {
  69211. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  69212. return;
  69213. }
  69214. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  69215. },
  69216. enumerable: true,
  69217. configurable: true
  69218. });
  69219. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  69220. /**
  69221. * Gets the PCF or PCSS Quality.
  69222. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69223. */
  69224. get: function () {
  69225. return this._filteringQuality;
  69226. },
  69227. /**
  69228. * Sets the PCF or PCSS Quality.
  69229. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69230. */
  69231. set: function (filteringQuality) {
  69232. this._filteringQuality = filteringQuality;
  69233. },
  69234. enumerable: true,
  69235. configurable: true
  69236. });
  69237. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  69238. /**
  69239. * Gets if the current filter is set to "PCSS" (contact hardening).
  69240. */
  69241. get: function () {
  69242. return this.filter === ShadowGenerator.FILTER_PCSS;
  69243. },
  69244. /**
  69245. * Sets the current filter to "PCSS" (contact hardening).
  69246. */
  69247. set: function (value) {
  69248. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  69249. return;
  69250. }
  69251. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  69252. },
  69253. enumerable: true,
  69254. configurable: true
  69255. });
  69256. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  69257. /**
  69258. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69259. * Using a ratio helps keeping shape stability independently of the map size.
  69260. *
  69261. * It does not account for the light projection as it was having too much
  69262. * instability during the light setup or during light position changes.
  69263. *
  69264. * Only valid if useContactHardeningShadow is true.
  69265. */
  69266. get: function () {
  69267. return this._contactHardeningLightSizeUVRatio;
  69268. },
  69269. /**
  69270. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69271. * Using a ratio helps keeping shape stability independently of the map size.
  69272. *
  69273. * It does not account for the light projection as it was having too much
  69274. * instability during the light setup or during light position changes.
  69275. *
  69276. * Only valid if useContactHardeningShadow is true.
  69277. */
  69278. set: function (contactHardeningLightSizeUVRatio) {
  69279. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  69280. },
  69281. enumerable: true,
  69282. configurable: true
  69283. });
  69284. /**
  69285. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  69286. * 0 means strongest and 1 would means no shadow.
  69287. * @returns the darkness.
  69288. */
  69289. ShadowGenerator.prototype.getDarkness = function () {
  69290. return this._darkness;
  69291. };
  69292. /**
  69293. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  69294. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  69295. * @returns the shadow generator allowing fluent coding.
  69296. */
  69297. ShadowGenerator.prototype.setDarkness = function (darkness) {
  69298. if (darkness >= 1.0)
  69299. this._darkness = 1.0;
  69300. else if (darkness <= 0.0)
  69301. this._darkness = 0.0;
  69302. else
  69303. this._darkness = darkness;
  69304. return this;
  69305. };
  69306. /**
  69307. * Sets the ability to have transparent shadow (boolean).
  69308. * @param transparent True if transparent else False
  69309. * @returns the shadow generator allowing fluent coding
  69310. */
  69311. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  69312. this._transparencyShadow = transparent;
  69313. return this;
  69314. };
  69315. /**
  69316. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  69317. * @returns The render target texture if present otherwise, null
  69318. */
  69319. ShadowGenerator.prototype.getShadowMap = function () {
  69320. return this._shadowMap;
  69321. };
  69322. /**
  69323. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  69324. * @returns The render target texture if the shadow map is present otherwise, null
  69325. */
  69326. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  69327. if (this._shadowMap2) {
  69328. return this._shadowMap2;
  69329. }
  69330. return this._shadowMap;
  69331. };
  69332. /**
  69333. * Helper function to add a mesh and its descendants to the list of shadow casters.
  69334. * @param mesh Mesh to add
  69335. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  69336. * @returns the Shadow Generator itself
  69337. */
  69338. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  69339. if (includeDescendants === void 0) { includeDescendants = true; }
  69340. var _a;
  69341. if (!this._shadowMap) {
  69342. return this;
  69343. }
  69344. if (!this._shadowMap.renderList) {
  69345. this._shadowMap.renderList = [];
  69346. }
  69347. this._shadowMap.renderList.push(mesh);
  69348. if (includeDescendants) {
  69349. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  69350. }
  69351. return this;
  69352. };
  69353. /**
  69354. * Helper function to remove a mesh and its descendants from the list of shadow casters
  69355. * @param mesh Mesh to remove
  69356. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  69357. * @returns the Shadow Generator itself
  69358. */
  69359. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  69360. if (includeDescendants === void 0) { includeDescendants = true; }
  69361. if (!this._shadowMap || !this._shadowMap.renderList) {
  69362. return this;
  69363. }
  69364. var index = this._shadowMap.renderList.indexOf(mesh);
  69365. if (index !== -1) {
  69366. this._shadowMap.renderList.splice(index, 1);
  69367. }
  69368. if (includeDescendants) {
  69369. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  69370. var child = _a[_i];
  69371. this.removeShadowCaster(child);
  69372. }
  69373. }
  69374. return this;
  69375. };
  69376. /**
  69377. * Returns the associated light object.
  69378. * @returns the light generating the shadow
  69379. */
  69380. ShadowGenerator.prototype.getLight = function () {
  69381. return this._light;
  69382. };
  69383. ShadowGenerator.prototype._initializeGenerator = function () {
  69384. this._light._markMeshesAsLightDirty();
  69385. this._initializeShadowMap();
  69386. };
  69387. ShadowGenerator.prototype._initializeShadowMap = function () {
  69388. var _this = this;
  69389. // Render target
  69390. var engine = this._scene.getEngine();
  69391. if (engine.webGLVersion > 1) {
  69392. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  69393. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  69394. }
  69395. else {
  69396. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  69397. }
  69398. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69399. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69400. this._shadowMap.anisotropicFilteringLevel = 1;
  69401. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69402. this._shadowMap.renderParticles = false;
  69403. this._shadowMap.ignoreCameraViewport = true;
  69404. // Record Face Index before render.
  69405. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  69406. _this._currentFaceIndex = faceIndex;
  69407. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69408. engine.setColorWrite(false);
  69409. }
  69410. });
  69411. // Custom render function.
  69412. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  69413. // Blur if required afer render.
  69414. this._shadowMap.onAfterUnbindObservable.add(function () {
  69415. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69416. engine.setColorWrite(true);
  69417. }
  69418. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  69419. return;
  69420. }
  69421. var shadowMap = _this.getShadowMapForRendering();
  69422. if (shadowMap) {
  69423. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  69424. }
  69425. });
  69426. // Clear according to the chosen filter.
  69427. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  69428. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  69429. this._shadowMap.onClearObservable.add(function (engine) {
  69430. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69431. engine.clear(clearOne, false, true, false);
  69432. }
  69433. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  69434. engine.clear(clearZero, true, true, false);
  69435. }
  69436. else {
  69437. engine.clear(clearOne, true, true, false);
  69438. }
  69439. });
  69440. };
  69441. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  69442. var _this = this;
  69443. var engine = this._scene.getEngine();
  69444. var targetSize = this._mapSize / this.blurScale;
  69445. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  69446. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  69447. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69448. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69449. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69450. }
  69451. if (this.useKernelBlur) {
  69452. 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);
  69453. this._kernelBlurXPostprocess.width = targetSize;
  69454. this._kernelBlurXPostprocess.height = targetSize;
  69455. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  69456. effect.setTexture("textureSampler", _this._shadowMap);
  69457. });
  69458. 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);
  69459. this._kernelBlurXPostprocess.autoClear = false;
  69460. this._kernelBlurYPostprocess.autoClear = false;
  69461. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69462. this._kernelBlurXPostprocess.packedFloat = true;
  69463. this._kernelBlurYPostprocess.packedFloat = true;
  69464. }
  69465. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  69466. }
  69467. else {
  69468. 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);
  69469. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  69470. effect.setFloat2("screenSize", targetSize, targetSize);
  69471. effect.setTexture("textureSampler", _this._shadowMap);
  69472. });
  69473. this._boxBlurPostprocess.autoClear = false;
  69474. this._blurPostProcesses = [this._boxBlurPostprocess];
  69475. }
  69476. };
  69477. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69478. var index;
  69479. var engine = this._scene.getEngine();
  69480. if (depthOnlySubMeshes.length) {
  69481. engine.setColorWrite(false);
  69482. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69483. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  69484. }
  69485. engine.setColorWrite(true);
  69486. }
  69487. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69488. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  69489. }
  69490. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69491. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  69492. }
  69493. if (this._transparencyShadow) {
  69494. for (index = 0; index < transparentSubMeshes.length; index++) {
  69495. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  69496. }
  69497. }
  69498. };
  69499. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  69500. var _this = this;
  69501. var mesh = subMesh.getRenderingMesh();
  69502. var scene = this._scene;
  69503. var engine = scene.getEngine();
  69504. var material = subMesh.getMaterial();
  69505. if (!material) {
  69506. return;
  69507. }
  69508. // Culling
  69509. engine.setState(material.backFaceCulling);
  69510. // Managing instances
  69511. var batch = mesh._getInstancesRenderList(subMesh._id);
  69512. if (batch.mustReturn) {
  69513. return;
  69514. }
  69515. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69516. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  69517. engine.enableEffect(this._effect);
  69518. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  69519. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  69520. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  69521. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69522. this._effect.setVector3("lightData", this._cachedDirection);
  69523. }
  69524. else {
  69525. this._effect.setVector3("lightData", this._cachedPosition);
  69526. }
  69527. if (scene.activeCamera) {
  69528. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  69529. }
  69530. // Alpha test
  69531. if (material && material.needAlphaTesting()) {
  69532. var alphaTexture = material.getAlphaTestTexture();
  69533. if (alphaTexture) {
  69534. this._effect.setTexture("diffuseSampler", alphaTexture);
  69535. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  69536. }
  69537. }
  69538. // Bones
  69539. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69540. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  69541. }
  69542. // Morph targets
  69543. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  69544. if (this.forceBackFacesOnly) {
  69545. engine.setState(true, 0, false, true);
  69546. }
  69547. // Draw
  69548. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69549. if (this.forceBackFacesOnly) {
  69550. engine.setState(true, 0, false, false);
  69551. }
  69552. }
  69553. else {
  69554. // Need to reset refresh rate of the shadowMap
  69555. if (this._shadowMap) {
  69556. this._shadowMap.resetRefreshCounter();
  69557. }
  69558. }
  69559. };
  69560. ShadowGenerator.prototype._applyFilterValues = function () {
  69561. if (!this._shadowMap) {
  69562. return;
  69563. }
  69564. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  69565. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  69566. }
  69567. else {
  69568. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69569. }
  69570. };
  69571. /**
  69572. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69573. * @param onCompiled Callback triggered at the and of the effects compilation
  69574. * @param options Sets of optional options forcing the compilation with different modes
  69575. */
  69576. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  69577. var _this = this;
  69578. var localOptions = __assign({ useInstances: false }, options);
  69579. var shadowMap = this.getShadowMap();
  69580. if (!shadowMap) {
  69581. if (onCompiled) {
  69582. onCompiled(this);
  69583. }
  69584. return;
  69585. }
  69586. var renderList = shadowMap.renderList;
  69587. if (!renderList) {
  69588. if (onCompiled) {
  69589. onCompiled(this);
  69590. }
  69591. return;
  69592. }
  69593. var subMeshes = new Array();
  69594. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  69595. var mesh = renderList_1[_i];
  69596. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  69597. }
  69598. if (subMeshes.length === 0) {
  69599. if (onCompiled) {
  69600. onCompiled(this);
  69601. }
  69602. return;
  69603. }
  69604. var currentIndex = 0;
  69605. var checkReady = function () {
  69606. if (!_this._scene || !_this._scene.getEngine()) {
  69607. return;
  69608. }
  69609. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  69610. currentIndex++;
  69611. if (currentIndex >= subMeshes.length) {
  69612. if (onCompiled) {
  69613. onCompiled(_this);
  69614. }
  69615. return;
  69616. }
  69617. }
  69618. setTimeout(checkReady, 16);
  69619. };
  69620. checkReady();
  69621. };
  69622. /**
  69623. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69624. * @param options Sets of optional options forcing the compilation with different modes
  69625. * @returns A promise that resolves when the compilation completes
  69626. */
  69627. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  69628. var _this = this;
  69629. return new Promise(function (resolve) {
  69630. _this.forceCompilation(function () {
  69631. resolve();
  69632. }, options);
  69633. });
  69634. };
  69635. /**
  69636. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  69637. * @param subMesh The submesh we want to render in the shadow map
  69638. * @param useInstances Defines wether will draw in the map using instances
  69639. * @returns true if ready otherwise, false
  69640. */
  69641. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  69642. var defines = [];
  69643. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69644. defines.push("#define FLOAT");
  69645. }
  69646. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69647. defines.push("#define ESM");
  69648. }
  69649. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  69650. defines.push("#define DEPTHTEXTURE");
  69651. }
  69652. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69653. var mesh = subMesh.getMesh();
  69654. var material = subMesh.getMaterial();
  69655. // Normal bias.
  69656. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  69657. attribs.push(BABYLON.VertexBuffer.NormalKind);
  69658. defines.push("#define NORMAL");
  69659. if (mesh.nonUniformScaling) {
  69660. defines.push("#define NONUNIFORMSCALING");
  69661. }
  69662. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69663. defines.push("#define DIRECTIONINLIGHTDATA");
  69664. }
  69665. }
  69666. // Alpha test
  69667. if (material && material.needAlphaTesting()) {
  69668. var alphaTexture = material.getAlphaTestTexture();
  69669. if (alphaTexture) {
  69670. defines.push("#define ALPHATEST");
  69671. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69672. attribs.push(BABYLON.VertexBuffer.UVKind);
  69673. defines.push("#define UV1");
  69674. }
  69675. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69676. if (alphaTexture.coordinatesIndex === 1) {
  69677. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69678. defines.push("#define UV2");
  69679. }
  69680. }
  69681. }
  69682. }
  69683. // Bones
  69684. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69685. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69686. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69687. if (mesh.numBoneInfluencers > 4) {
  69688. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69689. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69690. }
  69691. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69692. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69693. }
  69694. else {
  69695. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69696. }
  69697. // Morph targets
  69698. var manager = mesh.morphTargetManager;
  69699. var morphInfluencers = 0;
  69700. if (manager) {
  69701. if (manager.numInfluencers > 0) {
  69702. defines.push("#define MORPHTARGETS");
  69703. morphInfluencers = manager.numInfluencers;
  69704. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  69705. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  69706. }
  69707. }
  69708. // Instances
  69709. if (useInstances) {
  69710. defines.push("#define INSTANCES");
  69711. attribs.push("world0");
  69712. attribs.push("world1");
  69713. attribs.push("world2");
  69714. attribs.push("world3");
  69715. }
  69716. // Get correct effect
  69717. var join = defines.join("\n");
  69718. if (this._cachedDefines !== join) {
  69719. this._cachedDefines = join;
  69720. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  69721. }
  69722. if (!this._effect.isReady()) {
  69723. return false;
  69724. }
  69725. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69726. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  69727. this._initializeBlurRTTAndPostProcesses();
  69728. }
  69729. }
  69730. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  69731. return false;
  69732. }
  69733. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  69734. return false;
  69735. }
  69736. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  69737. return false;
  69738. }
  69739. return true;
  69740. };
  69741. /**
  69742. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  69743. * @param defines Defines of the material we want to update
  69744. * @param lightIndex Index of the light in the enabled light list of the material
  69745. */
  69746. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  69747. var scene = this._scene;
  69748. var light = this._light;
  69749. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69750. return;
  69751. }
  69752. defines["SHADOW" + lightIndex] = true;
  69753. if (this.useContactHardeningShadow) {
  69754. defines["SHADOWPCSS" + lightIndex] = true;
  69755. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69756. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69757. }
  69758. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69759. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69760. }
  69761. // else default to high.
  69762. }
  69763. if (this.usePercentageCloserFiltering) {
  69764. defines["SHADOWPCF" + lightIndex] = true;
  69765. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69766. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69767. }
  69768. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69769. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69770. }
  69771. // else default to high.
  69772. }
  69773. else if (this.usePoissonSampling) {
  69774. defines["SHADOWPOISSON" + lightIndex] = true;
  69775. }
  69776. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69777. defines["SHADOWESM" + lightIndex] = true;
  69778. }
  69779. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69780. defines["SHADOWCLOSEESM" + lightIndex] = true;
  69781. }
  69782. if (light.needCube()) {
  69783. defines["SHADOWCUBE" + lightIndex] = true;
  69784. }
  69785. };
  69786. /**
  69787. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  69788. * defined in the generator but impacting the effect).
  69789. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  69790. * @param effect The effect we are binfing the information for
  69791. */
  69792. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  69793. var light = this._light;
  69794. var scene = this._scene;
  69795. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69796. return;
  69797. }
  69798. var camera = scene.activeCamera;
  69799. if (!camera) {
  69800. return;
  69801. }
  69802. var shadowMap = this.getShadowMap();
  69803. if (!shadowMap) {
  69804. return;
  69805. }
  69806. if (!light.needCube()) {
  69807. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  69808. }
  69809. // Only PCF uses depth stencil texture.
  69810. if (this._filter === ShadowGenerator.FILTER_PCF) {
  69811. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69812. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  69813. }
  69814. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  69815. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69816. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  69817. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  69818. }
  69819. else {
  69820. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69821. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  69822. }
  69823. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  69824. };
  69825. /**
  69826. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  69827. * (eq to shadow prjection matrix * light transform matrix)
  69828. * @returns The transform matrix used to create the shadow map
  69829. */
  69830. ShadowGenerator.prototype.getTransformMatrix = function () {
  69831. var scene = this._scene;
  69832. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  69833. return this._transformMatrix;
  69834. }
  69835. this._currentRenderID = scene.getRenderId();
  69836. this._currentFaceIndexCache = this._currentFaceIndex;
  69837. var lightPosition = this._light.position;
  69838. if (this._light.computeTransformedInformation()) {
  69839. lightPosition = this._light.transformedPosition;
  69840. }
  69841. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  69842. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  69843. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  69844. }
  69845. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  69846. this._cachedPosition.copyFrom(lightPosition);
  69847. this._cachedDirection.copyFrom(this._lightDirection);
  69848. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  69849. var shadowMap = this.getShadowMap();
  69850. if (shadowMap) {
  69851. var renderList = shadowMap.renderList;
  69852. if (renderList) {
  69853. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  69854. }
  69855. }
  69856. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  69857. }
  69858. return this._transformMatrix;
  69859. };
  69860. /**
  69861. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  69862. * Cube and 2D textures for instance.
  69863. */
  69864. ShadowGenerator.prototype.recreateShadowMap = function () {
  69865. var shadowMap = this._shadowMap;
  69866. if (!shadowMap) {
  69867. return;
  69868. }
  69869. // Track render list.
  69870. var renderList = shadowMap.renderList;
  69871. // Clean up existing data.
  69872. this._disposeRTTandPostProcesses();
  69873. // Reinitializes.
  69874. this._initializeGenerator();
  69875. // Reaffect the filter to ensure a correct fallback if necessary.
  69876. this.filter = this.filter;
  69877. // Reaffect the filter.
  69878. this._applyFilterValues();
  69879. // Reaffect Render List.
  69880. this._shadowMap.renderList = renderList;
  69881. };
  69882. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  69883. if (this._shadowMap2) {
  69884. this._shadowMap2.dispose();
  69885. this._shadowMap2 = null;
  69886. }
  69887. if (this._boxBlurPostprocess) {
  69888. this._boxBlurPostprocess.dispose();
  69889. this._boxBlurPostprocess = null;
  69890. }
  69891. if (this._kernelBlurXPostprocess) {
  69892. this._kernelBlurXPostprocess.dispose();
  69893. this._kernelBlurXPostprocess = null;
  69894. }
  69895. if (this._kernelBlurYPostprocess) {
  69896. this._kernelBlurYPostprocess.dispose();
  69897. this._kernelBlurYPostprocess = null;
  69898. }
  69899. this._blurPostProcesses = [];
  69900. };
  69901. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  69902. if (this._shadowMap) {
  69903. this._shadowMap.dispose();
  69904. this._shadowMap = null;
  69905. }
  69906. this._disposeBlurPostProcesses();
  69907. };
  69908. /**
  69909. * Disposes the ShadowGenerator.
  69910. * Returns nothing.
  69911. */
  69912. ShadowGenerator.prototype.dispose = function () {
  69913. this._disposeRTTandPostProcesses();
  69914. if (this._light) {
  69915. this._light._shadowGenerator = null;
  69916. this._light._markMeshesAsLightDirty();
  69917. }
  69918. };
  69919. /**
  69920. * Serializes the shadow generator setup to a json object.
  69921. * @returns The serialized JSON object
  69922. */
  69923. ShadowGenerator.prototype.serialize = function () {
  69924. var serializationObject = {};
  69925. var shadowMap = this.getShadowMap();
  69926. if (!shadowMap) {
  69927. return serializationObject;
  69928. }
  69929. serializationObject.lightId = this._light.id;
  69930. serializationObject.mapSize = shadowMap.getRenderSize();
  69931. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  69932. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  69933. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  69934. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  69935. serializationObject.usePoissonSampling = this.usePoissonSampling;
  69936. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  69937. serializationObject.depthScale = this.depthScale;
  69938. serializationObject.darkness = this.getDarkness();
  69939. serializationObject.blurBoxOffset = this.blurBoxOffset;
  69940. serializationObject.blurKernel = this.blurKernel;
  69941. serializationObject.blurScale = this.blurScale;
  69942. serializationObject.useKernelBlur = this.useKernelBlur;
  69943. serializationObject.transparencyShadow = this._transparencyShadow;
  69944. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  69945. serializationObject.bias = this.bias;
  69946. serializationObject.normalBias = this.normalBias;
  69947. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  69948. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  69949. serializationObject.filteringQuality = this.filteringQuality;
  69950. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  69951. serializationObject.renderList = [];
  69952. if (shadowMap.renderList) {
  69953. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  69954. var mesh = shadowMap.renderList[meshIndex];
  69955. serializationObject.renderList.push(mesh.id);
  69956. }
  69957. }
  69958. return serializationObject;
  69959. };
  69960. /**
  69961. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  69962. * @param parsedShadowGenerator The JSON object to parse
  69963. * @param scene The scene to create the shadow map for
  69964. * @returns The parsed shadow generator
  69965. */
  69966. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  69967. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  69968. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  69969. var shadowMap = shadowGenerator.getShadowMap();
  69970. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  69971. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  69972. meshes.forEach(function (mesh) {
  69973. if (!shadowMap) {
  69974. return;
  69975. }
  69976. if (!shadowMap.renderList) {
  69977. shadowMap.renderList = [];
  69978. }
  69979. shadowMap.renderList.push(mesh);
  69980. });
  69981. }
  69982. if (parsedShadowGenerator.usePoissonSampling) {
  69983. shadowGenerator.usePoissonSampling = true;
  69984. }
  69985. else if (parsedShadowGenerator.useExponentialShadowMap) {
  69986. shadowGenerator.useExponentialShadowMap = true;
  69987. }
  69988. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  69989. shadowGenerator.useBlurExponentialShadowMap = true;
  69990. }
  69991. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  69992. shadowGenerator.useCloseExponentialShadowMap = true;
  69993. }
  69994. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  69995. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  69996. }
  69997. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  69998. shadowGenerator.usePercentageCloserFiltering = true;
  69999. }
  70000. else if (parsedShadowGenerator.useContactHardeningShadow) {
  70001. shadowGenerator.useContactHardeningShadow = true;
  70002. }
  70003. if (parsedShadowGenerator.filteringQuality) {
  70004. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  70005. }
  70006. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  70007. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  70008. }
  70009. // Backward compat
  70010. else if (parsedShadowGenerator.useVarianceShadowMap) {
  70011. shadowGenerator.useExponentialShadowMap = true;
  70012. }
  70013. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  70014. shadowGenerator.useBlurExponentialShadowMap = true;
  70015. }
  70016. if (parsedShadowGenerator.depthScale) {
  70017. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  70018. }
  70019. if (parsedShadowGenerator.blurScale) {
  70020. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  70021. }
  70022. if (parsedShadowGenerator.blurBoxOffset) {
  70023. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  70024. }
  70025. if (parsedShadowGenerator.useKernelBlur) {
  70026. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  70027. }
  70028. if (parsedShadowGenerator.blurKernel) {
  70029. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  70030. }
  70031. if (parsedShadowGenerator.bias !== undefined) {
  70032. shadowGenerator.bias = parsedShadowGenerator.bias;
  70033. }
  70034. if (parsedShadowGenerator.normalBias !== undefined) {
  70035. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  70036. }
  70037. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  70038. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  70039. }
  70040. if (parsedShadowGenerator.darkness) {
  70041. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  70042. }
  70043. if (parsedShadowGenerator.transparencyShadow) {
  70044. shadowGenerator.setTransparencyShadow(true);
  70045. }
  70046. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  70047. return shadowGenerator;
  70048. };
  70049. /**
  70050. * Shadow generator mode None: no filtering applied.
  70051. */
  70052. ShadowGenerator.FILTER_NONE = 0;
  70053. /**
  70054. * Shadow generator mode ESM: Exponential Shadow Mapping.
  70055. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70056. */
  70057. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  70058. /**
  70059. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  70060. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  70061. */
  70062. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  70063. /**
  70064. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  70065. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70066. */
  70067. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  70068. /**
  70069. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  70070. * edge artifacts on steep falloff.
  70071. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70072. */
  70073. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  70074. /**
  70075. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  70076. * edge artifacts on steep falloff.
  70077. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70078. */
  70079. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  70080. /**
  70081. * Shadow generator mode PCF: Percentage Closer Filtering
  70082. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  70083. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  70084. */
  70085. ShadowGenerator.FILTER_PCF = 6;
  70086. /**
  70087. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  70088. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  70089. * Contact Hardening
  70090. */
  70091. ShadowGenerator.FILTER_PCSS = 7;
  70092. /**
  70093. * Reserved for PCF and PCSS
  70094. * Highest Quality.
  70095. *
  70096. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  70097. *
  70098. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  70099. */
  70100. ShadowGenerator.QUALITY_HIGH = 0;
  70101. /**
  70102. * Reserved for PCF and PCSS
  70103. * Good tradeoff for quality/perf cross devices
  70104. *
  70105. * Execute PCF on a 3*3 kernel.
  70106. *
  70107. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  70108. */
  70109. ShadowGenerator.QUALITY_MEDIUM = 1;
  70110. /**
  70111. * Reserved for PCF and PCSS
  70112. * The lowest quality but the fastest.
  70113. *
  70114. * Execute PCF on a 1*1 kernel.
  70115. *
  70116. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  70117. */
  70118. ShadowGenerator.QUALITY_LOW = 2;
  70119. return ShadowGenerator;
  70120. }());
  70121. BABYLON.ShadowGenerator = ShadowGenerator;
  70122. })(BABYLON || (BABYLON = {}));
  70123. //# sourceMappingURL=babylon.shadowGenerator.js.map
  70124. var BABYLON;
  70125. (function (BABYLON) {
  70126. var DefaultLoadingScreen = /** @class */ (function () {
  70127. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  70128. if (_loadingText === void 0) { _loadingText = ""; }
  70129. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  70130. var _this = this;
  70131. this._renderingCanvas = _renderingCanvas;
  70132. this._loadingText = _loadingText;
  70133. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  70134. // Resize
  70135. this._resizeLoadingUI = function () {
  70136. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  70137. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  70138. if (!_this._loadingDiv) {
  70139. return;
  70140. }
  70141. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  70142. _this._loadingDiv.style.left = canvasRect.left + "px";
  70143. _this._loadingDiv.style.top = canvasRect.top + "px";
  70144. _this._loadingDiv.style.width = canvasRect.width + "px";
  70145. _this._loadingDiv.style.height = canvasRect.height + "px";
  70146. };
  70147. }
  70148. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  70149. if (this._loadingDiv) {
  70150. // Do not add a loading screen if there is already one
  70151. return;
  70152. }
  70153. this._loadingDiv = document.createElement("div");
  70154. this._loadingDiv.id = "babylonjsLoadingDiv";
  70155. this._loadingDiv.style.opacity = "0";
  70156. this._loadingDiv.style.transition = "opacity 1.5s ease";
  70157. this._loadingDiv.style.pointerEvents = "none";
  70158. // Loading text
  70159. this._loadingTextDiv = document.createElement("div");
  70160. this._loadingTextDiv.style.position = "absolute";
  70161. this._loadingTextDiv.style.left = "0";
  70162. this._loadingTextDiv.style.top = "50%";
  70163. this._loadingTextDiv.style.marginTop = "80px";
  70164. this._loadingTextDiv.style.width = "100%";
  70165. this._loadingTextDiv.style.height = "20px";
  70166. this._loadingTextDiv.style.fontFamily = "Arial";
  70167. this._loadingTextDiv.style.fontSize = "14px";
  70168. this._loadingTextDiv.style.color = "white";
  70169. this._loadingTextDiv.style.textAlign = "center";
  70170. this._loadingTextDiv.innerHTML = "Loading";
  70171. this._loadingDiv.appendChild(this._loadingTextDiv);
  70172. //set the predefined text
  70173. this._loadingTextDiv.innerHTML = this._loadingText;
  70174. // Generating keyframes
  70175. var style = document.createElement('style');
  70176. style.type = 'text/css';
  70177. 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 }";
  70178. style.innerHTML = keyFrames;
  70179. document.getElementsByTagName('head')[0].appendChild(style);
  70180. // Loading img
  70181. var imgBack = new Image();
  70182. 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";
  70183. imgBack.style.position = "absolute";
  70184. imgBack.style.left = "50%";
  70185. imgBack.style.top = "50%";
  70186. imgBack.style.marginLeft = "-60px";
  70187. imgBack.style.marginTop = "-60px";
  70188. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  70189. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  70190. imgBack.style.transformOrigin = "50% 50%";
  70191. imgBack.style.webkitTransformOrigin = "50% 50%";
  70192. this._loadingDiv.appendChild(imgBack);
  70193. this._resizeLoadingUI();
  70194. window.addEventListener("resize", this._resizeLoadingUI);
  70195. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70196. document.body.appendChild(this._loadingDiv);
  70197. this._loadingDiv.style.opacity = "1";
  70198. };
  70199. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  70200. var _this = this;
  70201. if (!this._loadingDiv) {
  70202. return;
  70203. }
  70204. var onTransitionEnd = function () {
  70205. if (!_this._loadingDiv) {
  70206. return;
  70207. }
  70208. document.body.removeChild(_this._loadingDiv);
  70209. window.removeEventListener("resize", _this._resizeLoadingUI);
  70210. _this._loadingDiv = null;
  70211. };
  70212. this._loadingDiv.style.opacity = "0";
  70213. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  70214. };
  70215. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  70216. set: function (text) {
  70217. this._loadingText = text;
  70218. if (this._loadingTextDiv) {
  70219. this._loadingTextDiv.innerHTML = this._loadingText;
  70220. }
  70221. },
  70222. enumerable: true,
  70223. configurable: true
  70224. });
  70225. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  70226. get: function () {
  70227. return this._loadingDivBackgroundColor;
  70228. },
  70229. set: function (color) {
  70230. this._loadingDivBackgroundColor = color;
  70231. if (!this._loadingDiv) {
  70232. return;
  70233. }
  70234. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70235. },
  70236. enumerable: true,
  70237. configurable: true
  70238. });
  70239. return DefaultLoadingScreen;
  70240. }());
  70241. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  70242. })(BABYLON || (BABYLON = {}));
  70243. //# sourceMappingURL=babylon.loadingScreen.js.map
  70244. var BABYLON;
  70245. (function (BABYLON) {
  70246. var SceneLoaderProgressEvent = /** @class */ (function () {
  70247. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  70248. this.lengthComputable = lengthComputable;
  70249. this.loaded = loaded;
  70250. this.total = total;
  70251. }
  70252. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  70253. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  70254. };
  70255. return SceneLoaderProgressEvent;
  70256. }());
  70257. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  70258. var SceneLoader = /** @class */ (function () {
  70259. function SceneLoader() {
  70260. }
  70261. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  70262. get: function () {
  70263. return 0;
  70264. },
  70265. enumerable: true,
  70266. configurable: true
  70267. });
  70268. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  70269. get: function () {
  70270. return 1;
  70271. },
  70272. enumerable: true,
  70273. configurable: true
  70274. });
  70275. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  70276. get: function () {
  70277. return 2;
  70278. },
  70279. enumerable: true,
  70280. configurable: true
  70281. });
  70282. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  70283. get: function () {
  70284. return 3;
  70285. },
  70286. enumerable: true,
  70287. configurable: true
  70288. });
  70289. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  70290. get: function () {
  70291. return SceneLoader._ForceFullSceneLoadingForIncremental;
  70292. },
  70293. set: function (value) {
  70294. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  70295. },
  70296. enumerable: true,
  70297. configurable: true
  70298. });
  70299. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  70300. get: function () {
  70301. return SceneLoader._ShowLoadingScreen;
  70302. },
  70303. set: function (value) {
  70304. SceneLoader._ShowLoadingScreen = value;
  70305. },
  70306. enumerable: true,
  70307. configurable: true
  70308. });
  70309. Object.defineProperty(SceneLoader, "loggingLevel", {
  70310. get: function () {
  70311. return SceneLoader._loggingLevel;
  70312. },
  70313. set: function (value) {
  70314. SceneLoader._loggingLevel = value;
  70315. },
  70316. enumerable: true,
  70317. configurable: true
  70318. });
  70319. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  70320. get: function () {
  70321. return SceneLoader._CleanBoneMatrixWeights;
  70322. },
  70323. set: function (value) {
  70324. SceneLoader._CleanBoneMatrixWeights = value;
  70325. },
  70326. enumerable: true,
  70327. configurable: true
  70328. });
  70329. SceneLoader._getDefaultPlugin = function () {
  70330. return SceneLoader._registeredPlugins[".babylon"];
  70331. };
  70332. SceneLoader._getPluginForExtension = function (extension) {
  70333. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  70334. if (registeredPlugin) {
  70335. return registeredPlugin;
  70336. }
  70337. 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");
  70338. return SceneLoader._getDefaultPlugin();
  70339. };
  70340. SceneLoader._getPluginForDirectLoad = function (data) {
  70341. for (var extension in SceneLoader._registeredPlugins) {
  70342. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  70343. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  70344. return SceneLoader._registeredPlugins[extension];
  70345. }
  70346. }
  70347. return SceneLoader._getDefaultPlugin();
  70348. };
  70349. SceneLoader._getPluginForFilename = function (sceneFilename) {
  70350. if (sceneFilename.name) {
  70351. sceneFilename = sceneFilename.name;
  70352. }
  70353. var queryStringPosition = sceneFilename.indexOf("?");
  70354. if (queryStringPosition !== -1) {
  70355. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  70356. }
  70357. var dotPosition = sceneFilename.lastIndexOf(".");
  70358. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  70359. return SceneLoader._getPluginForExtension(extension);
  70360. };
  70361. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  70362. SceneLoader._getDirectLoad = function (sceneFilename) {
  70363. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  70364. return sceneFilename.substr(5);
  70365. }
  70366. return null;
  70367. };
  70368. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  70369. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  70370. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  70371. var plugin;
  70372. if (registeredPlugin.plugin.createPlugin) {
  70373. plugin = registeredPlugin.plugin.createPlugin();
  70374. }
  70375. else {
  70376. plugin = registeredPlugin.plugin;
  70377. }
  70378. var useArrayBuffer = registeredPlugin.isBinary;
  70379. var database;
  70380. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  70381. var dataCallback = function (data, responseURL) {
  70382. if (scene.isDisposed) {
  70383. onError("Scene has been disposed");
  70384. return;
  70385. }
  70386. scene.database = database;
  70387. onSuccess(plugin, data, responseURL);
  70388. };
  70389. var request = null;
  70390. var pluginDisposed = false;
  70391. var onDisposeObservable = plugin.onDisposeObservable;
  70392. if (onDisposeObservable) {
  70393. onDisposeObservable.add(function () {
  70394. pluginDisposed = true;
  70395. if (request) {
  70396. request.abort();
  70397. request = null;
  70398. }
  70399. onDispose();
  70400. });
  70401. }
  70402. var manifestChecked = function () {
  70403. if (pluginDisposed) {
  70404. return;
  70405. }
  70406. var url = rootUrl + sceneFilename;
  70407. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  70408. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  70409. } : undefined, database, useArrayBuffer, function (request, exception) {
  70410. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  70411. });
  70412. };
  70413. if (directLoad) {
  70414. dataCallback(directLoad);
  70415. return plugin;
  70416. }
  70417. if (rootUrl.indexOf("file:") === -1) {
  70418. var engine = scene.getEngine();
  70419. var canUseOfflineSupport = engine.enableOfflineSupport;
  70420. if (canUseOfflineSupport) {
  70421. // Also check for exceptions
  70422. var exceptionFound = false;
  70423. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  70424. var regex = _a[_i];
  70425. if (regex.test(rootUrl + sceneFilename)) {
  70426. exceptionFound = true;
  70427. break;
  70428. }
  70429. }
  70430. canUseOfflineSupport = !exceptionFound;
  70431. }
  70432. if (canUseOfflineSupport) {
  70433. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  70434. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  70435. }
  70436. else {
  70437. manifestChecked();
  70438. }
  70439. }
  70440. // Loading file from disk via input file or drag'n'drop
  70441. else {
  70442. var fileOrString = sceneFilename;
  70443. if (fileOrString.name) { // File
  70444. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  70445. }
  70446. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  70447. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  70448. }
  70449. else {
  70450. onError("Unable to find file named " + sceneFilename);
  70451. }
  70452. }
  70453. return plugin;
  70454. };
  70455. // Public functions
  70456. SceneLoader.GetPluginForExtension = function (extension) {
  70457. return SceneLoader._getPluginForExtension(extension).plugin;
  70458. };
  70459. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  70460. return !!SceneLoader._registeredPlugins[extension];
  70461. };
  70462. SceneLoader.RegisterPlugin = function (plugin) {
  70463. if (typeof plugin.extensions === "string") {
  70464. var extension = plugin.extensions;
  70465. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  70466. plugin: plugin,
  70467. isBinary: false
  70468. };
  70469. }
  70470. else {
  70471. var extensions = plugin.extensions;
  70472. Object.keys(extensions).forEach(function (extension) {
  70473. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  70474. plugin: plugin,
  70475. isBinary: extensions[extension].isBinary
  70476. };
  70477. });
  70478. }
  70479. };
  70480. /**
  70481. * Import meshes into a scene
  70482. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70483. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70484. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70485. * @param scene the instance of BABYLON.Scene to append to
  70486. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  70487. * @param onProgress a callback with a progress event for each file being loaded
  70488. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70489. * @param pluginExtension the extension used to determine the plugin
  70490. * @returns The loaded plugin
  70491. */
  70492. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70493. if (sceneFilename === void 0) { sceneFilename = ""; }
  70494. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70495. if (onSuccess === void 0) { onSuccess = null; }
  70496. if (onProgress === void 0) { onProgress = null; }
  70497. if (onError === void 0) { onError = null; }
  70498. if (pluginExtension === void 0) { pluginExtension = null; }
  70499. if (!scene) {
  70500. BABYLON.Tools.Error("No scene available to import mesh to");
  70501. return null;
  70502. }
  70503. if (!sceneFilename) {
  70504. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70505. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70506. }
  70507. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70508. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70509. return null;
  70510. }
  70511. var loadingToken = {};
  70512. scene._addPendingData(loadingToken);
  70513. var disposeHandler = function () {
  70514. scene._removePendingData(loadingToken);
  70515. };
  70516. var errorHandler = function (message, exception) {
  70517. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  70518. if (onError) {
  70519. onError(scene, errorMessage, exception);
  70520. }
  70521. else {
  70522. BABYLON.Tools.Error(errorMessage);
  70523. // should the exception be thrown?
  70524. }
  70525. disposeHandler();
  70526. };
  70527. var progressHandler = onProgress ? function (event) {
  70528. try {
  70529. onProgress(event);
  70530. }
  70531. catch (e) {
  70532. errorHandler("Error in onProgress callback", e);
  70533. }
  70534. } : undefined;
  70535. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  70536. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  70537. if (onSuccess) {
  70538. try {
  70539. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  70540. }
  70541. catch (e) {
  70542. errorHandler("Error in onSuccess callback", e);
  70543. }
  70544. }
  70545. scene._removePendingData(loadingToken);
  70546. };
  70547. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70548. if (plugin.rewriteRootURL) {
  70549. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  70550. }
  70551. if (sceneFilename === "") {
  70552. if (sceneFilename === "") {
  70553. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70554. }
  70555. }
  70556. if (plugin.importMesh) {
  70557. var syncedPlugin = plugin;
  70558. var meshes = new Array();
  70559. var particleSystems = new Array();
  70560. var skeletons = new Array();
  70561. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  70562. return;
  70563. }
  70564. scene.loadingPluginName = plugin.name;
  70565. successHandler(meshes, particleSystems, skeletons, []);
  70566. }
  70567. else {
  70568. var asyncedPlugin = plugin;
  70569. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  70570. scene.loadingPluginName = plugin.name;
  70571. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  70572. }).catch(function (error) {
  70573. errorHandler(error.message, error);
  70574. });
  70575. }
  70576. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70577. };
  70578. /**
  70579. * Import meshes into a scene
  70580. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70581. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70582. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70583. * @param scene the instance of BABYLON.Scene to append to
  70584. * @param onProgress a callback with a progress event for each file being loaded
  70585. * @param pluginExtension the extension used to determine the plugin
  70586. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  70587. */
  70588. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70589. if (sceneFilename === void 0) { sceneFilename = ""; }
  70590. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70591. if (onProgress === void 0) { onProgress = null; }
  70592. if (pluginExtension === void 0) { pluginExtension = null; }
  70593. return new Promise(function (resolve, reject) {
  70594. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  70595. resolve({
  70596. meshes: meshes,
  70597. particleSystems: particleSystems,
  70598. skeletons: skeletons,
  70599. animationGroups: animationGroups
  70600. });
  70601. }, onProgress, function (scene, message, exception) {
  70602. reject(exception || new Error(message));
  70603. }, pluginExtension);
  70604. });
  70605. };
  70606. /**
  70607. * Load a scene
  70608. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70609. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70610. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70611. * @param onSuccess a callback with the scene when import succeeds
  70612. * @param onProgress a callback with a progress event for each file being loaded
  70613. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70614. * @param pluginExtension the extension used to determine the plugin
  70615. * @returns The loaded plugin
  70616. */
  70617. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  70618. if (onSuccess === void 0) { onSuccess = null; }
  70619. if (onProgress === void 0) { onProgress = null; }
  70620. if (onError === void 0) { onError = null; }
  70621. if (pluginExtension === void 0) { pluginExtension = null; }
  70622. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  70623. };
  70624. /**
  70625. * Load a scene
  70626. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70627. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70628. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70629. * @param onProgress a callback with a progress event for each file being loaded
  70630. * @param pluginExtension the extension used to determine the plugin
  70631. * @returns The loaded scene
  70632. */
  70633. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  70634. if (onProgress === void 0) { onProgress = null; }
  70635. if (pluginExtension === void 0) { pluginExtension = null; }
  70636. return new Promise(function (resolve, reject) {
  70637. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  70638. resolve(scene);
  70639. }, onProgress, function (scene, message, exception) {
  70640. reject(exception || new Error(message));
  70641. }, pluginExtension);
  70642. });
  70643. };
  70644. /**
  70645. * Append a scene
  70646. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70647. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70648. * @param scene is the instance of BABYLON.Scene to append to
  70649. * @param onSuccess a callback with the scene when import succeeds
  70650. * @param onProgress a callback with a progress event for each file being loaded
  70651. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70652. * @param pluginExtension the extension used to determine the plugin
  70653. * @returns The loaded plugin
  70654. */
  70655. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70656. if (sceneFilename === void 0) { sceneFilename = ""; }
  70657. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70658. if (onSuccess === void 0) { onSuccess = null; }
  70659. if (onProgress === void 0) { onProgress = null; }
  70660. if (onError === void 0) { onError = null; }
  70661. if (pluginExtension === void 0) { pluginExtension = null; }
  70662. if (!scene) {
  70663. BABYLON.Tools.Error("No scene available to append to");
  70664. return null;
  70665. }
  70666. if (!sceneFilename) {
  70667. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70668. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70669. }
  70670. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70671. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70672. return null;
  70673. }
  70674. if (SceneLoader.ShowLoadingScreen) {
  70675. scene.getEngine().displayLoadingUI();
  70676. }
  70677. var loadingToken = {};
  70678. scene._addPendingData(loadingToken);
  70679. var disposeHandler = function () {
  70680. scene._removePendingData(loadingToken);
  70681. scene.getEngine().hideLoadingUI();
  70682. };
  70683. var errorHandler = function (message, exception) {
  70684. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70685. if (onError) {
  70686. onError(scene, errorMessage, exception);
  70687. }
  70688. else {
  70689. BABYLON.Tools.Error(errorMessage);
  70690. // should the exception be thrown?
  70691. }
  70692. disposeHandler();
  70693. };
  70694. var progressHandler = onProgress ? function (event) {
  70695. try {
  70696. onProgress(event);
  70697. }
  70698. catch (e) {
  70699. errorHandler("Error in onProgress callback", e);
  70700. }
  70701. } : undefined;
  70702. var successHandler = function () {
  70703. if (onSuccess) {
  70704. try {
  70705. onSuccess(scene);
  70706. }
  70707. catch (e) {
  70708. errorHandler("Error in onSuccess callback", e);
  70709. }
  70710. }
  70711. scene._removePendingData(loadingToken);
  70712. };
  70713. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70714. if (sceneFilename === "") {
  70715. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70716. }
  70717. if (plugin.load) {
  70718. var syncedPlugin = plugin;
  70719. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  70720. return;
  70721. }
  70722. scene.loadingPluginName = plugin.name;
  70723. successHandler();
  70724. }
  70725. else {
  70726. var asyncedPlugin = plugin;
  70727. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  70728. scene.loadingPluginName = plugin.name;
  70729. successHandler();
  70730. }).catch(function (error) {
  70731. errorHandler(error.message, error);
  70732. });
  70733. }
  70734. if (SceneLoader.ShowLoadingScreen) {
  70735. scene.executeWhenReady(function () {
  70736. scene.getEngine().hideLoadingUI();
  70737. });
  70738. }
  70739. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70740. };
  70741. /**
  70742. * Append a scene
  70743. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70744. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70745. * @param scene is the instance of BABYLON.Scene to append to
  70746. * @param onProgress a callback with a progress event for each file being loaded
  70747. * @param pluginExtension the extension used to determine the plugin
  70748. * @returns The given scene
  70749. */
  70750. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70751. if (sceneFilename === void 0) { sceneFilename = ""; }
  70752. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70753. if (onProgress === void 0) { onProgress = null; }
  70754. if (pluginExtension === void 0) { pluginExtension = null; }
  70755. return new Promise(function (resolve, reject) {
  70756. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  70757. resolve(scene);
  70758. }, onProgress, function (scene, message, exception) {
  70759. reject(exception || new Error(message));
  70760. }, pluginExtension);
  70761. });
  70762. };
  70763. /**
  70764. * Load a scene into an asset container
  70765. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70766. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70767. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  70768. * @param onSuccess a callback with the scene when import succeeds
  70769. * @param onProgress a callback with a progress event for each file being loaded
  70770. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70771. * @param pluginExtension the extension used to determine the plugin
  70772. * @returns The loaded plugin
  70773. */
  70774. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70775. if (sceneFilename === void 0) { sceneFilename = ""; }
  70776. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70777. if (onSuccess === void 0) { onSuccess = null; }
  70778. if (onProgress === void 0) { onProgress = null; }
  70779. if (onError === void 0) { onError = null; }
  70780. if (pluginExtension === void 0) { pluginExtension = null; }
  70781. if (!scene) {
  70782. BABYLON.Tools.Error("No scene available to load asset container to");
  70783. return null;
  70784. }
  70785. if (!sceneFilename) {
  70786. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70787. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70788. }
  70789. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70790. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70791. return null;
  70792. }
  70793. var loadingToken = {};
  70794. scene._addPendingData(loadingToken);
  70795. var disposeHandler = function () {
  70796. scene._removePendingData(loadingToken);
  70797. };
  70798. var errorHandler = function (message, exception) {
  70799. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70800. if (onError) {
  70801. onError(scene, errorMessage, exception);
  70802. }
  70803. else {
  70804. BABYLON.Tools.Error(errorMessage);
  70805. // should the exception be thrown?
  70806. }
  70807. disposeHandler();
  70808. };
  70809. var progressHandler = onProgress ? function (event) {
  70810. try {
  70811. onProgress(event);
  70812. }
  70813. catch (e) {
  70814. errorHandler("Error in onProgress callback", e);
  70815. }
  70816. } : undefined;
  70817. var successHandler = function (assets) {
  70818. if (onSuccess) {
  70819. try {
  70820. onSuccess(assets);
  70821. }
  70822. catch (e) {
  70823. errorHandler("Error in onSuccess callback", e);
  70824. }
  70825. }
  70826. scene._removePendingData(loadingToken);
  70827. };
  70828. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70829. if (plugin.loadAssetContainer) {
  70830. var syncedPlugin = plugin;
  70831. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  70832. if (!assetContainer) {
  70833. return;
  70834. }
  70835. scene.loadingPluginName = plugin.name;
  70836. successHandler(assetContainer);
  70837. }
  70838. else if (plugin.loadAssetContainerAsync) {
  70839. var asyncedPlugin = plugin;
  70840. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  70841. scene.loadingPluginName = plugin.name;
  70842. successHandler(assetContainer);
  70843. }).catch(function (error) {
  70844. errorHandler(error.message, error);
  70845. });
  70846. }
  70847. else {
  70848. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  70849. }
  70850. if (SceneLoader.ShowLoadingScreen) {
  70851. scene.executeWhenReady(function () {
  70852. scene.getEngine().hideLoadingUI();
  70853. });
  70854. }
  70855. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70856. };
  70857. /**
  70858. * Load a scene into an asset container
  70859. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70860. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70861. * @param scene is the instance of BABYLON.Scene to append to
  70862. * @param onProgress a callback with a progress event for each file being loaded
  70863. * @param pluginExtension the extension used to determine the plugin
  70864. * @returns The loaded asset container
  70865. */
  70866. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70867. if (sceneFilename === void 0) { sceneFilename = ""; }
  70868. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70869. if (onProgress === void 0) { onProgress = null; }
  70870. if (pluginExtension === void 0) { pluginExtension = null; }
  70871. return new Promise(function (resolve, reject) {
  70872. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  70873. resolve(assetContainer);
  70874. }, onProgress, function (scene, message, exception) {
  70875. reject(exception || new Error(message));
  70876. }, pluginExtension);
  70877. });
  70878. };
  70879. // Flags
  70880. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  70881. SceneLoader._ShowLoadingScreen = true;
  70882. SceneLoader._CleanBoneMatrixWeights = false;
  70883. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  70884. // Members
  70885. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  70886. SceneLoader._registeredPlugins = {};
  70887. return SceneLoader;
  70888. }());
  70889. BABYLON.SceneLoader = SceneLoader;
  70890. ;
  70891. })(BABYLON || (BABYLON = {}));
  70892. //# sourceMappingURL=babylon.sceneLoader.js.map
  70893. var BABYLON;
  70894. (function (BABYLON) {
  70895. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  70896. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  70897. var parsedMaterial = parsedData.materials[index];
  70898. if (parsedMaterial.id === id) {
  70899. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  70900. }
  70901. }
  70902. return null;
  70903. };
  70904. var isDescendantOf = function (mesh, names, hierarchyIds) {
  70905. for (var i in names) {
  70906. if (mesh.name === names[i]) {
  70907. hierarchyIds.push(mesh.id);
  70908. return true;
  70909. }
  70910. }
  70911. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  70912. hierarchyIds.push(mesh.id);
  70913. return true;
  70914. }
  70915. return false;
  70916. };
  70917. var logOperation = function (operation, producer) {
  70918. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  70919. };
  70920. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  70921. if (addToScene === void 0) { addToScene = false; }
  70922. var container = new BABYLON.AssetContainer(scene);
  70923. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70924. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70925. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70926. // and avoid problems with multiple concurrent .babylon loads.
  70927. var log = "importScene has failed JSON parse";
  70928. try {
  70929. var parsedData = JSON.parse(data);
  70930. log = "";
  70931. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  70932. var index;
  70933. var cache;
  70934. // Lights
  70935. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  70936. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  70937. var parsedLight = parsedData.lights[index];
  70938. var light = BABYLON.Light.Parse(parsedLight, scene);
  70939. if (light) {
  70940. container.lights.push(light);
  70941. log += (index === 0 ? "\n\tLights:" : "");
  70942. log += "\n\t\t" + light.toString(fullDetails);
  70943. }
  70944. }
  70945. }
  70946. // Animations
  70947. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  70948. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  70949. var parsedAnimation = parsedData.animations[index];
  70950. var animation = BABYLON.Animation.Parse(parsedAnimation);
  70951. scene.animations.push(animation);
  70952. container.animations.push(animation);
  70953. log += (index === 0 ? "\n\tAnimations:" : "");
  70954. log += "\n\t\t" + animation.toString(fullDetails);
  70955. }
  70956. }
  70957. // Materials
  70958. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  70959. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  70960. var parsedMaterial = parsedData.materials[index];
  70961. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  70962. container.materials.push(mat);
  70963. log += (index === 0 ? "\n\tMaterials:" : "");
  70964. log += "\n\t\t" + mat.toString(fullDetails);
  70965. }
  70966. }
  70967. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  70968. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  70969. var parsedMultiMaterial = parsedData.multiMaterials[index];
  70970. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  70971. container.multiMaterials.push(mmat);
  70972. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  70973. log += "\n\t\t" + mmat.toString(fullDetails);
  70974. }
  70975. }
  70976. // Morph targets
  70977. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  70978. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  70979. var managerData = _a[_i];
  70980. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  70981. }
  70982. }
  70983. // Skeletons
  70984. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  70985. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  70986. var parsedSkeleton = parsedData.skeletons[index];
  70987. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  70988. container.skeletons.push(skeleton);
  70989. log += (index === 0 ? "\n\tSkeletons:" : "");
  70990. log += "\n\t\t" + skeleton.toString(fullDetails);
  70991. }
  70992. }
  70993. // Geometries
  70994. var geometries = parsedData.geometries;
  70995. if (geometries !== undefined && geometries !== null) {
  70996. var addedGeometry = new Array();
  70997. // Boxes
  70998. var boxes = geometries.boxes;
  70999. if (boxes !== undefined && boxes !== null) {
  71000. for (index = 0, cache = boxes.length; index < cache; index++) {
  71001. var parsedBox = boxes[index];
  71002. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  71003. }
  71004. }
  71005. // Spheres
  71006. var spheres = geometries.spheres;
  71007. if (spheres !== undefined && spheres !== null) {
  71008. for (index = 0, cache = spheres.length; index < cache; index++) {
  71009. var parsedSphere = spheres[index];
  71010. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  71011. }
  71012. }
  71013. // Cylinders
  71014. var cylinders = geometries.cylinders;
  71015. if (cylinders !== undefined && cylinders !== null) {
  71016. for (index = 0, cache = cylinders.length; index < cache; index++) {
  71017. var parsedCylinder = cylinders[index];
  71018. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  71019. }
  71020. }
  71021. // Toruses
  71022. var toruses = geometries.toruses;
  71023. if (toruses !== undefined && toruses !== null) {
  71024. for (index = 0, cache = toruses.length; index < cache; index++) {
  71025. var parsedTorus = toruses[index];
  71026. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  71027. }
  71028. }
  71029. // Grounds
  71030. var grounds = geometries.grounds;
  71031. if (grounds !== undefined && grounds !== null) {
  71032. for (index = 0, cache = grounds.length; index < cache; index++) {
  71033. var parsedGround = grounds[index];
  71034. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  71035. }
  71036. }
  71037. // Planes
  71038. var planes = geometries.planes;
  71039. if (planes !== undefined && planes !== null) {
  71040. for (index = 0, cache = planes.length; index < cache; index++) {
  71041. var parsedPlane = planes[index];
  71042. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  71043. }
  71044. }
  71045. // TorusKnots
  71046. var torusKnots = geometries.torusKnots;
  71047. if (torusKnots !== undefined && torusKnots !== null) {
  71048. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  71049. var parsedTorusKnot = torusKnots[index];
  71050. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  71051. }
  71052. }
  71053. // VertexData
  71054. var vertexData = geometries.vertexData;
  71055. if (vertexData !== undefined && vertexData !== null) {
  71056. for (index = 0, cache = vertexData.length; index < cache; index++) {
  71057. var parsedVertexData = vertexData[index];
  71058. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  71059. }
  71060. }
  71061. addedGeometry.forEach(function (g) {
  71062. if (g) {
  71063. container.geometries.push(g);
  71064. }
  71065. });
  71066. }
  71067. // Transform nodes
  71068. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  71069. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  71070. var parsedTransformNode = parsedData.transformNodes[index];
  71071. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  71072. container.transformNodes.push(node);
  71073. }
  71074. }
  71075. // Meshes
  71076. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71077. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71078. var parsedMesh = parsedData.meshes[index];
  71079. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71080. container.meshes.push(mesh);
  71081. log += (index === 0 ? "\n\tMeshes:" : "");
  71082. log += "\n\t\t" + mesh.toString(fullDetails);
  71083. }
  71084. }
  71085. // Cameras
  71086. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  71087. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  71088. var parsedCamera = parsedData.cameras[index];
  71089. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  71090. container.cameras.push(camera);
  71091. log += (index === 0 ? "\n\tCameras:" : "");
  71092. log += "\n\t\t" + camera.toString(fullDetails);
  71093. }
  71094. }
  71095. // Browsing all the graph to connect the dots
  71096. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  71097. var camera = scene.cameras[index];
  71098. if (camera._waitingParentId) {
  71099. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  71100. camera._waitingParentId = null;
  71101. }
  71102. }
  71103. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  71104. var light_1 = scene.lights[index];
  71105. if (light_1 && light_1._waitingParentId) {
  71106. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  71107. light_1._waitingParentId = null;
  71108. }
  71109. }
  71110. // Sounds
  71111. // TODO: add sound
  71112. var loadedSounds = [];
  71113. var loadedSound;
  71114. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  71115. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  71116. var parsedSound = parsedData.sounds[index];
  71117. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71118. if (!parsedSound.url)
  71119. parsedSound.url = parsedSound.name;
  71120. if (!loadedSounds[parsedSound.url]) {
  71121. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  71122. loadedSounds[parsedSound.url] = loadedSound;
  71123. container.sounds.push(loadedSound);
  71124. }
  71125. else {
  71126. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  71127. }
  71128. }
  71129. else {
  71130. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  71131. }
  71132. }
  71133. }
  71134. loadedSounds = [];
  71135. // Connect parents & children and parse actions
  71136. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  71137. var transformNode = scene.transformNodes[index];
  71138. if (transformNode._waitingParentId) {
  71139. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  71140. transformNode._waitingParentId = null;
  71141. }
  71142. }
  71143. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71144. var mesh = scene.meshes[index];
  71145. if (mesh._waitingParentId) {
  71146. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  71147. mesh._waitingParentId = null;
  71148. }
  71149. if (mesh._waitingActions) {
  71150. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  71151. mesh._waitingActions = null;
  71152. }
  71153. }
  71154. // freeze world matrix application
  71155. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71156. var currentMesh = scene.meshes[index];
  71157. if (currentMesh._waitingFreezeWorldMatrix) {
  71158. currentMesh.freezeWorldMatrix();
  71159. currentMesh._waitingFreezeWorldMatrix = null;
  71160. }
  71161. else {
  71162. currentMesh.computeWorldMatrix(true);
  71163. }
  71164. }
  71165. // Shadows
  71166. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  71167. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  71168. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  71169. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  71170. // SG would be available on their associated lights
  71171. }
  71172. }
  71173. // Lights exclusions / inclusions
  71174. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  71175. var light_2 = scene.lights[index];
  71176. // Excluded check
  71177. if (light_2._excludedMeshesIds.length > 0) {
  71178. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  71179. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  71180. if (excludedMesh) {
  71181. light_2.excludedMeshes.push(excludedMesh);
  71182. }
  71183. }
  71184. light_2._excludedMeshesIds = [];
  71185. }
  71186. // Included check
  71187. if (light_2._includedOnlyMeshesIds.length > 0) {
  71188. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  71189. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  71190. if (includedOnlyMesh) {
  71191. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  71192. }
  71193. }
  71194. light_2._includedOnlyMeshesIds = [];
  71195. }
  71196. }
  71197. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  71198. // Actions (scene)
  71199. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  71200. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  71201. }
  71202. if (!addToScene) {
  71203. container.removeAllFromScene();
  71204. }
  71205. }
  71206. catch (err) {
  71207. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  71208. if (onError) {
  71209. onError(msg, err);
  71210. }
  71211. else {
  71212. BABYLON.Tools.Log(msg);
  71213. throw err;
  71214. }
  71215. }
  71216. finally {
  71217. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71218. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71219. }
  71220. }
  71221. return container;
  71222. };
  71223. BABYLON.SceneLoader.RegisterPlugin({
  71224. name: "babylon.js",
  71225. extensions: ".babylon",
  71226. canDirectLoad: function (data) {
  71227. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  71228. return true;
  71229. }
  71230. return false;
  71231. },
  71232. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  71233. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71234. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71235. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71236. // and avoid problems with multiple concurrent .babylon loads.
  71237. var log = "importMesh has failed JSON parse";
  71238. try {
  71239. var parsedData = JSON.parse(data);
  71240. log = "";
  71241. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71242. if (!meshesNames) {
  71243. meshesNames = null;
  71244. }
  71245. else if (!Array.isArray(meshesNames)) {
  71246. meshesNames = [meshesNames];
  71247. }
  71248. var hierarchyIds = new Array();
  71249. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71250. var loadedSkeletonsIds = [];
  71251. var loadedMaterialsIds = [];
  71252. var index;
  71253. var cache;
  71254. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71255. var parsedMesh = parsedData.meshes[index];
  71256. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  71257. if (meshesNames !== null) {
  71258. // Remove found mesh name from list.
  71259. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  71260. }
  71261. //Geometry?
  71262. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  71263. //does the file contain geometries?
  71264. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  71265. //find the correct geometry and add it to the scene
  71266. var found = false;
  71267. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  71268. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  71269. return;
  71270. }
  71271. else {
  71272. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  71273. if (parsedGeometryData.id === parsedMesh.geometryId) {
  71274. switch (geometryType) {
  71275. case "boxes":
  71276. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  71277. break;
  71278. case "spheres":
  71279. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  71280. break;
  71281. case "cylinders":
  71282. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  71283. break;
  71284. case "toruses":
  71285. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  71286. break;
  71287. case "grounds":
  71288. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  71289. break;
  71290. case "planes":
  71291. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  71292. break;
  71293. case "torusKnots":
  71294. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  71295. break;
  71296. case "vertexData":
  71297. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  71298. break;
  71299. }
  71300. found = true;
  71301. }
  71302. });
  71303. }
  71304. });
  71305. if (found === false) {
  71306. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  71307. }
  71308. }
  71309. }
  71310. // Material ?
  71311. if (parsedMesh.materialId) {
  71312. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  71313. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71314. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  71315. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  71316. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  71317. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  71318. var subMatId = parsedMultiMaterial.materials[matIndex];
  71319. loadedMaterialsIds.push(subMatId);
  71320. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  71321. if (mat) {
  71322. log += "\n\tMaterial " + mat.toString(fullDetails);
  71323. }
  71324. }
  71325. loadedMaterialsIds.push(parsedMultiMaterial.id);
  71326. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71327. if (mmat) {
  71328. materialFound = true;
  71329. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  71330. }
  71331. break;
  71332. }
  71333. }
  71334. }
  71335. if (materialFound === false) {
  71336. loadedMaterialsIds.push(parsedMesh.materialId);
  71337. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  71338. if (!mat) {
  71339. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  71340. }
  71341. else {
  71342. log += "\n\tMaterial " + mat.toString(fullDetails);
  71343. }
  71344. }
  71345. }
  71346. // Skeleton ?
  71347. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71348. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  71349. if (skeletonAlreadyLoaded === false) {
  71350. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  71351. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  71352. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  71353. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71354. skeletons.push(skeleton);
  71355. loadedSkeletonsIds.push(parsedSkeleton.id);
  71356. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  71357. }
  71358. }
  71359. }
  71360. }
  71361. // Morph targets ?
  71362. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71363. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71364. var managerData = _a[_i];
  71365. BABYLON.MorphTargetManager.Parse(managerData, scene);
  71366. }
  71367. }
  71368. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71369. meshes.push(mesh);
  71370. log += "\n\tMesh " + mesh.toString(fullDetails);
  71371. }
  71372. }
  71373. // Connecting parents
  71374. var currentMesh;
  71375. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71376. currentMesh = scene.meshes[index];
  71377. if (currentMesh._waitingParentId) {
  71378. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  71379. currentMesh._waitingParentId = null;
  71380. }
  71381. }
  71382. // freeze and compute world matrix application
  71383. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71384. currentMesh = scene.meshes[index];
  71385. if (currentMesh._waitingFreezeWorldMatrix) {
  71386. currentMesh.freezeWorldMatrix();
  71387. currentMesh._waitingFreezeWorldMatrix = null;
  71388. }
  71389. else {
  71390. currentMesh.computeWorldMatrix(true);
  71391. }
  71392. }
  71393. }
  71394. // Particles
  71395. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  71396. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  71397. if (parser) {
  71398. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  71399. var parsedParticleSystem = parsedData.particleSystems[index];
  71400. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  71401. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  71402. }
  71403. }
  71404. }
  71405. }
  71406. return true;
  71407. }
  71408. catch (err) {
  71409. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  71410. if (onError) {
  71411. onError(msg, err);
  71412. }
  71413. else {
  71414. BABYLON.Tools.Log(msg);
  71415. throw err;
  71416. }
  71417. }
  71418. finally {
  71419. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71420. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71421. }
  71422. }
  71423. return false;
  71424. },
  71425. load: function (scene, data, rootUrl, onError) {
  71426. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71427. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71428. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71429. // and avoid problems with multiple concurrent .babylon loads.
  71430. var log = "importScene has failed JSON parse";
  71431. try {
  71432. var parsedData = JSON.parse(data);
  71433. log = "";
  71434. // Scene
  71435. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  71436. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  71437. }
  71438. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  71439. scene.autoClear = parsedData.autoClear;
  71440. }
  71441. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  71442. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  71443. }
  71444. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  71445. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  71446. }
  71447. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  71448. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  71449. }
  71450. // Fog
  71451. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  71452. scene.fogMode = parsedData.fogMode;
  71453. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  71454. scene.fogStart = parsedData.fogStart;
  71455. scene.fogEnd = parsedData.fogEnd;
  71456. scene.fogDensity = parsedData.fogDensity;
  71457. log += "\tFog mode for scene: ";
  71458. switch (scene.fogMode) {
  71459. // getters not compiling, so using hardcoded
  71460. case 1:
  71461. log += "exp\n";
  71462. break;
  71463. case 2:
  71464. log += "exp2\n";
  71465. break;
  71466. case 3:
  71467. log += "linear\n";
  71468. break;
  71469. }
  71470. }
  71471. //Physics
  71472. if (parsedData.physicsEnabled) {
  71473. var physicsPlugin;
  71474. if (parsedData.physicsEngine === "cannon") {
  71475. physicsPlugin = new BABYLON.CannonJSPlugin();
  71476. }
  71477. else if (parsedData.physicsEngine === "oimo") {
  71478. physicsPlugin = new BABYLON.OimoJSPlugin();
  71479. }
  71480. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  71481. //else - default engine, which is currently oimo
  71482. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  71483. scene.enablePhysics(physicsGravity, physicsPlugin);
  71484. }
  71485. // Metadata
  71486. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  71487. scene.metadata = parsedData.metadata;
  71488. }
  71489. //collisions, if defined. otherwise, default is true
  71490. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  71491. scene.collisionsEnabled = parsedData.collisionsEnabled;
  71492. }
  71493. scene.workerCollisions = !!parsedData.workerCollisions;
  71494. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  71495. if (!container) {
  71496. return false;
  71497. }
  71498. if (parsedData.autoAnimate) {
  71499. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  71500. }
  71501. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  71502. scene.setActiveCameraByID(parsedData.activeCameraID);
  71503. }
  71504. // Environment texture
  71505. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  71506. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  71507. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  71508. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  71509. if (parsedData.environmentTextureRotationY) {
  71510. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  71511. }
  71512. scene.environmentTexture = hdrTexture;
  71513. }
  71514. else {
  71515. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  71516. if (parsedData.environmentTextureRotationY) {
  71517. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  71518. }
  71519. scene.environmentTexture = cubeTexture;
  71520. }
  71521. if (parsedData.createDefaultSkybox === true) {
  71522. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  71523. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  71524. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  71525. }
  71526. }
  71527. // Finish
  71528. return true;
  71529. }
  71530. catch (err) {
  71531. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  71532. if (onError) {
  71533. onError(msg, err);
  71534. }
  71535. else {
  71536. BABYLON.Tools.Log(msg);
  71537. throw err;
  71538. }
  71539. }
  71540. finally {
  71541. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71542. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71543. }
  71544. }
  71545. return false;
  71546. },
  71547. loadAssetContainer: function (scene, data, rootUrl, onError) {
  71548. var container = loadAssetContainer(scene, data, rootUrl, onError);
  71549. return container;
  71550. }
  71551. });
  71552. })(BABYLON || (BABYLON = {}));
  71553. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  71554. var BABYLON;
  71555. (function (BABYLON) {
  71556. var FilesInput = /** @class */ (function () {
  71557. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  71558. this.onProcessFileCallback = function () { return true; };
  71559. this._engine = engine;
  71560. this._currentScene = scene;
  71561. this._sceneLoadedCallback = sceneLoadedCallback;
  71562. this._progressCallback = progressCallback;
  71563. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  71564. this._textureLoadingCallback = textureLoadingCallback;
  71565. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  71566. this._onReloadCallback = onReloadCallback;
  71567. this._errorCallback = errorCallback;
  71568. }
  71569. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  71570. var _this = this;
  71571. if (elementToMonitor) {
  71572. this._elementToMonitor = elementToMonitor;
  71573. this._dragEnterHandler = function (e) { _this.drag(e); };
  71574. this._dragOverHandler = function (e) { _this.drag(e); };
  71575. this._dropHandler = function (e) { _this.drop(e); };
  71576. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  71577. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  71578. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  71579. }
  71580. };
  71581. FilesInput.prototype.dispose = function () {
  71582. if (!this._elementToMonitor) {
  71583. return;
  71584. }
  71585. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  71586. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  71587. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  71588. };
  71589. FilesInput.prototype.renderFunction = function () {
  71590. if (this._additionalRenderLoopLogicCallback) {
  71591. this._additionalRenderLoopLogicCallback();
  71592. }
  71593. if (this._currentScene) {
  71594. if (this._textureLoadingCallback) {
  71595. var remaining = this._currentScene.getWaitingItemsCount();
  71596. if (remaining > 0) {
  71597. this._textureLoadingCallback(remaining);
  71598. }
  71599. }
  71600. this._currentScene.render();
  71601. }
  71602. };
  71603. FilesInput.prototype.drag = function (e) {
  71604. e.stopPropagation();
  71605. e.preventDefault();
  71606. };
  71607. FilesInput.prototype.drop = function (eventDrop) {
  71608. eventDrop.stopPropagation();
  71609. eventDrop.preventDefault();
  71610. this.loadFiles(eventDrop);
  71611. };
  71612. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  71613. var _this = this;
  71614. var reader = folder.createReader();
  71615. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  71616. reader.readEntries(function (entries) {
  71617. remaining.count += entries.length;
  71618. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  71619. var entry = entries_1[_i];
  71620. if (entry.isFile) {
  71621. entry.file(function (file) {
  71622. file.correctName = relativePath + file.name;
  71623. files.push(file);
  71624. if (--remaining.count === 0) {
  71625. callback();
  71626. }
  71627. });
  71628. }
  71629. else if (entry.isDirectory) {
  71630. _this._traverseFolder(entry, files, remaining, callback);
  71631. }
  71632. }
  71633. if (--remaining.count) {
  71634. callback();
  71635. }
  71636. });
  71637. };
  71638. FilesInput.prototype._processFiles = function (files) {
  71639. for (var i = 0; i < files.length; i++) {
  71640. var name = files[i].correctName.toLowerCase();
  71641. var extension = name.split('.').pop();
  71642. if (!this.onProcessFileCallback(files[i], name, extension)) {
  71643. continue;
  71644. }
  71645. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  71646. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  71647. this._sceneFileToLoad = files[i];
  71648. }
  71649. else {
  71650. FilesInput.FilesToLoad[name] = files[i];
  71651. }
  71652. }
  71653. };
  71654. FilesInput.prototype.loadFiles = function (event) {
  71655. var _this = this;
  71656. if (this._startingProcessingFilesCallback)
  71657. this._startingProcessingFilesCallback();
  71658. // Handling data transfer via drag'n'drop
  71659. if (event && event.dataTransfer && event.dataTransfer.files) {
  71660. this._filesToLoad = event.dataTransfer.files;
  71661. }
  71662. // Handling files from input files
  71663. if (event && event.target && event.target.files) {
  71664. this._filesToLoad = event.target.files;
  71665. }
  71666. if (this._filesToLoad && this._filesToLoad.length > 0) {
  71667. var files_1 = new Array();
  71668. var folders = [];
  71669. var items = event.dataTransfer ? event.dataTransfer.items : null;
  71670. for (var i = 0; i < this._filesToLoad.length; i++) {
  71671. var fileToLoad = this._filesToLoad[i];
  71672. var name_1 = fileToLoad.name.toLowerCase();
  71673. var entry = void 0;
  71674. fileToLoad.correctName = name_1;
  71675. if (items) {
  71676. var item = items[i];
  71677. if (item.getAsEntry) {
  71678. entry = item.getAsEntry();
  71679. }
  71680. else if (item.webkitGetAsEntry) {
  71681. entry = item.webkitGetAsEntry();
  71682. }
  71683. }
  71684. if (!entry) {
  71685. files_1.push(fileToLoad);
  71686. }
  71687. else {
  71688. if (entry.isDirectory) {
  71689. folders.push(entry);
  71690. }
  71691. else {
  71692. files_1.push(fileToLoad);
  71693. }
  71694. }
  71695. }
  71696. if (folders.length === 0) {
  71697. this._processFiles(files_1);
  71698. this._processReload();
  71699. }
  71700. else {
  71701. var remaining = { count: folders.length };
  71702. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  71703. var folder = folders_1[_i];
  71704. this._traverseFolder(folder, files_1, remaining, function () {
  71705. _this._processFiles(files_1);
  71706. if (remaining.count === 0) {
  71707. _this._processReload();
  71708. }
  71709. });
  71710. }
  71711. }
  71712. }
  71713. };
  71714. FilesInput.prototype._processReload = function () {
  71715. if (this._onReloadCallback) {
  71716. this._onReloadCallback(this._sceneFileToLoad);
  71717. }
  71718. else {
  71719. this.reload();
  71720. }
  71721. };
  71722. FilesInput.prototype.reload = function () {
  71723. var _this = this;
  71724. // If a scene file has been provided
  71725. if (this._sceneFileToLoad) {
  71726. if (this._currentScene) {
  71727. if (BABYLON.Tools.errorsCount > 0) {
  71728. BABYLON.Tools.ClearLogCache();
  71729. }
  71730. this._engine.stopRenderLoop();
  71731. }
  71732. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  71733. if (_this._progressCallback) {
  71734. _this._progressCallback(progress);
  71735. }
  71736. }).then(function (scene) {
  71737. if (_this._currentScene) {
  71738. _this._currentScene.dispose();
  71739. }
  71740. _this._currentScene = scene;
  71741. if (_this._sceneLoadedCallback) {
  71742. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  71743. }
  71744. // Wait for textures and shaders to be ready
  71745. _this._currentScene.executeWhenReady(function () {
  71746. _this._engine.runRenderLoop(function () {
  71747. _this.renderFunction();
  71748. });
  71749. });
  71750. }).catch(function (error) {
  71751. if (_this._errorCallback) {
  71752. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  71753. }
  71754. });
  71755. }
  71756. else {
  71757. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  71758. }
  71759. };
  71760. FilesInput.FilesToLoad = {};
  71761. return FilesInput;
  71762. }());
  71763. BABYLON.FilesInput = FilesInput;
  71764. })(BABYLON || (BABYLON = {}));
  71765. //# sourceMappingURL=babylon.filesInput.js.map
  71766. var BABYLON;
  71767. (function (BABYLON) {
  71768. var Tags = /** @class */ (function () {
  71769. function Tags() {
  71770. }
  71771. Tags.EnableFor = function (obj) {
  71772. obj._tags = obj._tags || {};
  71773. obj.hasTags = function () {
  71774. return Tags.HasTags(obj);
  71775. };
  71776. obj.addTags = function (tagsString) {
  71777. return Tags.AddTagsTo(obj, tagsString);
  71778. };
  71779. obj.removeTags = function (tagsString) {
  71780. return Tags.RemoveTagsFrom(obj, tagsString);
  71781. };
  71782. obj.matchesTagsQuery = function (tagsQuery) {
  71783. return Tags.MatchesQuery(obj, tagsQuery);
  71784. };
  71785. };
  71786. Tags.DisableFor = function (obj) {
  71787. delete obj._tags;
  71788. delete obj.hasTags;
  71789. delete obj.addTags;
  71790. delete obj.removeTags;
  71791. delete obj.matchesTagsQuery;
  71792. };
  71793. Tags.HasTags = function (obj) {
  71794. if (!obj._tags) {
  71795. return false;
  71796. }
  71797. return !BABYLON.Tools.IsEmpty(obj._tags);
  71798. };
  71799. Tags.GetTags = function (obj, asString) {
  71800. if (asString === void 0) { asString = true; }
  71801. if (!obj._tags) {
  71802. return null;
  71803. }
  71804. if (asString) {
  71805. var tagsArray = [];
  71806. for (var tag in obj._tags) {
  71807. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  71808. tagsArray.push(tag);
  71809. }
  71810. }
  71811. return tagsArray.join(" ");
  71812. }
  71813. else {
  71814. return obj._tags;
  71815. }
  71816. };
  71817. // the tags 'true' and 'false' are reserved and cannot be used as tags
  71818. // a tag cannot start with '||', '&&', and '!'
  71819. // it cannot contain whitespaces
  71820. Tags.AddTagsTo = function (obj, tagsString) {
  71821. if (!tagsString) {
  71822. return;
  71823. }
  71824. if (typeof tagsString !== "string") {
  71825. return;
  71826. }
  71827. var tags = tagsString.split(" ");
  71828. tags.forEach(function (tag, index, array) {
  71829. Tags._AddTagTo(obj, tag);
  71830. });
  71831. };
  71832. Tags._AddTagTo = function (obj, tag) {
  71833. tag = tag.trim();
  71834. if (tag === "" || tag === "true" || tag === "false") {
  71835. return;
  71836. }
  71837. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  71838. return;
  71839. }
  71840. Tags.EnableFor(obj);
  71841. obj._tags[tag] = true;
  71842. };
  71843. Tags.RemoveTagsFrom = function (obj, tagsString) {
  71844. if (!Tags.HasTags(obj)) {
  71845. return;
  71846. }
  71847. var tags = tagsString.split(" ");
  71848. for (var t in tags) {
  71849. Tags._RemoveTagFrom(obj, tags[t]);
  71850. }
  71851. };
  71852. Tags._RemoveTagFrom = function (obj, tag) {
  71853. delete obj._tags[tag];
  71854. };
  71855. Tags.MatchesQuery = function (obj, tagsQuery) {
  71856. if (tagsQuery === undefined) {
  71857. return true;
  71858. }
  71859. if (tagsQuery === "") {
  71860. return Tags.HasTags(obj);
  71861. }
  71862. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  71863. };
  71864. return Tags;
  71865. }());
  71866. BABYLON.Tags = Tags;
  71867. })(BABYLON || (BABYLON = {}));
  71868. //# sourceMappingURL=babylon.tags.js.map
  71869. var BABYLON;
  71870. (function (BABYLON) {
  71871. /**
  71872. * Class used to evalaute queries containing `and` and `or` operators
  71873. */
  71874. var AndOrNotEvaluator = /** @class */ (function () {
  71875. function AndOrNotEvaluator() {
  71876. }
  71877. /**
  71878. * Evaluate a query
  71879. * @param query defines the query to evaluate
  71880. * @param evaluateCallback defines the callback used to filter result
  71881. * @returns true if the query matches
  71882. */
  71883. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  71884. if (!query.match(/\([^\(\)]*\)/g)) {
  71885. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  71886. }
  71887. else {
  71888. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  71889. // remove parenthesis
  71890. r = r.slice(1, r.length - 1);
  71891. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  71892. });
  71893. }
  71894. if (query === "true") {
  71895. return true;
  71896. }
  71897. if (query === "false") {
  71898. return false;
  71899. }
  71900. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  71901. };
  71902. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  71903. evaluateCallback = evaluateCallback || (function (r) {
  71904. return r === "true" ? true : false;
  71905. });
  71906. var result;
  71907. var or = parenthesisContent.split("||");
  71908. for (var i in or) {
  71909. if (or.hasOwnProperty(i)) {
  71910. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  71911. var and = ori.split("&&");
  71912. if (and.length > 1) {
  71913. for (var j = 0; j < and.length; ++j) {
  71914. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  71915. if (andj !== "true" && andj !== "false") {
  71916. if (andj[0] === "!") {
  71917. result = !evaluateCallback(andj.substring(1));
  71918. }
  71919. else {
  71920. result = evaluateCallback(andj);
  71921. }
  71922. }
  71923. else {
  71924. result = andj === "true" ? true : false;
  71925. }
  71926. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  71927. ori = "false";
  71928. break;
  71929. }
  71930. }
  71931. }
  71932. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  71933. result = true;
  71934. break;
  71935. }
  71936. // result equals false (or undefined)
  71937. if (ori !== "true" && ori !== "false") {
  71938. if (ori[0] === "!") {
  71939. result = !evaluateCallback(ori.substring(1));
  71940. }
  71941. else {
  71942. result = evaluateCallback(ori);
  71943. }
  71944. }
  71945. else {
  71946. result = ori === "true" ? true : false;
  71947. }
  71948. }
  71949. }
  71950. // the whole parenthesis scope is replaced by 'true' or 'false'
  71951. return result ? "true" : "false";
  71952. };
  71953. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  71954. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  71955. // remove whitespaces
  71956. r = r.replace(/[\s]/g, function () { return ""; });
  71957. return r.length % 2 ? "!" : "";
  71958. });
  71959. booleanString = booleanString.trim();
  71960. if (booleanString === "!true") {
  71961. booleanString = "false";
  71962. }
  71963. else if (booleanString === "!false") {
  71964. booleanString = "true";
  71965. }
  71966. return booleanString;
  71967. };
  71968. return AndOrNotEvaluator;
  71969. }());
  71970. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  71971. })(BABYLON || (BABYLON = {}));
  71972. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  71973. var BABYLON;
  71974. (function (BABYLON) {
  71975. /**
  71976. * Class used to enable access to IndexedDB
  71977. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  71978. */
  71979. var Database = /** @class */ (function () {
  71980. /**
  71981. * Creates a new Database
  71982. * @param urlToScene defines the url to load the scene
  71983. * @param callbackManifestChecked defines the callback to use when manifest is checked
  71984. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  71985. */
  71986. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  71987. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  71988. var _this = this;
  71989. // Handling various flavors of prefixed version of IndexedDB
  71990. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  71991. this.callbackManifestChecked = callbackManifestChecked;
  71992. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  71993. this.db = null;
  71994. this._enableSceneOffline = false;
  71995. this._enableTexturesOffline = false;
  71996. this.manifestVersionFound = 0;
  71997. this.mustUpdateRessources = false;
  71998. this.hasReachedQuota = false;
  71999. if (!Database.IDBStorageEnabled) {
  72000. this.callbackManifestChecked(true);
  72001. }
  72002. else {
  72003. if (disableManifestCheck) {
  72004. this._enableSceneOffline = true;
  72005. this._enableTexturesOffline = true;
  72006. this.manifestVersionFound = 1;
  72007. BABYLON.Tools.SetImmediate(function () {
  72008. _this.callbackManifestChecked(true);
  72009. });
  72010. }
  72011. else {
  72012. this._checkManifestFile();
  72013. }
  72014. }
  72015. }
  72016. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  72017. /**
  72018. * Gets a boolean indicating if scene must be saved in the database
  72019. */
  72020. get: function () {
  72021. return this._enableSceneOffline;
  72022. },
  72023. enumerable: true,
  72024. configurable: true
  72025. });
  72026. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  72027. /**
  72028. * Gets a boolean indicating if textures must be saved in the database
  72029. */
  72030. get: function () {
  72031. return this._enableTexturesOffline;
  72032. },
  72033. enumerable: true,
  72034. configurable: true
  72035. });
  72036. Database.prototype._checkManifestFile = function () {
  72037. var _this = this;
  72038. var noManifestFile = function () {
  72039. _this._enableSceneOffline = false;
  72040. _this._enableTexturesOffline = false;
  72041. _this.callbackManifestChecked(false);
  72042. };
  72043. var timeStampUsed = false;
  72044. var manifestURL = this.currentSceneUrl + ".manifest";
  72045. var xhr = new XMLHttpRequest();
  72046. if (navigator.onLine) {
  72047. // Adding a timestamp to by-pass browsers' cache
  72048. timeStampUsed = true;
  72049. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  72050. }
  72051. xhr.open("GET", manifestURL, true);
  72052. xhr.addEventListener("load", function () {
  72053. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  72054. try {
  72055. var manifestFile = JSON.parse(xhr.response);
  72056. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  72057. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  72058. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  72059. _this.manifestVersionFound = manifestFile.version;
  72060. }
  72061. if (_this.callbackManifestChecked) {
  72062. _this.callbackManifestChecked(true);
  72063. }
  72064. }
  72065. catch (ex) {
  72066. noManifestFile();
  72067. }
  72068. }
  72069. else {
  72070. noManifestFile();
  72071. }
  72072. }, false);
  72073. xhr.addEventListener("error", function (event) {
  72074. if (timeStampUsed) {
  72075. timeStampUsed = false;
  72076. // Let's retry without the timeStamp
  72077. // It could fail when coupled with HTML5 Offline API
  72078. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  72079. xhr.open("GET", retryManifestURL, true);
  72080. xhr.send();
  72081. }
  72082. else {
  72083. noManifestFile();
  72084. }
  72085. }, false);
  72086. try {
  72087. xhr.send();
  72088. }
  72089. catch (ex) {
  72090. BABYLON.Tools.Error("Error on XHR send request.");
  72091. this.callbackManifestChecked(false);
  72092. }
  72093. };
  72094. /**
  72095. * Open the database and make it available
  72096. * @param successCallback defines the callback to call on success
  72097. * @param errorCallback defines the callback to call on error
  72098. */
  72099. Database.prototype.openAsync = function (successCallback, errorCallback) {
  72100. var _this = this;
  72101. var handleError = function () {
  72102. _this.isSupported = false;
  72103. if (errorCallback)
  72104. errorCallback();
  72105. };
  72106. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  72107. // Your browser doesn't support IndexedDB
  72108. this.isSupported = false;
  72109. if (errorCallback)
  72110. errorCallback();
  72111. }
  72112. else {
  72113. // If the DB hasn't been opened or created yet
  72114. if (!this.db) {
  72115. this.hasReachedQuota = false;
  72116. this.isSupported = true;
  72117. var request = this.idbFactory.open("babylonjs", 1);
  72118. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  72119. request.onerror = function (event) {
  72120. handleError();
  72121. };
  72122. // executes when a version change transaction cannot complete due to other active transactions
  72123. request.onblocked = function (event) {
  72124. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  72125. handleError();
  72126. };
  72127. // DB has been opened successfully
  72128. request.onsuccess = function (event) {
  72129. _this.db = request.result;
  72130. successCallback();
  72131. };
  72132. // Initialization of the DB. Creating Scenes & Textures stores
  72133. request.onupgradeneeded = function (event) {
  72134. _this.db = (event.target).result;
  72135. if (_this.db) {
  72136. try {
  72137. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  72138. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  72139. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  72140. }
  72141. catch (ex) {
  72142. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  72143. handleError();
  72144. }
  72145. }
  72146. };
  72147. }
  72148. // DB has already been created and opened
  72149. else {
  72150. if (successCallback)
  72151. successCallback();
  72152. }
  72153. }
  72154. };
  72155. /**
  72156. * Loads an image from the database
  72157. * @param url defines the url to load from
  72158. * @param image defines the target DOM image
  72159. */
  72160. Database.prototype.loadImageFromDB = function (url, image) {
  72161. var _this = this;
  72162. var completeURL = Database._ReturnFullUrlLocation(url);
  72163. var saveAndLoadImage = function () {
  72164. if (!_this.hasReachedQuota && _this.db !== null) {
  72165. // the texture is not yet in the DB, let's try to save it
  72166. _this._saveImageIntoDBAsync(completeURL, image);
  72167. }
  72168. // If the texture is not in the DB and we've reached the DB quota limit
  72169. // let's load it directly from the web
  72170. else {
  72171. image.src = url;
  72172. }
  72173. };
  72174. if (!this.mustUpdateRessources) {
  72175. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  72176. }
  72177. // First time we're download the images or update requested in the manifest file by a version change
  72178. else {
  72179. saveAndLoadImage();
  72180. }
  72181. };
  72182. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  72183. if (this.isSupported && this.db !== null) {
  72184. var texture;
  72185. var transaction = this.db.transaction(["textures"]);
  72186. transaction.onabort = function (event) {
  72187. image.src = url;
  72188. };
  72189. transaction.oncomplete = function (event) {
  72190. var blobTextureURL;
  72191. if (texture) {
  72192. var URL = window.URL || window.webkitURL;
  72193. blobTextureURL = URL.createObjectURL(texture.data);
  72194. image.onerror = function () {
  72195. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  72196. image.src = url;
  72197. };
  72198. image.src = blobTextureURL;
  72199. }
  72200. else {
  72201. notInDBCallback();
  72202. }
  72203. };
  72204. var getRequest = transaction.objectStore("textures").get(url);
  72205. getRequest.onsuccess = function (event) {
  72206. texture = (event.target).result;
  72207. };
  72208. getRequest.onerror = function (event) {
  72209. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  72210. image.src = url;
  72211. };
  72212. }
  72213. else {
  72214. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72215. image.src = url;
  72216. }
  72217. };
  72218. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  72219. var _this = this;
  72220. if (this.isSupported) {
  72221. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  72222. var generateBlobUrl = function () {
  72223. var blobTextureURL;
  72224. if (blob) {
  72225. var URL = window.URL || window.webkitURL;
  72226. try {
  72227. blobTextureURL = URL.createObjectURL(blob);
  72228. }
  72229. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  72230. catch (ex) {
  72231. blobTextureURL = URL.createObjectURL(blob);
  72232. }
  72233. }
  72234. if (blobTextureURL) {
  72235. image.src = blobTextureURL;
  72236. }
  72237. };
  72238. if (Database.IsUASupportingBlobStorage) { // Create XHR
  72239. var xhr = new XMLHttpRequest(), blob;
  72240. xhr.open("GET", url, true);
  72241. xhr.responseType = "blob";
  72242. xhr.addEventListener("load", function () {
  72243. if (xhr.status === 200 && _this.db) {
  72244. // Blob as response (XHR2)
  72245. blob = xhr.response;
  72246. var transaction = _this.db.transaction(["textures"], "readwrite");
  72247. // the transaction could abort because of a QuotaExceededError error
  72248. transaction.onabort = function (event) {
  72249. try {
  72250. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72251. var srcElement = (event.srcElement || event.target);
  72252. var error = srcElement.error;
  72253. if (error && error.name === "QuotaExceededError") {
  72254. _this.hasReachedQuota = true;
  72255. }
  72256. }
  72257. catch (ex) { }
  72258. generateBlobUrl();
  72259. };
  72260. transaction.oncomplete = function (event) {
  72261. generateBlobUrl();
  72262. };
  72263. var newTexture = { textureUrl: url, data: blob };
  72264. try {
  72265. // Put the blob into the dabase
  72266. var addRequest = transaction.objectStore("textures").put(newTexture);
  72267. addRequest.onsuccess = function (event) {
  72268. };
  72269. addRequest.onerror = function (event) {
  72270. generateBlobUrl();
  72271. };
  72272. }
  72273. catch (ex) {
  72274. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  72275. if (ex.code === 25) {
  72276. Database.IsUASupportingBlobStorage = false;
  72277. }
  72278. image.src = url;
  72279. }
  72280. }
  72281. else {
  72282. image.src = url;
  72283. }
  72284. }, false);
  72285. xhr.addEventListener("error", function (event) {
  72286. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  72287. image.src = url;
  72288. }, false);
  72289. xhr.send();
  72290. }
  72291. else {
  72292. image.src = url;
  72293. }
  72294. }
  72295. else {
  72296. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72297. image.src = url;
  72298. }
  72299. };
  72300. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  72301. var _this = this;
  72302. var updateVersion = function () {
  72303. // the version is not yet in the DB or we need to update it
  72304. _this._saveVersionIntoDBAsync(url, versionLoaded);
  72305. };
  72306. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  72307. };
  72308. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  72309. var _this = this;
  72310. if (this.isSupported && this.db) {
  72311. var version;
  72312. try {
  72313. var transaction = this.db.transaction(["versions"]);
  72314. transaction.oncomplete = function (event) {
  72315. if (version) {
  72316. // If the version in the JSON file is different from the version in DB
  72317. if (_this.manifestVersionFound !== version.data) {
  72318. _this.mustUpdateRessources = true;
  72319. updateInDBCallback();
  72320. }
  72321. else {
  72322. callback(version.data);
  72323. }
  72324. }
  72325. // version was not found in DB
  72326. else {
  72327. _this.mustUpdateRessources = true;
  72328. updateInDBCallback();
  72329. }
  72330. };
  72331. transaction.onabort = function (event) {
  72332. callback(-1);
  72333. };
  72334. var getRequest = transaction.objectStore("versions").get(url);
  72335. getRequest.onsuccess = function (event) {
  72336. version = (event.target).result;
  72337. };
  72338. getRequest.onerror = function (event) {
  72339. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  72340. callback(-1);
  72341. };
  72342. }
  72343. catch (ex) {
  72344. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  72345. callback(-1);
  72346. }
  72347. }
  72348. else {
  72349. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72350. callback(-1);
  72351. }
  72352. };
  72353. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  72354. var _this = this;
  72355. if (this.isSupported && !this.hasReachedQuota && this.db) {
  72356. try {
  72357. // Open a transaction to the database
  72358. var transaction = this.db.transaction(["versions"], "readwrite");
  72359. // the transaction could abort because of a QuotaExceededError error
  72360. transaction.onabort = function (event) {
  72361. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72362. var error = event.srcElement['error'];
  72363. if (error && error.name === "QuotaExceededError") {
  72364. _this.hasReachedQuota = true;
  72365. }
  72366. }
  72367. catch (ex) { }
  72368. callback(-1);
  72369. };
  72370. transaction.oncomplete = function (event) {
  72371. callback(_this.manifestVersionFound);
  72372. };
  72373. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  72374. // Put the scene into the database
  72375. var addRequest = transaction.objectStore("versions").put(newVersion);
  72376. addRequest.onsuccess = function (event) {
  72377. };
  72378. addRequest.onerror = function (event) {
  72379. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  72380. };
  72381. }
  72382. catch (ex) {
  72383. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  72384. callback(-1);
  72385. }
  72386. }
  72387. else {
  72388. callback(-1);
  72389. }
  72390. };
  72391. /**
  72392. * Loads a file from database
  72393. * @param url defines the URL to load from
  72394. * @param sceneLoaded defines a callback to call on success
  72395. * @param progressCallBack defines a callback to call when progress changed
  72396. * @param errorCallback defines a callback to call on error
  72397. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  72398. */
  72399. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  72400. var _this = this;
  72401. var completeUrl = Database._ReturnFullUrlLocation(url);
  72402. var saveAndLoadFile = function () {
  72403. // the scene is not yet in the DB, let's try to save it
  72404. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  72405. };
  72406. this._checkVersionFromDB(completeUrl, function (version) {
  72407. if (version !== -1) {
  72408. if (!_this.mustUpdateRessources) {
  72409. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  72410. }
  72411. else {
  72412. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  72413. }
  72414. }
  72415. else {
  72416. if (errorCallback) {
  72417. errorCallback();
  72418. }
  72419. }
  72420. });
  72421. };
  72422. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  72423. if (this.isSupported && this.db) {
  72424. var targetStore;
  72425. if (url.indexOf(".babylon") !== -1) {
  72426. targetStore = "scenes";
  72427. }
  72428. else {
  72429. targetStore = "textures";
  72430. }
  72431. var file;
  72432. var transaction = this.db.transaction([targetStore]);
  72433. transaction.oncomplete = function (event) {
  72434. if (file) {
  72435. callback(file.data);
  72436. }
  72437. // file was not found in DB
  72438. else {
  72439. notInDBCallback();
  72440. }
  72441. };
  72442. transaction.onabort = function (event) {
  72443. notInDBCallback();
  72444. };
  72445. var getRequest = transaction.objectStore(targetStore).get(url);
  72446. getRequest.onsuccess = function (event) {
  72447. file = (event.target).result;
  72448. };
  72449. getRequest.onerror = function (event) {
  72450. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  72451. notInDBCallback();
  72452. };
  72453. }
  72454. else {
  72455. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72456. callback();
  72457. }
  72458. };
  72459. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  72460. var _this = this;
  72461. if (this.isSupported) {
  72462. var targetStore;
  72463. if (url.indexOf(".babylon") !== -1) {
  72464. targetStore = "scenes";
  72465. }
  72466. else {
  72467. targetStore = "textures";
  72468. }
  72469. // Create XHR
  72470. var xhr = new XMLHttpRequest();
  72471. var fileData;
  72472. xhr.open("GET", url + "?" + Date.now(), true);
  72473. if (useArrayBuffer) {
  72474. xhr.responseType = "arraybuffer";
  72475. }
  72476. if (progressCallback) {
  72477. xhr.onprogress = progressCallback;
  72478. }
  72479. xhr.addEventListener("load", function () {
  72480. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  72481. // Blob as response (XHR2)
  72482. //fileData = xhr.responseText;
  72483. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  72484. if (!_this.hasReachedQuota && _this.db) {
  72485. // Open a transaction to the database
  72486. var transaction = _this.db.transaction([targetStore], "readwrite");
  72487. // the transaction could abort because of a QuotaExceededError error
  72488. transaction.onabort = function (event) {
  72489. try {
  72490. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72491. var error = event.srcElement['error'];
  72492. if (error && error.name === "QuotaExceededError") {
  72493. _this.hasReachedQuota = true;
  72494. }
  72495. }
  72496. catch (ex) { }
  72497. callback(fileData);
  72498. };
  72499. transaction.oncomplete = function (event) {
  72500. callback(fileData);
  72501. };
  72502. var newFile;
  72503. if (targetStore === "scenes") {
  72504. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  72505. }
  72506. else {
  72507. newFile = { textureUrl: url, data: fileData };
  72508. }
  72509. try {
  72510. // Put the scene into the database
  72511. var addRequest = transaction.objectStore(targetStore).put(newFile);
  72512. addRequest.onsuccess = function (event) {
  72513. };
  72514. addRequest.onerror = function (event) {
  72515. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  72516. };
  72517. }
  72518. catch (ex) {
  72519. callback(fileData);
  72520. }
  72521. }
  72522. else {
  72523. callback(fileData);
  72524. }
  72525. }
  72526. else {
  72527. if (xhr.status >= 400 && errorCallback) {
  72528. errorCallback(xhr);
  72529. }
  72530. else {
  72531. callback();
  72532. }
  72533. }
  72534. }, false);
  72535. xhr.addEventListener("error", function (event) {
  72536. BABYLON.Tools.Error("error on XHR request.");
  72537. callback();
  72538. }, false);
  72539. xhr.send();
  72540. }
  72541. else {
  72542. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72543. callback();
  72544. }
  72545. };
  72546. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  72547. Database.IsUASupportingBlobStorage = true;
  72548. /** Gets a boolean indicating if Database storate is enabled */
  72549. Database.IDBStorageEnabled = true;
  72550. Database._ParseURL = function (url) {
  72551. var a = document.createElement('a');
  72552. a.href = url;
  72553. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  72554. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  72555. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  72556. return absLocation;
  72557. };
  72558. Database._ReturnFullUrlLocation = function (url) {
  72559. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  72560. return (Database._ParseURL(window.location.href) + url);
  72561. }
  72562. else {
  72563. return url;
  72564. }
  72565. };
  72566. return Database;
  72567. }());
  72568. BABYLON.Database = Database;
  72569. })(BABYLON || (BABYLON = {}));
  72570. //# sourceMappingURL=babylon.database.js.map
  72571. var BABYLON;
  72572. (function (BABYLON) {
  72573. var FresnelParameters = /** @class */ (function () {
  72574. function FresnelParameters() {
  72575. this._isEnabled = true;
  72576. this.leftColor = BABYLON.Color3.White();
  72577. this.rightColor = BABYLON.Color3.Black();
  72578. this.bias = 0;
  72579. this.power = 1;
  72580. }
  72581. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  72582. get: function () {
  72583. return this._isEnabled;
  72584. },
  72585. set: function (value) {
  72586. if (this._isEnabled === value) {
  72587. return;
  72588. }
  72589. this._isEnabled = value;
  72590. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  72591. },
  72592. enumerable: true,
  72593. configurable: true
  72594. });
  72595. FresnelParameters.prototype.clone = function () {
  72596. var newFresnelParameters = new FresnelParameters();
  72597. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  72598. return newFresnelParameters;
  72599. };
  72600. FresnelParameters.prototype.serialize = function () {
  72601. var serializationObject = {};
  72602. serializationObject.isEnabled = this.isEnabled;
  72603. serializationObject.leftColor = this.leftColor.asArray();
  72604. serializationObject.rightColor = this.rightColor.asArray();
  72605. serializationObject.bias = this.bias;
  72606. serializationObject.power = this.power;
  72607. return serializationObject;
  72608. };
  72609. FresnelParameters.Parse = function (parsedFresnelParameters) {
  72610. var fresnelParameters = new FresnelParameters();
  72611. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  72612. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  72613. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  72614. fresnelParameters.bias = parsedFresnelParameters.bias;
  72615. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  72616. return fresnelParameters;
  72617. };
  72618. return FresnelParameters;
  72619. }());
  72620. BABYLON.FresnelParameters = FresnelParameters;
  72621. })(BABYLON || (BABYLON = {}));
  72622. //# sourceMappingURL=babylon.fresnelParameters.js.map
  72623. var BABYLON;
  72624. (function (BABYLON) {
  72625. var MultiMaterial = /** @class */ (function (_super) {
  72626. __extends(MultiMaterial, _super);
  72627. function MultiMaterial(name, scene) {
  72628. var _this = _super.call(this, name, scene, true) || this;
  72629. scene.multiMaterials.push(_this);
  72630. _this.subMaterials = new Array();
  72631. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  72632. return _this;
  72633. }
  72634. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  72635. get: function () {
  72636. return this._subMaterials;
  72637. },
  72638. set: function (value) {
  72639. this._subMaterials = value;
  72640. this._hookArray(value);
  72641. },
  72642. enumerable: true,
  72643. configurable: true
  72644. });
  72645. MultiMaterial.prototype._hookArray = function (array) {
  72646. var _this = this;
  72647. var oldPush = array.push;
  72648. array.push = function () {
  72649. var items = [];
  72650. for (var _i = 0; _i < arguments.length; _i++) {
  72651. items[_i] = arguments[_i];
  72652. }
  72653. var result = oldPush.apply(array, items);
  72654. _this._markAllSubMeshesAsTexturesDirty();
  72655. return result;
  72656. };
  72657. var oldSplice = array.splice;
  72658. array.splice = function (index, deleteCount) {
  72659. var deleted = oldSplice.apply(array, [index, deleteCount]);
  72660. _this._markAllSubMeshesAsTexturesDirty();
  72661. return deleted;
  72662. };
  72663. };
  72664. // Properties
  72665. MultiMaterial.prototype.getSubMaterial = function (index) {
  72666. if (index < 0 || index >= this.subMaterials.length) {
  72667. return this.getScene().defaultMaterial;
  72668. }
  72669. return this.subMaterials[index];
  72670. };
  72671. MultiMaterial.prototype.getActiveTextures = function () {
  72672. var _a;
  72673. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  72674. if (subMaterial) {
  72675. return subMaterial.getActiveTextures();
  72676. }
  72677. else {
  72678. return [];
  72679. }
  72680. }));
  72681. };
  72682. // Methods
  72683. MultiMaterial.prototype.getClassName = function () {
  72684. return "MultiMaterial";
  72685. };
  72686. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  72687. for (var index = 0; index < this.subMaterials.length; index++) {
  72688. var subMaterial = this.subMaterials[index];
  72689. if (subMaterial) {
  72690. if (subMaterial.storeEffectOnSubMeshes) {
  72691. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  72692. return false;
  72693. }
  72694. continue;
  72695. }
  72696. if (!subMaterial.isReady(mesh)) {
  72697. return false;
  72698. }
  72699. }
  72700. }
  72701. return true;
  72702. };
  72703. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  72704. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  72705. for (var index = 0; index < this.subMaterials.length; index++) {
  72706. var subMaterial = null;
  72707. var current = this.subMaterials[index];
  72708. if (cloneChildren && current) {
  72709. subMaterial = current.clone(name + "-" + current.name);
  72710. }
  72711. else {
  72712. subMaterial = this.subMaterials[index];
  72713. }
  72714. newMultiMaterial.subMaterials.push(subMaterial);
  72715. }
  72716. return newMultiMaterial;
  72717. };
  72718. MultiMaterial.prototype.serialize = function () {
  72719. var serializationObject = {};
  72720. serializationObject.name = this.name;
  72721. serializationObject.id = this.id;
  72722. if (BABYLON.Tags) {
  72723. serializationObject.tags = BABYLON.Tags.GetTags(this);
  72724. }
  72725. serializationObject.materials = [];
  72726. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  72727. var subMat = this.subMaterials[matIndex];
  72728. if (subMat) {
  72729. serializationObject.materials.push(subMat.id);
  72730. }
  72731. else {
  72732. serializationObject.materials.push(null);
  72733. }
  72734. }
  72735. return serializationObject;
  72736. };
  72737. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  72738. var scene = this.getScene();
  72739. if (!scene) {
  72740. return;
  72741. }
  72742. var index = scene.multiMaterials.indexOf(this);
  72743. if (index >= 0) {
  72744. scene.multiMaterials.splice(index, 1);
  72745. }
  72746. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  72747. };
  72748. return MultiMaterial;
  72749. }(BABYLON.Material));
  72750. BABYLON.MultiMaterial = MultiMaterial;
  72751. })(BABYLON || (BABYLON = {}));
  72752. //# sourceMappingURL=babylon.multiMaterial.js.map
  72753. var BABYLON;
  72754. (function (BABYLON) {
  72755. var FreeCameraTouchInput = /** @class */ (function () {
  72756. function FreeCameraTouchInput() {
  72757. this._offsetX = null;
  72758. this._offsetY = null;
  72759. this._pointerPressed = new Array();
  72760. this.touchAngularSensibility = 200000.0;
  72761. this.touchMoveSensibility = 250.0;
  72762. }
  72763. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  72764. var _this = this;
  72765. var previousPosition = null;
  72766. if (this._pointerInput === undefined) {
  72767. this._onLostFocus = function (evt) {
  72768. _this._offsetX = null;
  72769. _this._offsetY = null;
  72770. };
  72771. this._pointerInput = function (p, s) {
  72772. var evt = p.event;
  72773. if (evt.pointerType === "mouse") {
  72774. return;
  72775. }
  72776. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72777. if (!noPreventDefault) {
  72778. evt.preventDefault();
  72779. }
  72780. _this._pointerPressed.push(evt.pointerId);
  72781. if (_this._pointerPressed.length !== 1) {
  72782. return;
  72783. }
  72784. previousPosition = {
  72785. x: evt.clientX,
  72786. y: evt.clientY
  72787. };
  72788. }
  72789. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  72790. if (!noPreventDefault) {
  72791. evt.preventDefault();
  72792. }
  72793. var index = _this._pointerPressed.indexOf(evt.pointerId);
  72794. if (index === -1) {
  72795. return;
  72796. }
  72797. _this._pointerPressed.splice(index, 1);
  72798. if (index != 0) {
  72799. return;
  72800. }
  72801. previousPosition = null;
  72802. _this._offsetX = null;
  72803. _this._offsetY = null;
  72804. }
  72805. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  72806. if (!noPreventDefault) {
  72807. evt.preventDefault();
  72808. }
  72809. if (!previousPosition) {
  72810. return;
  72811. }
  72812. var index = _this._pointerPressed.indexOf(evt.pointerId);
  72813. if (index != 0) {
  72814. return;
  72815. }
  72816. _this._offsetX = evt.clientX - previousPosition.x;
  72817. _this._offsetY = -(evt.clientY - previousPosition.y);
  72818. }
  72819. };
  72820. }
  72821. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  72822. if (this._onLostFocus) {
  72823. element.addEventListener("blur", this._onLostFocus);
  72824. }
  72825. };
  72826. FreeCameraTouchInput.prototype.detachControl = function (element) {
  72827. if (this._pointerInput && element) {
  72828. if (this._observer) {
  72829. this.camera.getScene().onPointerObservable.remove(this._observer);
  72830. this._observer = null;
  72831. }
  72832. if (this._onLostFocus) {
  72833. element.removeEventListener("blur", this._onLostFocus);
  72834. this._onLostFocus = null;
  72835. }
  72836. this._pointerPressed = [];
  72837. this._offsetX = null;
  72838. this._offsetY = null;
  72839. }
  72840. };
  72841. FreeCameraTouchInput.prototype.checkInputs = function () {
  72842. if (this._offsetX && this._offsetY) {
  72843. var camera = this.camera;
  72844. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  72845. if (this._pointerPressed.length > 1) {
  72846. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  72847. }
  72848. else {
  72849. var speed = camera._computeLocalCameraSpeed();
  72850. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  72851. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  72852. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  72853. }
  72854. }
  72855. };
  72856. FreeCameraTouchInput.prototype.getClassName = function () {
  72857. return "FreeCameraTouchInput";
  72858. };
  72859. FreeCameraTouchInput.prototype.getSimpleName = function () {
  72860. return "touch";
  72861. };
  72862. __decorate([
  72863. BABYLON.serialize()
  72864. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  72865. __decorate([
  72866. BABYLON.serialize()
  72867. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  72868. return FreeCameraTouchInput;
  72869. }());
  72870. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  72871. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  72872. })(BABYLON || (BABYLON = {}));
  72873. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  72874. var BABYLON;
  72875. (function (BABYLON) {
  72876. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  72877. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  72878. });
  72879. // We're mainly based on the logic defined into the FreeCamera code
  72880. var TouchCamera = /** @class */ (function (_super) {
  72881. __extends(TouchCamera, _super);
  72882. //-- end properties for backward compatibility for inputs
  72883. function TouchCamera(name, position, scene) {
  72884. var _this = _super.call(this, name, position, scene) || this;
  72885. _this.inputs.addTouch();
  72886. _this._setupInputs();
  72887. return _this;
  72888. }
  72889. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  72890. //-- Begin properties for backward compatibility for inputs
  72891. get: function () {
  72892. var touch = this.inputs.attached["touch"];
  72893. if (touch)
  72894. return touch.touchAngularSensibility;
  72895. return 0;
  72896. },
  72897. set: function (value) {
  72898. var touch = this.inputs.attached["touch"];
  72899. if (touch)
  72900. touch.touchAngularSensibility = value;
  72901. },
  72902. enumerable: true,
  72903. configurable: true
  72904. });
  72905. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  72906. get: function () {
  72907. var touch = this.inputs.attached["touch"];
  72908. if (touch)
  72909. return touch.touchMoveSensibility;
  72910. return 0;
  72911. },
  72912. set: function (value) {
  72913. var touch = this.inputs.attached["touch"];
  72914. if (touch)
  72915. touch.touchMoveSensibility = value;
  72916. },
  72917. enumerable: true,
  72918. configurable: true
  72919. });
  72920. TouchCamera.prototype.getClassName = function () {
  72921. return "TouchCamera";
  72922. };
  72923. /** @hidden */
  72924. TouchCamera.prototype._setupInputs = function () {
  72925. var mouse = this.inputs.attached["mouse"];
  72926. if (mouse) {
  72927. mouse.touchEnabled = false;
  72928. }
  72929. };
  72930. return TouchCamera;
  72931. }(BABYLON.FreeCamera));
  72932. BABYLON.TouchCamera = TouchCamera;
  72933. })(BABYLON || (BABYLON = {}));
  72934. //# sourceMappingURL=babylon.touchCamera.js.map
  72935. var BABYLON;
  72936. (function (BABYLON) {
  72937. var ProceduralTexture = /** @class */ (function (_super) {
  72938. __extends(ProceduralTexture, _super);
  72939. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  72940. if (fallbackTexture === void 0) { fallbackTexture = null; }
  72941. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72942. if (isCube === void 0) { isCube = false; }
  72943. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  72944. _this.isCube = isCube;
  72945. _this.isEnabled = true;
  72946. _this._currentRefreshId = -1;
  72947. _this._refreshRate = 1;
  72948. _this._vertexBuffers = {};
  72949. _this._uniforms = new Array();
  72950. _this._samplers = new Array();
  72951. /** @hidden */
  72952. _this._textures = {};
  72953. _this._floats = {};
  72954. _this._ints = {};
  72955. _this._floatsArrays = {};
  72956. _this._colors3 = {};
  72957. _this._colors4 = {};
  72958. _this._vectors2 = {};
  72959. _this._vectors3 = {};
  72960. _this._matrices = {};
  72961. _this._fallbackTextureUsed = false;
  72962. scene = _this.getScene();
  72963. scene.proceduralTextures.push(_this);
  72964. _this._engine = scene.getEngine();
  72965. _this.name = name;
  72966. _this.isRenderTarget = true;
  72967. _this._size = size;
  72968. _this._generateMipMaps = generateMipMaps;
  72969. _this.setFragment(fragment);
  72970. _this._fallbackTexture = fallbackTexture;
  72971. if (isCube) {
  72972. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  72973. _this.setFloat("face", 0);
  72974. }
  72975. else {
  72976. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  72977. }
  72978. // VBO
  72979. var vertices = [];
  72980. vertices.push(1, 1);
  72981. vertices.push(-1, 1);
  72982. vertices.push(-1, -1);
  72983. vertices.push(1, -1);
  72984. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72985. _this._createIndexBuffer();
  72986. return _this;
  72987. }
  72988. ProceduralTexture.prototype._createIndexBuffer = function () {
  72989. var engine = this._engine;
  72990. // Indices
  72991. var indices = [];
  72992. indices.push(0);
  72993. indices.push(1);
  72994. indices.push(2);
  72995. indices.push(0);
  72996. indices.push(2);
  72997. indices.push(3);
  72998. this._indexBuffer = engine.createIndexBuffer(indices);
  72999. };
  73000. /** @hidden */
  73001. ProceduralTexture.prototype._rebuild = function () {
  73002. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73003. if (vb) {
  73004. vb._rebuild();
  73005. }
  73006. this._createIndexBuffer();
  73007. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  73008. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  73009. }
  73010. };
  73011. ProceduralTexture.prototype.reset = function () {
  73012. if (this._effect === undefined) {
  73013. return;
  73014. }
  73015. var engine = this._engine;
  73016. engine._releaseEffect(this._effect);
  73017. };
  73018. ProceduralTexture.prototype.isReady = function () {
  73019. var _this = this;
  73020. var engine = this._engine;
  73021. var shaders;
  73022. if (!this._fragment) {
  73023. return false;
  73024. }
  73025. if (this._fallbackTextureUsed) {
  73026. return true;
  73027. }
  73028. if (this._fragment.fragmentElement !== undefined) {
  73029. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  73030. }
  73031. else {
  73032. shaders = { vertex: "procedural", fragment: this._fragment };
  73033. }
  73034. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  73035. _this.releaseInternalTexture();
  73036. if (_this._fallbackTexture) {
  73037. _this._texture = _this._fallbackTexture._texture;
  73038. if (_this._texture) {
  73039. _this._texture.incrementReferences();
  73040. }
  73041. }
  73042. _this._fallbackTextureUsed = true;
  73043. });
  73044. return this._effect.isReady();
  73045. };
  73046. ProceduralTexture.prototype.resetRefreshCounter = function () {
  73047. this._currentRefreshId = -1;
  73048. };
  73049. ProceduralTexture.prototype.setFragment = function (fragment) {
  73050. this._fragment = fragment;
  73051. };
  73052. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  73053. get: function () {
  73054. return this._refreshRate;
  73055. },
  73056. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  73057. set: function (value) {
  73058. this._refreshRate = value;
  73059. this.resetRefreshCounter();
  73060. },
  73061. enumerable: true,
  73062. configurable: true
  73063. });
  73064. /** @hidden */
  73065. ProceduralTexture.prototype._shouldRender = function () {
  73066. if (!this.isEnabled || !this.isReady() || !this._texture) {
  73067. return false;
  73068. }
  73069. if (this._fallbackTextureUsed) {
  73070. return false;
  73071. }
  73072. if (this._currentRefreshId === -1) { // At least render once
  73073. this._currentRefreshId = 1;
  73074. return true;
  73075. }
  73076. if (this.refreshRate === this._currentRefreshId) {
  73077. this._currentRefreshId = 1;
  73078. return true;
  73079. }
  73080. this._currentRefreshId++;
  73081. return false;
  73082. };
  73083. ProceduralTexture.prototype.getRenderSize = function () {
  73084. return this._size;
  73085. };
  73086. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  73087. if (this._fallbackTextureUsed) {
  73088. return;
  73089. }
  73090. this.releaseInternalTexture();
  73091. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  73092. // Update properties
  73093. this._size = size;
  73094. this._generateMipMaps = generateMipMaps;
  73095. };
  73096. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  73097. if (this._uniforms.indexOf(uniformName) === -1) {
  73098. this._uniforms.push(uniformName);
  73099. }
  73100. };
  73101. ProceduralTexture.prototype.setTexture = function (name, texture) {
  73102. if (this._samplers.indexOf(name) === -1) {
  73103. this._samplers.push(name);
  73104. }
  73105. this._textures[name] = texture;
  73106. return this;
  73107. };
  73108. ProceduralTexture.prototype.setFloat = function (name, value) {
  73109. this._checkUniform(name);
  73110. this._floats[name] = value;
  73111. return this;
  73112. };
  73113. /**
  73114. * Set the value of an uniform to an integer value
  73115. * @param name defines the name of the uniform
  73116. * @param value defines the value to set
  73117. * @returns the current procedural texture
  73118. */
  73119. ProceduralTexture.prototype.setInt = function (name, value) {
  73120. this._checkUniform(name);
  73121. this._ints[name] = value;
  73122. return this;
  73123. };
  73124. ProceduralTexture.prototype.setFloats = function (name, value) {
  73125. this._checkUniform(name);
  73126. this._floatsArrays[name] = value;
  73127. return this;
  73128. };
  73129. ProceduralTexture.prototype.setColor3 = function (name, value) {
  73130. this._checkUniform(name);
  73131. this._colors3[name] = value;
  73132. return this;
  73133. };
  73134. ProceduralTexture.prototype.setColor4 = function (name, value) {
  73135. this._checkUniform(name);
  73136. this._colors4[name] = value;
  73137. return this;
  73138. };
  73139. ProceduralTexture.prototype.setVector2 = function (name, value) {
  73140. this._checkUniform(name);
  73141. this._vectors2[name] = value;
  73142. return this;
  73143. };
  73144. ProceduralTexture.prototype.setVector3 = function (name, value) {
  73145. this._checkUniform(name);
  73146. this._vectors3[name] = value;
  73147. return this;
  73148. };
  73149. ProceduralTexture.prototype.setMatrix = function (name, value) {
  73150. this._checkUniform(name);
  73151. this._matrices[name] = value;
  73152. return this;
  73153. };
  73154. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  73155. var scene = this.getScene();
  73156. if (!scene) {
  73157. return;
  73158. }
  73159. var engine = this._engine;
  73160. // Render
  73161. engine.enableEffect(this._effect);
  73162. engine.setState(false);
  73163. // Texture
  73164. for (var name in this._textures) {
  73165. this._effect.setTexture(name, this._textures[name]);
  73166. }
  73167. // Float
  73168. for (name in this._ints) {
  73169. this._effect.setInt(name, this._ints[name]);
  73170. }
  73171. // Float
  73172. for (name in this._floats) {
  73173. this._effect.setFloat(name, this._floats[name]);
  73174. }
  73175. // Floats
  73176. for (name in this._floatsArrays) {
  73177. this._effect.setArray(name, this._floatsArrays[name]);
  73178. }
  73179. // Color3
  73180. for (name in this._colors3) {
  73181. this._effect.setColor3(name, this._colors3[name]);
  73182. }
  73183. // Color4
  73184. for (name in this._colors4) {
  73185. var color = this._colors4[name];
  73186. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  73187. }
  73188. // Vector2
  73189. for (name in this._vectors2) {
  73190. this._effect.setVector2(name, this._vectors2[name]);
  73191. }
  73192. // Vector3
  73193. for (name in this._vectors3) {
  73194. this._effect.setVector3(name, this._vectors3[name]);
  73195. }
  73196. // Matrix
  73197. for (name in this._matrices) {
  73198. this._effect.setMatrix(name, this._matrices[name]);
  73199. }
  73200. if (!this._texture) {
  73201. return;
  73202. }
  73203. if (this.isCube) {
  73204. for (var face = 0; face < 6; face++) {
  73205. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  73206. // VBOs
  73207. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73208. this._effect.setFloat("face", face);
  73209. // Clear
  73210. engine.clear(scene.clearColor, true, true, true);
  73211. // Draw order
  73212. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73213. // Mipmaps
  73214. if (face === 5) {
  73215. engine.generateMipMapsForCubemap(this._texture);
  73216. }
  73217. }
  73218. }
  73219. else {
  73220. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  73221. // VBOs
  73222. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73223. // Clear
  73224. engine.clear(scene.clearColor, true, true, true);
  73225. // Draw order
  73226. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73227. }
  73228. // Unbind
  73229. engine.unBindFramebuffer(this._texture, this.isCube);
  73230. if (this.onGenerated) {
  73231. this.onGenerated();
  73232. }
  73233. };
  73234. ProceduralTexture.prototype.clone = function () {
  73235. var textureSize = this.getSize();
  73236. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  73237. // Base texture
  73238. newTexture.hasAlpha = this.hasAlpha;
  73239. newTexture.level = this.level;
  73240. // RenderTarget Texture
  73241. newTexture.coordinatesMode = this.coordinatesMode;
  73242. return newTexture;
  73243. };
  73244. ProceduralTexture.prototype.dispose = function () {
  73245. var scene = this.getScene();
  73246. if (!scene) {
  73247. return;
  73248. }
  73249. var index = scene.proceduralTextures.indexOf(this);
  73250. if (index >= 0) {
  73251. scene.proceduralTextures.splice(index, 1);
  73252. }
  73253. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73254. if (vertexBuffer) {
  73255. vertexBuffer.dispose();
  73256. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73257. }
  73258. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  73259. this._indexBuffer = null;
  73260. }
  73261. _super.prototype.dispose.call(this);
  73262. };
  73263. __decorate([
  73264. BABYLON.serialize()
  73265. ], ProceduralTexture.prototype, "_size", void 0);
  73266. __decorate([
  73267. BABYLON.serialize()
  73268. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  73269. __decorate([
  73270. BABYLON.serialize()
  73271. ], ProceduralTexture.prototype, "isEnabled", void 0);
  73272. __decorate([
  73273. BABYLON.serialize()
  73274. ], ProceduralTexture.prototype, "refreshRate", null);
  73275. return ProceduralTexture;
  73276. }(BABYLON.Texture));
  73277. BABYLON.ProceduralTexture = ProceduralTexture;
  73278. })(BABYLON || (BABYLON = {}));
  73279. //# sourceMappingURL=babylon.proceduralTexture.js.map
  73280. var BABYLON;
  73281. (function (BABYLON) {
  73282. var CustomProceduralTexture = /** @class */ (function (_super) {
  73283. __extends(CustomProceduralTexture, _super);
  73284. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  73285. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  73286. _this._animate = true;
  73287. _this._time = 0;
  73288. _this._texturePath = texturePath;
  73289. //Try to load json
  73290. _this.loadJson(texturePath);
  73291. _this.refreshRate = 1;
  73292. return _this;
  73293. }
  73294. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  73295. var _this = this;
  73296. var noConfigFile = function () {
  73297. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  73298. try {
  73299. _this.setFragment(_this._texturePath);
  73300. }
  73301. catch (ex) {
  73302. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  73303. }
  73304. };
  73305. var configFileUrl = jsonUrl + "/config.json";
  73306. var xhr = new XMLHttpRequest();
  73307. xhr.open("GET", configFileUrl, true);
  73308. xhr.addEventListener("load", function () {
  73309. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73310. try {
  73311. _this._config = JSON.parse(xhr.response);
  73312. _this.updateShaderUniforms();
  73313. _this.updateTextures();
  73314. _this.setFragment(_this._texturePath + "/custom");
  73315. _this._animate = _this._config.animate;
  73316. _this.refreshRate = _this._config.refreshrate;
  73317. }
  73318. catch (ex) {
  73319. noConfigFile();
  73320. }
  73321. }
  73322. else {
  73323. noConfigFile();
  73324. }
  73325. }, false);
  73326. xhr.addEventListener("error", function () {
  73327. noConfigFile();
  73328. }, false);
  73329. try {
  73330. xhr.send();
  73331. }
  73332. catch (ex) {
  73333. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  73334. }
  73335. };
  73336. CustomProceduralTexture.prototype.isReady = function () {
  73337. if (!_super.prototype.isReady.call(this)) {
  73338. return false;
  73339. }
  73340. for (var name in this._textures) {
  73341. var texture = this._textures[name];
  73342. if (!texture.isReady()) {
  73343. return false;
  73344. }
  73345. }
  73346. return true;
  73347. };
  73348. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  73349. var scene = this.getScene();
  73350. if (this._animate && scene) {
  73351. this._time += scene.getAnimationRatio() * 0.03;
  73352. this.updateShaderUniforms();
  73353. }
  73354. _super.prototype.render.call(this, useCameraPostProcess);
  73355. };
  73356. CustomProceduralTexture.prototype.updateTextures = function () {
  73357. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  73358. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  73359. }
  73360. };
  73361. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  73362. if (this._config) {
  73363. for (var j = 0; j < this._config.uniforms.length; j++) {
  73364. var uniform = this._config.uniforms[j];
  73365. switch (uniform.type) {
  73366. case "float":
  73367. this.setFloat(uniform.name, uniform.value);
  73368. break;
  73369. case "color3":
  73370. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  73371. break;
  73372. case "color4":
  73373. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  73374. break;
  73375. case "vector2":
  73376. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  73377. break;
  73378. case "vector3":
  73379. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  73380. break;
  73381. }
  73382. }
  73383. }
  73384. this.setFloat("time", this._time);
  73385. };
  73386. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  73387. get: function () {
  73388. return this._animate;
  73389. },
  73390. set: function (value) {
  73391. this._animate = value;
  73392. },
  73393. enumerable: true,
  73394. configurable: true
  73395. });
  73396. return CustomProceduralTexture;
  73397. }(BABYLON.ProceduralTexture));
  73398. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  73399. })(BABYLON || (BABYLON = {}));
  73400. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  73401. var BABYLON;
  73402. (function (BABYLON) {
  73403. var FreeCameraGamepadInput = /** @class */ (function () {
  73404. function FreeCameraGamepadInput() {
  73405. this.gamepadAngularSensibility = 200;
  73406. this.gamepadMoveSensibility = 40;
  73407. // private members
  73408. this._cameraTransform = BABYLON.Matrix.Identity();
  73409. this._deltaTransform = BABYLON.Vector3.Zero();
  73410. this._vector3 = BABYLON.Vector3.Zero();
  73411. this._vector2 = BABYLON.Vector2.Zero();
  73412. }
  73413. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73414. var _this = this;
  73415. var manager = this.camera.getScene().gamepadManager;
  73416. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73417. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73418. // prioritize XBOX gamepads.
  73419. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73420. _this.gamepad = gamepad;
  73421. }
  73422. }
  73423. });
  73424. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73425. if (_this.gamepad === gamepad) {
  73426. _this.gamepad = null;
  73427. }
  73428. });
  73429. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73430. };
  73431. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  73432. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73433. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73434. this.gamepad = null;
  73435. };
  73436. FreeCameraGamepadInput.prototype.checkInputs = function () {
  73437. if (this.gamepad && this.gamepad.leftStick) {
  73438. var camera = this.camera;
  73439. var LSValues = this.gamepad.leftStick;
  73440. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  73441. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73442. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  73443. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  73444. var RSValues = this.gamepad.rightStick;
  73445. if (RSValues) {
  73446. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  73447. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  73448. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  73449. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  73450. }
  73451. else {
  73452. RSValues = { x: 0, y: 0 };
  73453. }
  73454. if (!camera.rotationQuaternion) {
  73455. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  73456. }
  73457. else {
  73458. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  73459. }
  73460. var speed = camera._computeLocalCameraSpeed() * 50.0;
  73461. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  73462. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  73463. camera.cameraDirection.addInPlace(this._deltaTransform);
  73464. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  73465. camera.cameraRotation.addInPlace(this._vector2);
  73466. }
  73467. };
  73468. FreeCameraGamepadInput.prototype.getClassName = function () {
  73469. return "FreeCameraGamepadInput";
  73470. };
  73471. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  73472. return "gamepad";
  73473. };
  73474. __decorate([
  73475. BABYLON.serialize()
  73476. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  73477. __decorate([
  73478. BABYLON.serialize()
  73479. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73480. return FreeCameraGamepadInput;
  73481. }());
  73482. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  73483. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  73484. })(BABYLON || (BABYLON = {}));
  73485. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  73486. var BABYLON;
  73487. (function (BABYLON) {
  73488. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  73489. function ArcRotateCameraGamepadInput() {
  73490. this.gamepadRotationSensibility = 80;
  73491. this.gamepadMoveSensibility = 40;
  73492. }
  73493. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73494. var _this = this;
  73495. var manager = this.camera.getScene().gamepadManager;
  73496. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73497. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73498. // prioritize XBOX gamepads.
  73499. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73500. _this.gamepad = gamepad;
  73501. }
  73502. }
  73503. });
  73504. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73505. if (_this.gamepad === gamepad) {
  73506. _this.gamepad = null;
  73507. }
  73508. });
  73509. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73510. };
  73511. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  73512. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73513. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73514. this.gamepad = null;
  73515. };
  73516. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  73517. if (this.gamepad) {
  73518. var camera = this.camera;
  73519. var RSValues = this.gamepad.rightStick;
  73520. if (RSValues) {
  73521. if (RSValues.x != 0) {
  73522. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  73523. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  73524. camera.inertialAlphaOffset += normalizedRX;
  73525. }
  73526. }
  73527. if (RSValues.y != 0) {
  73528. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  73529. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  73530. camera.inertialBetaOffset += normalizedRY;
  73531. }
  73532. }
  73533. }
  73534. var LSValues = this.gamepad.leftStick;
  73535. if (LSValues && LSValues.y != 0) {
  73536. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73537. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  73538. this.camera.inertialRadiusOffset -= normalizedLY;
  73539. }
  73540. }
  73541. }
  73542. };
  73543. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  73544. return "ArcRotateCameraGamepadInput";
  73545. };
  73546. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  73547. return "gamepad";
  73548. };
  73549. __decorate([
  73550. BABYLON.serialize()
  73551. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  73552. __decorate([
  73553. BABYLON.serialize()
  73554. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73555. return ArcRotateCameraGamepadInput;
  73556. }());
  73557. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  73558. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  73559. })(BABYLON || (BABYLON = {}));
  73560. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  73561. var BABYLON;
  73562. (function (BABYLON) {
  73563. var GamepadManager = /** @class */ (function () {
  73564. function GamepadManager(_scene) {
  73565. var _this = this;
  73566. this._scene = _scene;
  73567. this._babylonGamepads = [];
  73568. this._oneGamepadConnected = false;
  73569. /** @hidden */
  73570. this._isMonitoring = false;
  73571. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  73572. if (!BABYLON.Tools.IsWindowObjectExist()) {
  73573. this._gamepadEventSupported = false;
  73574. }
  73575. else {
  73576. this._gamepadEventSupported = 'GamepadEvent' in window;
  73577. this._gamepadSupport = (navigator.getGamepads ||
  73578. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  73579. }
  73580. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  73581. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  73582. for (var i in _this._babylonGamepads) {
  73583. var gamepad = _this._babylonGamepads[i];
  73584. if (gamepad && gamepad._isConnected) {
  73585. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  73586. }
  73587. }
  73588. });
  73589. this._onGamepadConnectedEvent = function (evt) {
  73590. var gamepad = evt.gamepad;
  73591. if (gamepad.index in _this._babylonGamepads) {
  73592. if (_this._babylonGamepads[gamepad.index].isConnected) {
  73593. return;
  73594. }
  73595. }
  73596. var newGamepad;
  73597. if (_this._babylonGamepads[gamepad.index]) {
  73598. newGamepad = _this._babylonGamepads[gamepad.index];
  73599. newGamepad.browserGamepad = gamepad;
  73600. newGamepad._isConnected = true;
  73601. }
  73602. else {
  73603. newGamepad = _this._addNewGamepad(gamepad);
  73604. }
  73605. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73606. _this._startMonitoringGamepads();
  73607. };
  73608. this._onGamepadDisconnectedEvent = function (evt) {
  73609. var gamepad = evt.gamepad;
  73610. // Remove the gamepad from the list of gamepads to monitor.
  73611. for (var i in _this._babylonGamepads) {
  73612. if (_this._babylonGamepads[i].index === gamepad.index) {
  73613. var disconnectedGamepad = _this._babylonGamepads[i];
  73614. disconnectedGamepad._isConnected = false;
  73615. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  73616. break;
  73617. }
  73618. }
  73619. };
  73620. if (this._gamepadSupport) {
  73621. //first add already-connected gamepads
  73622. this._updateGamepadObjects();
  73623. if (this._babylonGamepads.length) {
  73624. this._startMonitoringGamepads();
  73625. }
  73626. // Checking if the gamepad connected event is supported (like in Firefox)
  73627. if (this._gamepadEventSupported) {
  73628. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  73629. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  73630. }
  73631. else {
  73632. this._startMonitoringGamepads();
  73633. }
  73634. }
  73635. }
  73636. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  73637. get: function () {
  73638. return this._babylonGamepads;
  73639. },
  73640. enumerable: true,
  73641. configurable: true
  73642. });
  73643. GamepadManager.prototype.getGamepadByType = function (type) {
  73644. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  73645. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  73646. var gamepad = _a[_i];
  73647. if (gamepad && gamepad.type === type) {
  73648. return gamepad;
  73649. }
  73650. }
  73651. return null;
  73652. };
  73653. GamepadManager.prototype.dispose = function () {
  73654. if (this._gamepadEventSupported) {
  73655. if (this._onGamepadConnectedEvent) {
  73656. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  73657. }
  73658. if (this._onGamepadDisconnectedEvent) {
  73659. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  73660. }
  73661. this._onGamepadConnectedEvent = null;
  73662. this._onGamepadDisconnectedEvent = null;
  73663. }
  73664. this._babylonGamepads.forEach(function (gamepad) {
  73665. gamepad.dispose();
  73666. });
  73667. this.onGamepadConnectedObservable.clear();
  73668. this.onGamepadDisconnectedObservable.clear();
  73669. this._oneGamepadConnected = false;
  73670. this._stopMonitoringGamepads();
  73671. this._babylonGamepads = [];
  73672. };
  73673. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  73674. if (!this._oneGamepadConnected) {
  73675. this._oneGamepadConnected = true;
  73676. }
  73677. var newGamepad;
  73678. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  73679. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  73680. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  73681. }
  73682. // if pose is supported, use the (WebVR) pose enabled controller
  73683. else if (gamepad.pose) {
  73684. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  73685. }
  73686. else {
  73687. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  73688. }
  73689. this._babylonGamepads[newGamepad.index] = newGamepad;
  73690. return newGamepad;
  73691. };
  73692. GamepadManager.prototype._startMonitoringGamepads = function () {
  73693. if (!this._isMonitoring) {
  73694. this._isMonitoring = true;
  73695. //back-comp
  73696. if (!this._scene) {
  73697. this._checkGamepadsStatus();
  73698. }
  73699. }
  73700. };
  73701. GamepadManager.prototype._stopMonitoringGamepads = function () {
  73702. this._isMonitoring = false;
  73703. };
  73704. /** @hidden */
  73705. GamepadManager.prototype._checkGamepadsStatus = function () {
  73706. var _this = this;
  73707. // Hack to be compatible Chrome
  73708. this._updateGamepadObjects();
  73709. for (var i in this._babylonGamepads) {
  73710. var gamepad = this._babylonGamepads[i];
  73711. if (!gamepad || !gamepad.isConnected) {
  73712. continue;
  73713. }
  73714. gamepad.update();
  73715. }
  73716. if (this._isMonitoring && !this._scene) {
  73717. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  73718. }
  73719. };
  73720. // This function is called only on Chrome, which does not properly support
  73721. // connection/disconnection events and forces you to recopy again the gamepad object
  73722. GamepadManager.prototype._updateGamepadObjects = function () {
  73723. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  73724. for (var i = 0; i < gamepads.length; i++) {
  73725. var gamepad = gamepads[i];
  73726. if (gamepad) {
  73727. if (!this._babylonGamepads[gamepad.index]) {
  73728. var newGamepad = this._addNewGamepad(gamepad);
  73729. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73730. }
  73731. else {
  73732. // Forced to copy again this object for Chrome for unknown reason
  73733. this._babylonGamepads[i].browserGamepad = gamepad;
  73734. if (!this._babylonGamepads[i].isConnected) {
  73735. this._babylonGamepads[i]._isConnected = true;
  73736. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  73737. }
  73738. }
  73739. }
  73740. }
  73741. };
  73742. return GamepadManager;
  73743. }());
  73744. BABYLON.GamepadManager = GamepadManager;
  73745. })(BABYLON || (BABYLON = {}));
  73746. //# sourceMappingURL=babylon.gamepadManager.js.map
  73747. var BABYLON;
  73748. (function (BABYLON) {
  73749. var StickValues = /** @class */ (function () {
  73750. function StickValues(x, y) {
  73751. this.x = x;
  73752. this.y = y;
  73753. }
  73754. return StickValues;
  73755. }());
  73756. BABYLON.StickValues = StickValues;
  73757. var Gamepad = /** @class */ (function () {
  73758. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  73759. if (leftStickX === void 0) { leftStickX = 0; }
  73760. if (leftStickY === void 0) { leftStickY = 1; }
  73761. if (rightStickX === void 0) { rightStickX = 2; }
  73762. if (rightStickY === void 0) { rightStickY = 3; }
  73763. this.id = id;
  73764. this.index = index;
  73765. this.browserGamepad = browserGamepad;
  73766. this._leftStick = { x: 0, y: 0 };
  73767. this._rightStick = { x: 0, y: 0 };
  73768. /** @hidden */
  73769. this._isConnected = true;
  73770. this._invertLeftStickY = false;
  73771. this.type = Gamepad.GAMEPAD;
  73772. this._leftStickAxisX = leftStickX;
  73773. this._leftStickAxisY = leftStickY;
  73774. this._rightStickAxisX = rightStickX;
  73775. this._rightStickAxisY = rightStickY;
  73776. if (this.browserGamepad.axes.length >= 2) {
  73777. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  73778. }
  73779. if (this.browserGamepad.axes.length >= 4) {
  73780. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  73781. }
  73782. }
  73783. Object.defineProperty(Gamepad.prototype, "isConnected", {
  73784. get: function () {
  73785. return this._isConnected;
  73786. },
  73787. enumerable: true,
  73788. configurable: true
  73789. });
  73790. Gamepad.prototype.onleftstickchanged = function (callback) {
  73791. this._onleftstickchanged = callback;
  73792. };
  73793. Gamepad.prototype.onrightstickchanged = function (callback) {
  73794. this._onrightstickchanged = callback;
  73795. };
  73796. Object.defineProperty(Gamepad.prototype, "leftStick", {
  73797. get: function () {
  73798. return this._leftStick;
  73799. },
  73800. set: function (newValues) {
  73801. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  73802. this._onleftstickchanged(newValues);
  73803. }
  73804. this._leftStick = newValues;
  73805. },
  73806. enumerable: true,
  73807. configurable: true
  73808. });
  73809. Object.defineProperty(Gamepad.prototype, "rightStick", {
  73810. get: function () {
  73811. return this._rightStick;
  73812. },
  73813. set: function (newValues) {
  73814. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  73815. this._onrightstickchanged(newValues);
  73816. }
  73817. this._rightStick = newValues;
  73818. },
  73819. enumerable: true,
  73820. configurable: true
  73821. });
  73822. Gamepad.prototype.update = function () {
  73823. if (this._leftStick) {
  73824. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  73825. if (this._invertLeftStickY) {
  73826. this.leftStick.y *= -1;
  73827. }
  73828. }
  73829. if (this._rightStick) {
  73830. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  73831. }
  73832. };
  73833. Gamepad.prototype.dispose = function () {
  73834. };
  73835. Gamepad.GAMEPAD = 0;
  73836. Gamepad.GENERIC = 1;
  73837. Gamepad.XBOX = 2;
  73838. Gamepad.POSE_ENABLED = 3;
  73839. return Gamepad;
  73840. }());
  73841. BABYLON.Gamepad = Gamepad;
  73842. var GenericPad = /** @class */ (function (_super) {
  73843. __extends(GenericPad, _super);
  73844. function GenericPad(id, index, browserGamepad) {
  73845. var _this = _super.call(this, id, index, browserGamepad) || this;
  73846. _this.onButtonDownObservable = new BABYLON.Observable();
  73847. _this.onButtonUpObservable = new BABYLON.Observable();
  73848. _this.type = Gamepad.GENERIC;
  73849. _this._buttons = new Array(browserGamepad.buttons.length);
  73850. return _this;
  73851. }
  73852. GenericPad.prototype.onbuttondown = function (callback) {
  73853. this._onbuttondown = callback;
  73854. };
  73855. GenericPad.prototype.onbuttonup = function (callback) {
  73856. this._onbuttonup = callback;
  73857. };
  73858. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  73859. if (newValue !== currentValue) {
  73860. if (newValue === 1) {
  73861. if (this._onbuttondown) {
  73862. this._onbuttondown(buttonIndex);
  73863. }
  73864. this.onButtonDownObservable.notifyObservers(buttonIndex);
  73865. }
  73866. if (newValue === 0) {
  73867. if (this._onbuttonup) {
  73868. this._onbuttonup(buttonIndex);
  73869. }
  73870. this.onButtonUpObservable.notifyObservers(buttonIndex);
  73871. }
  73872. }
  73873. return newValue;
  73874. };
  73875. GenericPad.prototype.update = function () {
  73876. _super.prototype.update.call(this);
  73877. for (var index = 0; index < this._buttons.length; index++) {
  73878. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  73879. }
  73880. };
  73881. GenericPad.prototype.dispose = function () {
  73882. _super.prototype.dispose.call(this);
  73883. this.onButtonDownObservable.clear();
  73884. this.onButtonUpObservable.clear();
  73885. };
  73886. return GenericPad;
  73887. }(Gamepad));
  73888. BABYLON.GenericPad = GenericPad;
  73889. })(BABYLON || (BABYLON = {}));
  73890. //# sourceMappingURL=babylon.gamepad.js.map
  73891. var BABYLON;
  73892. (function (BABYLON) {
  73893. /**
  73894. * Defines supported buttons for XBox360 compatible gamepads
  73895. */
  73896. var Xbox360Button;
  73897. (function (Xbox360Button) {
  73898. /** A */
  73899. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  73900. /** B */
  73901. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  73902. /** X */
  73903. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  73904. /** Y */
  73905. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  73906. /** Start */
  73907. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  73908. /** Back */
  73909. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  73910. /** Left button */
  73911. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  73912. /** Right button */
  73913. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  73914. /** Left stick */
  73915. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  73916. /** Right stick */
  73917. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  73918. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  73919. /** Defines values for XBox360 DPad */
  73920. var Xbox360Dpad;
  73921. (function (Xbox360Dpad) {
  73922. /** Up */
  73923. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  73924. /** Down */
  73925. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  73926. /** Left */
  73927. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  73928. /** Right */
  73929. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  73930. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  73931. /**
  73932. * Defines a XBox360 gamepad
  73933. */
  73934. var Xbox360Pad = /** @class */ (function (_super) {
  73935. __extends(Xbox360Pad, _super);
  73936. /**
  73937. * Creates a new XBox360 gamepad object
  73938. * @param id defines the id of this gamepad
  73939. * @param index defines its index
  73940. * @param gamepad defines the internal HTML gamepad object
  73941. * @param xboxOne defines if it is a XBox One gamepad
  73942. */
  73943. function Xbox360Pad(id, index, gamepad, xboxOne) {
  73944. if (xboxOne === void 0) { xboxOne = false; }
  73945. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  73946. _this._leftTrigger = 0;
  73947. _this._rightTrigger = 0;
  73948. /** Observable raised when a button is pressed */
  73949. _this.onButtonDownObservable = new BABYLON.Observable();
  73950. /** Observable raised when a button is released */
  73951. _this.onButtonUpObservable = new BABYLON.Observable();
  73952. /** Observable raised when a pad is pressed */
  73953. _this.onPadDownObservable = new BABYLON.Observable();
  73954. /** Observable raised when a pad is released */
  73955. _this.onPadUpObservable = new BABYLON.Observable();
  73956. _this._buttonA = 0;
  73957. _this._buttonB = 0;
  73958. _this._buttonX = 0;
  73959. _this._buttonY = 0;
  73960. _this._buttonBack = 0;
  73961. _this._buttonStart = 0;
  73962. _this._buttonLB = 0;
  73963. _this._buttonRB = 0;
  73964. _this._buttonLeftStick = 0;
  73965. _this._buttonRightStick = 0;
  73966. _this._dPadUp = 0;
  73967. _this._dPadDown = 0;
  73968. _this._dPadLeft = 0;
  73969. _this._dPadRight = 0;
  73970. _this._isXboxOnePad = false;
  73971. _this.type = BABYLON.Gamepad.XBOX;
  73972. _this._isXboxOnePad = xboxOne;
  73973. return _this;
  73974. }
  73975. /**
  73976. * Defines the callback to call when left trigger is pressed
  73977. * @param callback defines the callback to use
  73978. */
  73979. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  73980. this._onlefttriggerchanged = callback;
  73981. };
  73982. /**
  73983. * Defines the callback to call when right trigger is pressed
  73984. * @param callback defines the callback to use
  73985. */
  73986. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  73987. this._onrighttriggerchanged = callback;
  73988. };
  73989. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  73990. /**
  73991. * Gets or sets left trigger value
  73992. */
  73993. get: function () {
  73994. return this._leftTrigger;
  73995. },
  73996. set: function (newValue) {
  73997. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  73998. this._onlefttriggerchanged(newValue);
  73999. }
  74000. this._leftTrigger = newValue;
  74001. },
  74002. enumerable: true,
  74003. configurable: true
  74004. });
  74005. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  74006. /**
  74007. * Gets or sets right trigger value
  74008. */
  74009. get: function () {
  74010. return this._rightTrigger;
  74011. },
  74012. set: function (newValue) {
  74013. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  74014. this._onrighttriggerchanged(newValue);
  74015. }
  74016. this._rightTrigger = newValue;
  74017. },
  74018. enumerable: true,
  74019. configurable: true
  74020. });
  74021. /**
  74022. * Defines the callback to call when a button is pressed
  74023. * @param callback defines the callback to use
  74024. */
  74025. Xbox360Pad.prototype.onbuttondown = function (callback) {
  74026. this._onbuttondown = callback;
  74027. };
  74028. /**
  74029. * Defines the callback to call when a button is released
  74030. * @param callback defines the callback to use
  74031. */
  74032. Xbox360Pad.prototype.onbuttonup = function (callback) {
  74033. this._onbuttonup = callback;
  74034. };
  74035. /**
  74036. * Defines the callback to call when a pad is pressed
  74037. * @param callback defines the callback to use
  74038. */
  74039. Xbox360Pad.prototype.ondpaddown = function (callback) {
  74040. this._ondpaddown = callback;
  74041. };
  74042. /**
  74043. * Defines the callback to call when a pad is released
  74044. * @param callback defines the callback to use
  74045. */
  74046. Xbox360Pad.prototype.ondpadup = function (callback) {
  74047. this._ondpadup = callback;
  74048. };
  74049. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  74050. if (newValue !== currentValue) {
  74051. if (newValue === 1) {
  74052. if (this._onbuttondown) {
  74053. this._onbuttondown(buttonType);
  74054. }
  74055. this.onButtonDownObservable.notifyObservers(buttonType);
  74056. }
  74057. if (newValue === 0) {
  74058. if (this._onbuttonup) {
  74059. this._onbuttonup(buttonType);
  74060. }
  74061. this.onButtonUpObservable.notifyObservers(buttonType);
  74062. }
  74063. }
  74064. return newValue;
  74065. };
  74066. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  74067. if (newValue !== currentValue) {
  74068. if (newValue === 1) {
  74069. if (this._ondpaddown) {
  74070. this._ondpaddown(buttonType);
  74071. }
  74072. this.onPadDownObservable.notifyObservers(buttonType);
  74073. }
  74074. if (newValue === 0) {
  74075. if (this._ondpadup) {
  74076. this._ondpadup(buttonType);
  74077. }
  74078. this.onPadUpObservable.notifyObservers(buttonType);
  74079. }
  74080. }
  74081. return newValue;
  74082. };
  74083. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  74084. /** Gets or sets value of A button */
  74085. get: function () {
  74086. return this._buttonA;
  74087. },
  74088. set: function (value) {
  74089. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  74090. },
  74091. enumerable: true,
  74092. configurable: true
  74093. });
  74094. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  74095. /** Gets or sets value of B button */
  74096. get: function () {
  74097. return this._buttonB;
  74098. },
  74099. set: function (value) {
  74100. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  74101. },
  74102. enumerable: true,
  74103. configurable: true
  74104. });
  74105. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  74106. /** Gets or sets value of X button */
  74107. get: function () {
  74108. return this._buttonX;
  74109. },
  74110. set: function (value) {
  74111. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  74112. },
  74113. enumerable: true,
  74114. configurable: true
  74115. });
  74116. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  74117. /** Gets or sets value of Y button */
  74118. get: function () {
  74119. return this._buttonY;
  74120. },
  74121. set: function (value) {
  74122. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  74123. },
  74124. enumerable: true,
  74125. configurable: true
  74126. });
  74127. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  74128. /** Gets or sets value of Start button */
  74129. get: function () {
  74130. return this._buttonStart;
  74131. },
  74132. set: function (value) {
  74133. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  74134. },
  74135. enumerable: true,
  74136. configurable: true
  74137. });
  74138. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  74139. /** Gets or sets value of Back button */
  74140. get: function () {
  74141. return this._buttonBack;
  74142. },
  74143. set: function (value) {
  74144. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  74145. },
  74146. enumerable: true,
  74147. configurable: true
  74148. });
  74149. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  74150. /** Gets or sets value of Left button */
  74151. get: function () {
  74152. return this._buttonLB;
  74153. },
  74154. set: function (value) {
  74155. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  74156. },
  74157. enumerable: true,
  74158. configurable: true
  74159. });
  74160. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  74161. /** Gets or sets value of Right button */
  74162. get: function () {
  74163. return this._buttonRB;
  74164. },
  74165. set: function (value) {
  74166. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  74167. },
  74168. enumerable: true,
  74169. configurable: true
  74170. });
  74171. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  74172. /** Gets or sets value of left stick */
  74173. get: function () {
  74174. return this._buttonLeftStick;
  74175. },
  74176. set: function (value) {
  74177. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  74178. },
  74179. enumerable: true,
  74180. configurable: true
  74181. });
  74182. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  74183. /** Gets or sets value of right stick */
  74184. get: function () {
  74185. return this._buttonRightStick;
  74186. },
  74187. set: function (value) {
  74188. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  74189. },
  74190. enumerable: true,
  74191. configurable: true
  74192. });
  74193. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  74194. /** Gets or sets value of DPad up */
  74195. get: function () {
  74196. return this._dPadUp;
  74197. },
  74198. set: function (value) {
  74199. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  74200. },
  74201. enumerable: true,
  74202. configurable: true
  74203. });
  74204. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  74205. /** Gets or sets value of DPad down */
  74206. get: function () {
  74207. return this._dPadDown;
  74208. },
  74209. set: function (value) {
  74210. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  74211. },
  74212. enumerable: true,
  74213. configurable: true
  74214. });
  74215. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  74216. /** Gets or sets value of DPad left */
  74217. get: function () {
  74218. return this._dPadLeft;
  74219. },
  74220. set: function (value) {
  74221. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  74222. },
  74223. enumerable: true,
  74224. configurable: true
  74225. });
  74226. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  74227. /** Gets or sets value of DPad right */
  74228. get: function () {
  74229. return this._dPadRight;
  74230. },
  74231. set: function (value) {
  74232. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  74233. },
  74234. enumerable: true,
  74235. configurable: true
  74236. });
  74237. /**
  74238. * Force the gamepad to synchronize with device values
  74239. */
  74240. Xbox360Pad.prototype.update = function () {
  74241. _super.prototype.update.call(this);
  74242. if (this._isXboxOnePad) {
  74243. this.buttonA = this.browserGamepad.buttons[0].value;
  74244. this.buttonB = this.browserGamepad.buttons[1].value;
  74245. this.buttonX = this.browserGamepad.buttons[2].value;
  74246. this.buttonY = this.browserGamepad.buttons[3].value;
  74247. this.buttonLB = this.browserGamepad.buttons[4].value;
  74248. this.buttonRB = this.browserGamepad.buttons[5].value;
  74249. this.leftTrigger = this.browserGamepad.axes[2];
  74250. this.rightTrigger = this.browserGamepad.axes[5];
  74251. this.buttonBack = this.browserGamepad.buttons[9].value;
  74252. this.buttonStart = this.browserGamepad.buttons[8].value;
  74253. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  74254. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  74255. this.dPadUp = this.browserGamepad.buttons[11].value;
  74256. this.dPadDown = this.browserGamepad.buttons[12].value;
  74257. this.dPadLeft = this.browserGamepad.buttons[13].value;
  74258. this.dPadRight = this.browserGamepad.buttons[14].value;
  74259. }
  74260. else {
  74261. this.buttonA = this.browserGamepad.buttons[0].value;
  74262. this.buttonB = this.browserGamepad.buttons[1].value;
  74263. this.buttonX = this.browserGamepad.buttons[2].value;
  74264. this.buttonY = this.browserGamepad.buttons[3].value;
  74265. this.buttonLB = this.browserGamepad.buttons[4].value;
  74266. this.buttonRB = this.browserGamepad.buttons[5].value;
  74267. this.leftTrigger = this.browserGamepad.buttons[6].value;
  74268. this.rightTrigger = this.browserGamepad.buttons[7].value;
  74269. this.buttonBack = this.browserGamepad.buttons[8].value;
  74270. this.buttonStart = this.browserGamepad.buttons[9].value;
  74271. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  74272. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  74273. this.dPadUp = this.browserGamepad.buttons[12].value;
  74274. this.dPadDown = this.browserGamepad.buttons[13].value;
  74275. this.dPadLeft = this.browserGamepad.buttons[14].value;
  74276. this.dPadRight = this.browserGamepad.buttons[15].value;
  74277. }
  74278. };
  74279. Xbox360Pad.prototype.dispose = function () {
  74280. _super.prototype.dispose.call(this);
  74281. this.onButtonDownObservable.clear();
  74282. this.onButtonUpObservable.clear();
  74283. this.onPadDownObservable.clear();
  74284. this.onPadUpObservable.clear();
  74285. };
  74286. return Xbox360Pad;
  74287. }(BABYLON.Gamepad));
  74288. BABYLON.Xbox360Pad = Xbox360Pad;
  74289. })(BABYLON || (BABYLON = {}));
  74290. //# sourceMappingURL=babylon.xboxGamepad.js.map
  74291. var BABYLON;
  74292. (function (BABYLON) {
  74293. /**
  74294. * Defines the types of pose enabled controllers that are supported
  74295. */
  74296. var PoseEnabledControllerType;
  74297. (function (PoseEnabledControllerType) {
  74298. /**
  74299. * HTC Vive
  74300. */
  74301. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  74302. /**
  74303. * Oculus Rift
  74304. */
  74305. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  74306. /**
  74307. * Windows mixed reality
  74308. */
  74309. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  74310. /**
  74311. * Samsung gear VR
  74312. */
  74313. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  74314. /**
  74315. * Google Daydream
  74316. */
  74317. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  74318. /**
  74319. * Generic
  74320. */
  74321. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  74322. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  74323. /**
  74324. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  74325. */
  74326. var PoseEnabledControllerHelper = /** @class */ (function () {
  74327. function PoseEnabledControllerHelper() {
  74328. }
  74329. /**
  74330. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  74331. * @param vrGamepad the gamepad to initialized
  74332. * @returns a vr controller of the type the gamepad identified as
  74333. */
  74334. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  74335. // Oculus Touch
  74336. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  74337. return new BABYLON.OculusTouchController(vrGamepad);
  74338. }
  74339. // Windows Mixed Reality controllers
  74340. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  74341. return new BABYLON.WindowsMotionController(vrGamepad);
  74342. }
  74343. // HTC Vive
  74344. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  74345. return new BABYLON.ViveController(vrGamepad);
  74346. }
  74347. // Samsung/Oculus Gear VR or Oculus Go
  74348. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  74349. return new BABYLON.GearVRController(vrGamepad);
  74350. }
  74351. // Google Daydream
  74352. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  74353. return new BABYLON.DaydreamController(vrGamepad);
  74354. }
  74355. // Generic
  74356. else {
  74357. return new BABYLON.GenericController(vrGamepad);
  74358. }
  74359. };
  74360. return PoseEnabledControllerHelper;
  74361. }());
  74362. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  74363. /**
  74364. * Defines the PoseEnabledController object that contains state of a vr capable controller
  74365. */
  74366. var PoseEnabledController = /** @class */ (function (_super) {
  74367. __extends(PoseEnabledController, _super);
  74368. /**
  74369. * Creates a new PoseEnabledController from a gamepad
  74370. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  74371. */
  74372. function PoseEnabledController(browserGamepad) {
  74373. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  74374. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74375. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74376. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  74377. /**
  74378. * The device position in babylon space
  74379. */
  74380. _this.devicePosition = BABYLON.Vector3.Zero();
  74381. /**
  74382. * The device rotation in babylon space
  74383. */
  74384. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  74385. /**
  74386. * The scale factor of the device in babylon space
  74387. */
  74388. _this.deviceScaleFactor = 1;
  74389. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  74390. /**
  74391. * Internal, matrix used to convert room space to babylon space
  74392. * @hidden
  74393. */
  74394. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74395. /**
  74396. * Node to be used when casting a ray from the controller
  74397. * @hidden
  74398. */
  74399. _this._pointingPoseNode = null;
  74400. _this._workingMatrix = BABYLON.Matrix.Identity();
  74401. /**
  74402. * @hidden
  74403. */
  74404. _this._meshAttachedObservable = new BABYLON.Observable();
  74405. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  74406. _this.controllerType = PoseEnabledControllerType.GENERIC;
  74407. _this.position = BABYLON.Vector3.Zero();
  74408. _this.rotationQuaternion = new BABYLON.Quaternion();
  74409. _this._calculatedPosition = BABYLON.Vector3.Zero();
  74410. _this._calculatedRotation = new BABYLON.Quaternion();
  74411. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  74412. return _this;
  74413. }
  74414. /**
  74415. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  74416. */
  74417. PoseEnabledController.prototype.update = function () {
  74418. _super.prototype.update.call(this);
  74419. this._updatePoseAndMesh();
  74420. };
  74421. /**
  74422. * Updates only the pose device and mesh without doing any button event checking
  74423. */
  74424. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  74425. var pose = this.browserGamepad.pose;
  74426. this.updateFromDevice(pose);
  74427. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  74428. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  74429. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  74430. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  74431. if (this._mesh) {
  74432. this._mesh.position.copyFrom(this.devicePosition);
  74433. if (this._mesh.rotationQuaternion) {
  74434. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  74435. }
  74436. }
  74437. };
  74438. /**
  74439. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74440. * @param poseData raw pose fromthe device
  74441. */
  74442. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  74443. if (poseData) {
  74444. this.rawPose = poseData;
  74445. if (poseData.position) {
  74446. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  74447. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  74448. this._deviceRoomPosition.z *= -1;
  74449. }
  74450. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  74451. this._calculatedPosition.addInPlace(this.position);
  74452. }
  74453. var pose = this.rawPose;
  74454. if (poseData.orientation && pose.orientation) {
  74455. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  74456. if (this._mesh) {
  74457. if (this._mesh.getScene().useRightHandedSystem) {
  74458. this._deviceRoomRotationQuaternion.z *= -1;
  74459. this._deviceRoomRotationQuaternion.w *= -1;
  74460. }
  74461. else {
  74462. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  74463. }
  74464. }
  74465. // if the camera is set, rotate to the camera's rotation
  74466. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  74467. }
  74468. }
  74469. };
  74470. /**
  74471. * Attaches a mesh to the controller
  74472. * @param mesh the mesh to be attached
  74473. */
  74474. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  74475. if (this._mesh) {
  74476. this._mesh.parent = null;
  74477. }
  74478. this._mesh = mesh;
  74479. if (this._poseControlledCamera) {
  74480. this._mesh.parent = this._poseControlledCamera;
  74481. }
  74482. if (!this._mesh.rotationQuaternion) {
  74483. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  74484. }
  74485. // 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
  74486. this._updatePoseAndMesh();
  74487. if (this._pointingPoseNode) {
  74488. var parents = [];
  74489. var obj = this._pointingPoseNode;
  74490. while (obj.parent) {
  74491. parents.push(obj.parent);
  74492. obj = obj.parent;
  74493. }
  74494. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  74495. }
  74496. this._meshAttachedObservable.notifyObservers(mesh);
  74497. };
  74498. /**
  74499. * Attaches the controllers mesh to a camera
  74500. * @param camera the camera the mesh should be attached to
  74501. */
  74502. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  74503. this._poseControlledCamera = camera;
  74504. if (this._mesh) {
  74505. this._mesh.parent = this._poseControlledCamera;
  74506. }
  74507. };
  74508. /**
  74509. * Disposes of the controller
  74510. */
  74511. PoseEnabledController.prototype.dispose = function () {
  74512. if (this._mesh) {
  74513. this._mesh.dispose();
  74514. }
  74515. this._mesh = null;
  74516. _super.prototype.dispose.call(this);
  74517. };
  74518. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  74519. /**
  74520. * The mesh that is attached to the controller
  74521. */
  74522. get: function () {
  74523. return this._mesh;
  74524. },
  74525. enumerable: true,
  74526. configurable: true
  74527. });
  74528. /**
  74529. * Gets the ray of the controller in the direction the controller is pointing
  74530. * @param length the length the resulting ray should be
  74531. * @returns a ray in the direction the controller is pointing
  74532. */
  74533. PoseEnabledController.prototype.getForwardRay = function (length) {
  74534. if (length === void 0) { length = 100; }
  74535. if (!this.mesh) {
  74536. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  74537. }
  74538. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  74539. var origin = m.getTranslation();
  74540. var forward = new BABYLON.Vector3(0, 0, -1);
  74541. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  74542. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  74543. return new BABYLON.Ray(origin, direction, length);
  74544. };
  74545. /**
  74546. * Name of the child mesh that can be used to cast a ray from the controller
  74547. */
  74548. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  74549. return PoseEnabledController;
  74550. }(BABYLON.Gamepad));
  74551. BABYLON.PoseEnabledController = PoseEnabledController;
  74552. })(BABYLON || (BABYLON = {}));
  74553. //# sourceMappingURL=babylon.poseEnabledController.js.map
  74554. var BABYLON;
  74555. (function (BABYLON) {
  74556. /**
  74557. * Defines the WebVRController object that represents controllers tracked in 3D space
  74558. */
  74559. var WebVRController = /** @class */ (function (_super) {
  74560. __extends(WebVRController, _super);
  74561. /**
  74562. * Creates a new WebVRController from a gamepad
  74563. * @param vrGamepad the gamepad that the WebVRController should be created from
  74564. */
  74565. function WebVRController(vrGamepad) {
  74566. var _this = _super.call(this, vrGamepad) || this;
  74567. // Observables
  74568. /**
  74569. * Fired when the trigger state has changed
  74570. */
  74571. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  74572. /**
  74573. * Fired when the main button state has changed
  74574. */
  74575. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  74576. /**
  74577. * Fired when the secondary button state has changed
  74578. */
  74579. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  74580. /**
  74581. * Fired when the pad state has changed
  74582. */
  74583. _this.onPadStateChangedObservable = new BABYLON.Observable();
  74584. /**
  74585. * Fired when controllers stick values have changed
  74586. */
  74587. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  74588. /**
  74589. * X and Y axis corrisponding to the controllers joystick
  74590. */
  74591. _this.pad = { x: 0, y: 0 };
  74592. // avoid GC, store state in a tmp object
  74593. _this._changes = {
  74594. pressChanged: false,
  74595. touchChanged: false,
  74596. valueChanged: false,
  74597. changed: false
  74598. };
  74599. _this._buttons = new Array(vrGamepad.buttons.length);
  74600. _this.hand = vrGamepad.hand;
  74601. return _this;
  74602. }
  74603. /**
  74604. * Fired when a controller button's state has changed
  74605. * @param callback the callback containing the button that was modified
  74606. */
  74607. WebVRController.prototype.onButtonStateChange = function (callback) {
  74608. this._onButtonStateChange = callback;
  74609. };
  74610. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  74611. /**
  74612. * The default controller model for the controller
  74613. */
  74614. get: function () {
  74615. return this._defaultModel;
  74616. },
  74617. enumerable: true,
  74618. configurable: true
  74619. });
  74620. /**
  74621. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  74622. */
  74623. WebVRController.prototype.update = function () {
  74624. _super.prototype.update.call(this);
  74625. for (var index = 0; index < this._buttons.length; index++) {
  74626. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  74627. }
  74628. ;
  74629. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  74630. this.pad.x = this.leftStick.x;
  74631. this.pad.y = this.leftStick.y;
  74632. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  74633. }
  74634. };
  74635. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  74636. if (!newState) {
  74637. newState = {
  74638. pressed: false,
  74639. touched: false,
  74640. value: 0
  74641. };
  74642. }
  74643. if (!currentState) {
  74644. this._buttons[buttonIndex] = {
  74645. pressed: newState.pressed,
  74646. touched: newState.touched,
  74647. value: newState.value
  74648. };
  74649. return;
  74650. }
  74651. this._checkChanges(newState, currentState);
  74652. if (this._changes.changed) {
  74653. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  74654. this._handleButtonChange(buttonIndex, newState, this._changes);
  74655. }
  74656. this._buttons[buttonIndex].pressed = newState.pressed;
  74657. this._buttons[buttonIndex].touched = newState.touched;
  74658. // oculus triggers are never 0, thou not touched.
  74659. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  74660. };
  74661. WebVRController.prototype._checkChanges = function (newState, currentState) {
  74662. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  74663. this._changes.touchChanged = newState.touched !== currentState.touched;
  74664. this._changes.valueChanged = newState.value !== currentState.value;
  74665. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  74666. return this._changes;
  74667. };
  74668. /**
  74669. * Disposes of th webVRCOntroller
  74670. */
  74671. WebVRController.prototype.dispose = function () {
  74672. _super.prototype.dispose.call(this);
  74673. this.onTriggerStateChangedObservable.clear();
  74674. this.onMainButtonStateChangedObservable.clear();
  74675. this.onSecondaryButtonStateChangedObservable.clear();
  74676. this.onPadStateChangedObservable.clear();
  74677. this.onPadValuesChangedObservable.clear();
  74678. };
  74679. return WebVRController;
  74680. }(BABYLON.PoseEnabledController));
  74681. BABYLON.WebVRController = WebVRController;
  74682. })(BABYLON || (BABYLON = {}));
  74683. //# sourceMappingURL=babylon.webVRController.js.map
  74684. var BABYLON;
  74685. (function (BABYLON) {
  74686. /**
  74687. * Oculus Touch Controller
  74688. */
  74689. var OculusTouchController = /** @class */ (function (_super) {
  74690. __extends(OculusTouchController, _super);
  74691. /**
  74692. * Creates a new OculusTouchController from a gamepad
  74693. * @param vrGamepad the gamepad that the controller should be created from
  74694. */
  74695. function OculusTouchController(vrGamepad) {
  74696. var _this = _super.call(this, vrGamepad) || this;
  74697. /**
  74698. * Fired when the secondary trigger on this controller is modified
  74699. */
  74700. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  74701. /**
  74702. * Fired when the thumb rest on this controller is modified
  74703. */
  74704. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  74705. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  74706. return _this;
  74707. }
  74708. /**
  74709. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74710. * @param scene scene in which to add meshes
  74711. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74712. */
  74713. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74714. var _this = this;
  74715. var meshName;
  74716. // Hand
  74717. if (this.hand === 'left') {
  74718. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  74719. }
  74720. else { // Right is the default if no hand is specified
  74721. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  74722. }
  74723. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  74724. /*
  74725. Parent Mesh name: oculus_touch_left
  74726. - body
  74727. - trigger
  74728. - thumbstick
  74729. - grip
  74730. - button_y
  74731. - button_x
  74732. - button_enter
  74733. */
  74734. _this._defaultModel = newMeshes[1];
  74735. _this.attachToMesh(_this._defaultModel);
  74736. if (meshLoaded) {
  74737. meshLoaded(_this._defaultModel);
  74738. }
  74739. });
  74740. };
  74741. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  74742. /**
  74743. * Fired when the A button on this controller is modified
  74744. */
  74745. get: function () {
  74746. if (this.hand === 'right') {
  74747. return this.onMainButtonStateChangedObservable;
  74748. }
  74749. else {
  74750. throw new Error('No A button on left hand');
  74751. }
  74752. },
  74753. enumerable: true,
  74754. configurable: true
  74755. });
  74756. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  74757. /**
  74758. * Fired when the B button on this controller is modified
  74759. */
  74760. get: function () {
  74761. if (this.hand === 'right') {
  74762. return this.onSecondaryButtonStateChangedObservable;
  74763. }
  74764. else {
  74765. throw new Error('No B button on left hand');
  74766. }
  74767. },
  74768. enumerable: true,
  74769. configurable: true
  74770. });
  74771. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  74772. /**
  74773. * Fired when the X button on this controller is modified
  74774. */
  74775. get: function () {
  74776. if (this.hand === 'left') {
  74777. return this.onMainButtonStateChangedObservable;
  74778. }
  74779. else {
  74780. throw new Error('No X button on right hand');
  74781. }
  74782. },
  74783. enumerable: true,
  74784. configurable: true
  74785. });
  74786. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  74787. /**
  74788. * Fired when the Y button on this controller is modified
  74789. */
  74790. get: function () {
  74791. if (this.hand === 'left') {
  74792. return this.onSecondaryButtonStateChangedObservable;
  74793. }
  74794. else {
  74795. throw new Error('No Y button on right hand');
  74796. }
  74797. },
  74798. enumerable: true,
  74799. configurable: true
  74800. });
  74801. /**
  74802. * Called once for each button that changed state since the last frame
  74803. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  74804. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  74805. * 2) secondary trigger (same)
  74806. * 3) A (right) X (left), touch, pressed = value
  74807. * 4) B / Y
  74808. * 5) thumb rest
  74809. * @param buttonIdx Which button index changed
  74810. * @param state New state of the button
  74811. * @param changes Which properties on the state changed since last frame
  74812. */
  74813. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74814. var notifyObject = state; //{ state: state, changes: changes };
  74815. var triggerDirection = this.hand === 'right' ? -1 : 1;
  74816. switch (buttonIdx) {
  74817. case 0:
  74818. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  74819. return;
  74820. case 1: // index trigger
  74821. if (this._defaultModel) {
  74822. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  74823. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  74824. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  74825. }
  74826. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  74827. return;
  74828. case 2: // secondary trigger
  74829. if (this._defaultModel) {
  74830. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  74831. }
  74832. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  74833. return;
  74834. case 3:
  74835. if (this._defaultModel) {
  74836. if (notifyObject.pressed) {
  74837. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  74838. }
  74839. else {
  74840. (this._defaultModel.getChildren()[1]).position.y = 0;
  74841. }
  74842. }
  74843. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  74844. return;
  74845. case 4:
  74846. if (this._defaultModel) {
  74847. if (notifyObject.pressed) {
  74848. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  74849. }
  74850. else {
  74851. (this._defaultModel.getChildren()[2]).position.y = 0;
  74852. }
  74853. }
  74854. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  74855. return;
  74856. case 5:
  74857. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  74858. return;
  74859. }
  74860. };
  74861. /**
  74862. * Base Url for the controller model.
  74863. */
  74864. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  74865. /**
  74866. * File name for the left controller model.
  74867. */
  74868. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  74869. /**
  74870. * File name for the right controller model.
  74871. */
  74872. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  74873. return OculusTouchController;
  74874. }(BABYLON.WebVRController));
  74875. BABYLON.OculusTouchController = OculusTouchController;
  74876. })(BABYLON || (BABYLON = {}));
  74877. //# sourceMappingURL=babylon.oculusTouchController.js.map
  74878. var BABYLON;
  74879. (function (BABYLON) {
  74880. /**
  74881. * Vive Controller
  74882. */
  74883. var ViveController = /** @class */ (function (_super) {
  74884. __extends(ViveController, _super);
  74885. /**
  74886. * Creates a new ViveController from a gamepad
  74887. * @param vrGamepad the gamepad that the controller should be created from
  74888. */
  74889. function ViveController(vrGamepad) {
  74890. var _this = _super.call(this, vrGamepad) || this;
  74891. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  74892. _this._invertLeftStickY = true;
  74893. return _this;
  74894. }
  74895. /**
  74896. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74897. * @param scene scene in which to add meshes
  74898. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74899. */
  74900. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74901. var _this = this;
  74902. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  74903. /*
  74904. Parent Mesh name: ViveWand
  74905. - body
  74906. - r_gripper
  74907. - l_gripper
  74908. - menu_button
  74909. - system_button
  74910. - trackpad
  74911. - trigger
  74912. - LED
  74913. */
  74914. _this._defaultModel = newMeshes[1];
  74915. _this.attachToMesh(_this._defaultModel);
  74916. if (meshLoaded) {
  74917. meshLoaded(_this._defaultModel);
  74918. }
  74919. });
  74920. };
  74921. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  74922. /**
  74923. * Fired when the left button on this controller is modified
  74924. */
  74925. get: function () {
  74926. return this.onMainButtonStateChangedObservable;
  74927. },
  74928. enumerable: true,
  74929. configurable: true
  74930. });
  74931. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  74932. /**
  74933. * Fired when the right button on this controller is modified
  74934. */
  74935. get: function () {
  74936. return this.onMainButtonStateChangedObservable;
  74937. },
  74938. enumerable: true,
  74939. configurable: true
  74940. });
  74941. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  74942. /**
  74943. * Fired when the menu button on this controller is modified
  74944. */
  74945. get: function () {
  74946. return this.onSecondaryButtonStateChangedObservable;
  74947. },
  74948. enumerable: true,
  74949. configurable: true
  74950. });
  74951. /**
  74952. * Called once for each button that changed state since the last frame
  74953. * Vive mapping:
  74954. * 0: touchpad
  74955. * 1: trigger
  74956. * 2: left AND right buttons
  74957. * 3: menu button
  74958. * @param buttonIdx Which button index changed
  74959. * @param state New state of the button
  74960. * @param changes Which properties on the state changed since last frame
  74961. */
  74962. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74963. var notifyObject = state; //{ state: state, changes: changes };
  74964. switch (buttonIdx) {
  74965. case 0:
  74966. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  74967. return;
  74968. case 1: // index trigger
  74969. if (this._defaultModel) {
  74970. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  74971. }
  74972. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  74973. return;
  74974. case 2: // left AND right button
  74975. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  74976. return;
  74977. case 3:
  74978. if (this._defaultModel) {
  74979. if (notifyObject.pressed) {
  74980. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  74981. }
  74982. else {
  74983. (this._defaultModel.getChildren()[2]).position.y = 0;
  74984. }
  74985. }
  74986. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  74987. return;
  74988. }
  74989. };
  74990. /**
  74991. * Base Url for the controller model.
  74992. */
  74993. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  74994. /**
  74995. * File name for the controller model.
  74996. */
  74997. ViveController.MODEL_FILENAME = 'wand.babylon';
  74998. return ViveController;
  74999. }(BABYLON.WebVRController));
  75000. BABYLON.ViveController = ViveController;
  75001. })(BABYLON || (BABYLON = {}));
  75002. //# sourceMappingURL=babylon.viveController.js.map
  75003. var BABYLON;
  75004. (function (BABYLON) {
  75005. /**
  75006. * Generic Controller
  75007. */
  75008. var GenericController = /** @class */ (function (_super) {
  75009. __extends(GenericController, _super);
  75010. /**
  75011. * Creates a new GenericController from a gamepad
  75012. * @param vrGamepad the gamepad that the controller should be created from
  75013. */
  75014. function GenericController(vrGamepad) {
  75015. return _super.call(this, vrGamepad) || this;
  75016. }
  75017. /**
  75018. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75019. * @param scene scene in which to add meshes
  75020. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75021. */
  75022. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75023. var _this = this;
  75024. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  75025. _this._defaultModel = newMeshes[1];
  75026. _this.attachToMesh(_this._defaultModel);
  75027. if (meshLoaded) {
  75028. meshLoaded(_this._defaultModel);
  75029. }
  75030. });
  75031. };
  75032. /**
  75033. * Called once for each button that changed state since the last frame
  75034. * @param buttonIdx Which button index changed
  75035. * @param state New state of the button
  75036. * @param changes Which properties on the state changed since last frame
  75037. */
  75038. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75039. console.log("Button id: " + buttonIdx + "state: ");
  75040. console.dir(state);
  75041. };
  75042. /**
  75043. * Base Url for the controller model.
  75044. */
  75045. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75046. /**
  75047. * File name for the controller model.
  75048. */
  75049. GenericController.MODEL_FILENAME = 'generic.babylon';
  75050. return GenericController;
  75051. }(BABYLON.WebVRController));
  75052. BABYLON.GenericController = GenericController;
  75053. })(BABYLON || (BABYLON = {}));
  75054. //# sourceMappingURL=babylon.genericController.js.map
  75055. var BABYLON;
  75056. (function (BABYLON) {
  75057. /**
  75058. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  75059. */
  75060. var LoadedMeshInfo = /** @class */ (function () {
  75061. function LoadedMeshInfo() {
  75062. /**
  75063. * Map of the button meshes contained in the controller
  75064. */
  75065. this.buttonMeshes = {};
  75066. /**
  75067. * Map of the axis meshes contained in the controller
  75068. */
  75069. this.axisMeshes = {};
  75070. }
  75071. return LoadedMeshInfo;
  75072. }());
  75073. /**
  75074. * Defines the WindowsMotionController object that the state of the windows motion controller
  75075. */
  75076. var WindowsMotionController = /** @class */ (function (_super) {
  75077. __extends(WindowsMotionController, _super);
  75078. /**
  75079. * Creates a new WindowsMotionController from a gamepad
  75080. * @param vrGamepad the gamepad that the controller should be created from
  75081. */
  75082. function WindowsMotionController(vrGamepad) {
  75083. var _this = _super.call(this, vrGamepad) || this;
  75084. _this._mapping = {
  75085. // Semantic button names
  75086. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  75087. // A mapping of the button name to glTF model node name
  75088. // that should be transformed by button value.
  75089. buttonMeshNames: {
  75090. 'trigger': 'SELECT',
  75091. 'menu': 'MENU',
  75092. 'grip': 'GRASP',
  75093. 'thumbstick': 'THUMBSTICK_PRESS',
  75094. 'trackpad': 'TOUCHPAD_PRESS'
  75095. },
  75096. // This mapping is used to translate from the Motion Controller to Babylon semantics
  75097. buttonObservableNames: {
  75098. 'trigger': 'onTriggerStateChangedObservable',
  75099. 'menu': 'onSecondaryButtonStateChangedObservable',
  75100. 'grip': 'onMainButtonStateChangedObservable',
  75101. 'thumbstick': 'onPadStateChangedObservable',
  75102. 'trackpad': 'onTrackpadChangedObservable'
  75103. },
  75104. // A mapping of the axis name to glTF model node name
  75105. // that should be transformed by axis value.
  75106. // This array mirrors the browserGamepad.axes array, such that
  75107. // the mesh corresponding to axis 0 is in this array index 0.
  75108. axisMeshNames: [
  75109. 'THUMBSTICK_X',
  75110. 'THUMBSTICK_Y',
  75111. 'TOUCHPAD_TOUCH_X',
  75112. 'TOUCHPAD_TOUCH_Y'
  75113. ],
  75114. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  75115. };
  75116. /**
  75117. * Fired when the trackpad on this controller is clicked
  75118. */
  75119. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  75120. /**
  75121. * Fired when the trackpad on this controller is modified
  75122. */
  75123. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  75124. /**
  75125. * The current x and y values of this controller's trackpad
  75126. */
  75127. _this.trackpad = { x: 0, y: 0 };
  75128. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  75129. _this._loadedMeshInfo = null;
  75130. return _this;
  75131. }
  75132. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  75133. /**
  75134. * Fired when the trigger on this controller is modified
  75135. */
  75136. get: function () {
  75137. return this.onTriggerStateChangedObservable;
  75138. },
  75139. enumerable: true,
  75140. configurable: true
  75141. });
  75142. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  75143. /**
  75144. * Fired when the menu button on this controller is modified
  75145. */
  75146. get: function () {
  75147. return this.onSecondaryButtonStateChangedObservable;
  75148. },
  75149. enumerable: true,
  75150. configurable: true
  75151. });
  75152. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  75153. /**
  75154. * Fired when the grip button on this controller is modified
  75155. */
  75156. get: function () {
  75157. return this.onMainButtonStateChangedObservable;
  75158. },
  75159. enumerable: true,
  75160. configurable: true
  75161. });
  75162. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  75163. /**
  75164. * Fired when the thumbstick button on this controller is modified
  75165. */
  75166. get: function () {
  75167. return this.onPadStateChangedObservable;
  75168. },
  75169. enumerable: true,
  75170. configurable: true
  75171. });
  75172. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  75173. /**
  75174. * Fired when the touchpad button on this controller is modified
  75175. */
  75176. get: function () {
  75177. return this.onTrackpadChangedObservable;
  75178. },
  75179. enumerable: true,
  75180. configurable: true
  75181. });
  75182. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  75183. /**
  75184. * Fired when the touchpad values on this controller are modified
  75185. */
  75186. get: function () {
  75187. return this.onTrackpadValuesChangedObservable;
  75188. },
  75189. enumerable: true,
  75190. configurable: true
  75191. });
  75192. WindowsMotionController.prototype._updateTrackpad = function () {
  75193. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  75194. this.trackpad.x = this.browserGamepad["axes"][2];
  75195. this.trackpad.y = this.browserGamepad["axes"][3];
  75196. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  75197. }
  75198. };
  75199. /**
  75200. * Called once per frame by the engine.
  75201. */
  75202. WindowsMotionController.prototype.update = function () {
  75203. _super.prototype.update.call(this);
  75204. if (this.browserGamepad.axes) {
  75205. this._updateTrackpad();
  75206. // Only need to animate axes if there is a loaded mesh
  75207. if (this._loadedMeshInfo) {
  75208. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  75209. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  75210. }
  75211. }
  75212. }
  75213. };
  75214. /**
  75215. * Called once for each button that changed state since the last frame
  75216. * @param buttonIdx Which button index changed
  75217. * @param state New state of the button
  75218. * @param changes Which properties on the state changed since last frame
  75219. */
  75220. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75221. var buttonName = this._mapping.buttons[buttonIdx];
  75222. if (!buttonName) {
  75223. return;
  75224. }
  75225. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  75226. this._updateTrackpad();
  75227. // Only emit events for buttons that we know how to map from index to name
  75228. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  75229. if (observable) {
  75230. observable.notifyObservers(state);
  75231. }
  75232. this._lerpButtonTransform(buttonName, state.value);
  75233. };
  75234. /**
  75235. * Moves the buttons on the controller mesh based on their current state
  75236. * @param buttonName the name of the button to move
  75237. * @param buttonValue the value of the button which determines the buttons new position
  75238. */
  75239. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  75240. // If there is no loaded mesh, there is nothing to transform.
  75241. if (!this._loadedMeshInfo) {
  75242. return;
  75243. }
  75244. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  75245. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75246. return;
  75247. }
  75248. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  75249. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  75250. };
  75251. /**
  75252. * Moves the axis on the controller mesh based on its current state
  75253. * @param axis the index of the axis
  75254. * @param axisValue the value of the axis which determines the meshes new position
  75255. * @hidden
  75256. */
  75257. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  75258. if (!this._loadedMeshInfo) {
  75259. return;
  75260. }
  75261. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  75262. if (!meshInfo) {
  75263. return;
  75264. }
  75265. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75266. return;
  75267. }
  75268. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  75269. var lerpValue = axisValue * 0.5 + 0.5;
  75270. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  75271. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  75272. };
  75273. /**
  75274. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75275. * @param scene scene in which to add meshes
  75276. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75277. */
  75278. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  75279. var _this = this;
  75280. if (forceDefault === void 0) { forceDefault = false; }
  75281. var path;
  75282. var filename;
  75283. // Checking if GLB loader is present
  75284. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  75285. // Determine the device specific folder based on the ID suffix
  75286. var device = 'default';
  75287. if (this.id && !forceDefault) {
  75288. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  75289. device = ((match && match[0]) || device);
  75290. }
  75291. // Hand
  75292. if (this.hand === 'left') {
  75293. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  75294. }
  75295. else { // Right is the default if no hand is specified
  75296. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  75297. }
  75298. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  75299. }
  75300. else {
  75301. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  75302. path = BABYLON.GenericController.MODEL_BASE_URL;
  75303. filename = BABYLON.GenericController.MODEL_FILENAME;
  75304. }
  75305. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  75306. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  75307. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  75308. if (!_this._loadedMeshInfo) {
  75309. return;
  75310. }
  75311. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  75312. _this.attachToMesh(_this._defaultModel);
  75313. if (meshLoaded) {
  75314. meshLoaded(_this._defaultModel);
  75315. }
  75316. }, null, function (scene, message) {
  75317. BABYLON.Tools.Log(message);
  75318. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  75319. if (!forceDefault) {
  75320. _this.initControllerMesh(scene, meshLoaded, true);
  75321. }
  75322. });
  75323. };
  75324. /**
  75325. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  75326. * can be transformed by button presses and axes values, based on this._mapping.
  75327. *
  75328. * @param scene scene in which the meshes exist
  75329. * @param meshes list of meshes that make up the controller model to process
  75330. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  75331. */
  75332. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  75333. var loadedMeshInfo = null;
  75334. // Create a new mesh to contain the glTF hierarchy
  75335. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  75336. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  75337. var childMesh = null;
  75338. for (var i = 0; i < meshes.length; i++) {
  75339. var mesh = meshes[i];
  75340. if (!mesh.parent) {
  75341. // Exclude controller meshes from picking results
  75342. mesh.isPickable = false;
  75343. // Handle root node, attach to the new parentMesh
  75344. childMesh = mesh;
  75345. break;
  75346. }
  75347. }
  75348. if (childMesh) {
  75349. childMesh.setParent(parentMesh);
  75350. // Create our mesh info. Note that this method will always return non-null.
  75351. loadedMeshInfo = this.createMeshInfo(parentMesh);
  75352. }
  75353. else {
  75354. BABYLON.Tools.Warn('Could not find root node in model file.');
  75355. }
  75356. return loadedMeshInfo;
  75357. };
  75358. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  75359. var loadedMeshInfo = new LoadedMeshInfo();
  75360. var i;
  75361. loadedMeshInfo.rootNode = rootNode;
  75362. // Reset the caches
  75363. loadedMeshInfo.buttonMeshes = {};
  75364. loadedMeshInfo.axisMeshes = {};
  75365. // Button Meshes
  75366. for (i = 0; i < this._mapping.buttons.length; i++) {
  75367. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  75368. if (!buttonMeshName) {
  75369. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  75370. continue;
  75371. }
  75372. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  75373. if (!buttonMesh) {
  75374. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  75375. continue;
  75376. }
  75377. var buttonMeshInfo = {
  75378. index: i,
  75379. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  75380. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  75381. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  75382. };
  75383. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  75384. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  75385. }
  75386. else {
  75387. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  75388. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  75389. '(VALUE: ' + !!buttonMeshInfo.value +
  75390. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  75391. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  75392. ')');
  75393. }
  75394. }
  75395. // Axis Meshes
  75396. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  75397. var axisMeshName = this._mapping.axisMeshNames[i];
  75398. if (!axisMeshName) {
  75399. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  75400. continue;
  75401. }
  75402. var axisMesh = getChildByName(rootNode, axisMeshName);
  75403. if (!axisMesh) {
  75404. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  75405. continue;
  75406. }
  75407. var axisMeshInfo = {
  75408. index: i,
  75409. value: getImmediateChildByName(axisMesh, 'VALUE'),
  75410. min: getImmediateChildByName(axisMesh, 'MIN'),
  75411. max: getImmediateChildByName(axisMesh, 'MAX')
  75412. };
  75413. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  75414. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  75415. }
  75416. else {
  75417. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  75418. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  75419. '(VALUE: ' + !!axisMeshInfo.value +
  75420. ', MIN: ' + !!axisMeshInfo.min +
  75421. ', MAX:' + !!axisMeshInfo.max +
  75422. ')');
  75423. }
  75424. }
  75425. // Pointing Ray
  75426. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  75427. if (!loadedMeshInfo.pointingPoseNode) {
  75428. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  75429. }
  75430. else {
  75431. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  75432. }
  75433. return loadedMeshInfo;
  75434. // Look through all children recursively. This will return null if no mesh exists with the given name.
  75435. function getChildByName(node, name) {
  75436. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  75437. }
  75438. // Look through only immediate children. This will return null if no mesh exists with the given name.
  75439. function getImmediateChildByName(node, name) {
  75440. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  75441. }
  75442. };
  75443. /**
  75444. * Gets the ray of the controller in the direction the controller is pointing
  75445. * @param length the length the resulting ray should be
  75446. * @returns a ray in the direction the controller is pointing
  75447. */
  75448. WindowsMotionController.prototype.getForwardRay = function (length) {
  75449. if (length === void 0) { length = 100; }
  75450. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  75451. return _super.prototype.getForwardRay.call(this, length);
  75452. }
  75453. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  75454. var origin = m.getTranslation();
  75455. var forward = new BABYLON.Vector3(0, 0, -1);
  75456. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  75457. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  75458. return new BABYLON.Ray(origin, direction, length);
  75459. };
  75460. /**
  75461. * Disposes of the controller
  75462. */
  75463. WindowsMotionController.prototype.dispose = function () {
  75464. _super.prototype.dispose.call(this);
  75465. this.onTrackpadChangedObservable.clear();
  75466. };
  75467. /**
  75468. * The base url used to load the left and right controller models
  75469. */
  75470. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  75471. /**
  75472. * The name of the left controller model file
  75473. */
  75474. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  75475. /**
  75476. * The name of the right controller model file
  75477. */
  75478. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  75479. /**
  75480. * The controller name prefix for this controller type
  75481. */
  75482. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  75483. /**
  75484. * The controller id pattern for this controller type
  75485. */
  75486. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  75487. return WindowsMotionController;
  75488. }(BABYLON.WebVRController));
  75489. BABYLON.WindowsMotionController = WindowsMotionController;
  75490. })(BABYLON || (BABYLON = {}));
  75491. //# sourceMappingURL=babylon.windowsMotionController.js.map
  75492. var BABYLON;
  75493. (function (BABYLON) {
  75494. /**
  75495. * Gear VR Controller
  75496. */
  75497. var GearVRController = /** @class */ (function (_super) {
  75498. __extends(GearVRController, _super);
  75499. /**
  75500. * Creates a new GearVRController from a gamepad
  75501. * @param vrGamepad the gamepad that the controller should be created from
  75502. */
  75503. function GearVRController(vrGamepad) {
  75504. var _this = _super.call(this, vrGamepad) || this;
  75505. _this._maxRotationDistFromHeadset = Math.PI / 5;
  75506. _this._draggedRoomRotation = 0;
  75507. _this._tmpVector = new BABYLON.Vector3();
  75508. _this._buttonIndexToObservableNameMap = [
  75509. 'onTrackpadChangedObservable',
  75510. 'onTriggerStateChangedObservable' // Trigger
  75511. ];
  75512. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  75513. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  75514. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  75515. return _this;
  75516. }
  75517. /**
  75518. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75519. * @param poseData raw pose fromthe device
  75520. */
  75521. GearVRController.prototype.updateFromDevice = function (poseData) {
  75522. _super.prototype.updateFromDevice.call(this, poseData);
  75523. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  75524. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  75525. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  75526. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  75527. // Find the radian distance away that the headset is from the controllers rotation
  75528. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  75529. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  75530. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  75531. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  75532. this._draggedRoomRotation += rotationAmount;
  75533. // Rotate controller around headset
  75534. var sin = Math.sin(-rotationAmount);
  75535. var cos = Math.cos(-rotationAmount);
  75536. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  75537. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  75538. }
  75539. }
  75540. }
  75541. };
  75542. /**
  75543. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75544. * @param scene scene in which to add meshes
  75545. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75546. */
  75547. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75548. var _this = this;
  75549. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  75550. // Offset the controller so it will rotate around the users wrist
  75551. var mesh = new BABYLON.Mesh("", scene);
  75552. newMeshes[1].parent = mesh;
  75553. newMeshes[1].position.z = -0.15;
  75554. _this._defaultModel = mesh;
  75555. _this.attachToMesh(_this._defaultModel);
  75556. if (meshLoaded) {
  75557. meshLoaded(_this._defaultModel);
  75558. }
  75559. });
  75560. };
  75561. /**
  75562. * Called once for each button that changed state since the last frame
  75563. * @param buttonIdx Which button index changed
  75564. * @param state New state of the button
  75565. * @param changes Which properties on the state changed since last frame
  75566. */
  75567. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75568. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  75569. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  75570. // Only emit events for buttons that we know how to map from index to observable
  75571. var observable = this[observableName];
  75572. if (observable) {
  75573. observable.notifyObservers(state);
  75574. }
  75575. }
  75576. };
  75577. /**
  75578. * Base Url for the controller model.
  75579. */
  75580. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75581. /**
  75582. * File name for the controller model.
  75583. */
  75584. GearVRController.MODEL_FILENAME = 'generic.babylon';
  75585. /**
  75586. * Gamepad Id prefix used to identify this controller.
  75587. */
  75588. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  75589. return GearVRController;
  75590. }(BABYLON.WebVRController));
  75591. BABYLON.GearVRController = GearVRController;
  75592. })(BABYLON || (BABYLON = {}));
  75593. //# sourceMappingURL=babylon.gearVRController.js.map
  75594. var BABYLON;
  75595. (function (BABYLON) {
  75596. /**
  75597. * Google Daydream controller
  75598. */
  75599. var DaydreamController = /** @class */ (function (_super) {
  75600. __extends(DaydreamController, _super);
  75601. /**
  75602. * Creates a new DaydreamController from a gamepad
  75603. * @param vrGamepad the gamepad that the controller should be created from
  75604. */
  75605. function DaydreamController(vrGamepad) {
  75606. var _this = _super.call(this, vrGamepad) || this;
  75607. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  75608. return _this;
  75609. }
  75610. /**
  75611. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75612. * @param scene scene in which to add meshes
  75613. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75614. */
  75615. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75616. var _this = this;
  75617. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  75618. _this._defaultModel = newMeshes[1];
  75619. _this.attachToMesh(_this._defaultModel);
  75620. if (meshLoaded) {
  75621. meshLoaded(_this._defaultModel);
  75622. }
  75623. });
  75624. };
  75625. /**
  75626. * Called once for each button that changed state since the last frame
  75627. * @param buttonIdx Which button index changed
  75628. * @param state New state of the button
  75629. * @param changes Which properties on the state changed since last frame
  75630. */
  75631. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75632. // Daydream controller only has 1 GamepadButton (on the trackpad).
  75633. if (buttonIdx === 0) {
  75634. var observable = this.onTriggerStateChangedObservable;
  75635. if (observable) {
  75636. observable.notifyObservers(state);
  75637. }
  75638. }
  75639. else {
  75640. // If the app or home buttons are ever made available
  75641. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  75642. }
  75643. };
  75644. /**
  75645. * Base Url for the controller model.
  75646. */
  75647. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75648. /**
  75649. * File name for the controller model.
  75650. */
  75651. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  75652. /**
  75653. * Gamepad Id prefix used to identify Daydream Controller.
  75654. */
  75655. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  75656. return DaydreamController;
  75657. }(BABYLON.WebVRController));
  75658. BABYLON.DaydreamController = DaydreamController;
  75659. })(BABYLON || (BABYLON = {}));
  75660. //# sourceMappingURL=babylon.daydreamController.js.map
  75661. var BABYLON;
  75662. (function (BABYLON) {
  75663. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  75664. get: function () {
  75665. if (!this._gamepadManager) {
  75666. this._gamepadManager = new BABYLON.GamepadManager(this);
  75667. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  75668. if (!component) {
  75669. component = new GamepadSystemSceneComponent(this);
  75670. this._addComponent(component);
  75671. }
  75672. }
  75673. return this._gamepadManager;
  75674. },
  75675. enumerable: true,
  75676. configurable: true
  75677. });
  75678. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  75679. this.add(new BABYLON.FreeCameraGamepadInput());
  75680. return this;
  75681. };
  75682. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  75683. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  75684. return this;
  75685. };
  75686. /**
  75687. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  75688. */
  75689. var GamepadSystemSceneComponent = /** @class */ (function () {
  75690. /**
  75691. * Creates a new instance of the component for the given scene
  75692. * @param scene Defines the scene to register the component in
  75693. */
  75694. function GamepadSystemSceneComponent(scene) {
  75695. /**
  75696. * The component name helpfull to identify the component in the list of scene components.
  75697. */
  75698. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  75699. this.scene = scene;
  75700. }
  75701. /**
  75702. * Registers the component in a given scene
  75703. */
  75704. GamepadSystemSceneComponent.prototype.register = function () {
  75705. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  75706. };
  75707. /**
  75708. * Rebuilds the elements related to this component in case of
  75709. * context lost for instance.
  75710. */
  75711. GamepadSystemSceneComponent.prototype.rebuild = function () {
  75712. // Nothing to do for gamepads
  75713. };
  75714. /**
  75715. * Disposes the component and the associated ressources
  75716. */
  75717. GamepadSystemSceneComponent.prototype.dispose = function () {
  75718. var gamepadManager = this.scene._gamepadManager;
  75719. if (gamepadManager) {
  75720. gamepadManager.dispose();
  75721. this.scene._gamepadManager = null;
  75722. }
  75723. };
  75724. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  75725. var gamepadManager = this.scene._gamepadManager;
  75726. if (gamepadManager && gamepadManager._isMonitoring) {
  75727. gamepadManager._checkGamepadsStatus();
  75728. }
  75729. };
  75730. return GamepadSystemSceneComponent;
  75731. }());
  75732. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  75733. })(BABYLON || (BABYLON = {}));
  75734. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  75735. var BABYLON;
  75736. (function (BABYLON) {
  75737. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  75738. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  75739. });
  75740. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  75741. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  75742. });
  75743. var FollowCamera = /** @class */ (function (_super) {
  75744. __extends(FollowCamera, _super);
  75745. function FollowCamera(name, position, scene, lockedTarget) {
  75746. if (lockedTarget === void 0) { lockedTarget = null; }
  75747. var _this = _super.call(this, name, position, scene) || this;
  75748. _this.radius = 12;
  75749. _this.rotationOffset = 0;
  75750. _this.heightOffset = 4;
  75751. _this.cameraAcceleration = 0.05;
  75752. _this.maxCameraSpeed = 20;
  75753. _this.lockedTarget = lockedTarget;
  75754. return _this;
  75755. }
  75756. FollowCamera.prototype.getRadians = function (degrees) {
  75757. return degrees * Math.PI / 180;
  75758. };
  75759. FollowCamera.prototype.follow = function (cameraTarget) {
  75760. if (!cameraTarget)
  75761. return;
  75762. var yRotation;
  75763. if (cameraTarget.rotationQuaternion) {
  75764. var rotMatrix = new BABYLON.Matrix();
  75765. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  75766. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  75767. }
  75768. else {
  75769. yRotation = cameraTarget.rotation.y;
  75770. }
  75771. var radians = this.getRadians(this.rotationOffset) + yRotation;
  75772. var targetPosition = cameraTarget.getAbsolutePosition();
  75773. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  75774. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  75775. var dx = targetX - this.position.x;
  75776. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  75777. var dz = (targetZ) - this.position.z;
  75778. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  75779. var vy = dy * this.cameraAcceleration;
  75780. var vz = dz * this.cameraAcceleration * 2;
  75781. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  75782. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75783. }
  75784. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  75785. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75786. }
  75787. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  75788. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75789. }
  75790. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  75791. this.setTarget(targetPosition);
  75792. };
  75793. /** @hidden */
  75794. FollowCamera.prototype._checkInputs = function () {
  75795. _super.prototype._checkInputs.call(this);
  75796. if (this.lockedTarget) {
  75797. this.follow(this.lockedTarget);
  75798. }
  75799. };
  75800. FollowCamera.prototype.getClassName = function () {
  75801. return "FollowCamera";
  75802. };
  75803. __decorate([
  75804. BABYLON.serialize()
  75805. ], FollowCamera.prototype, "radius", void 0);
  75806. __decorate([
  75807. BABYLON.serialize()
  75808. ], FollowCamera.prototype, "rotationOffset", void 0);
  75809. __decorate([
  75810. BABYLON.serialize()
  75811. ], FollowCamera.prototype, "heightOffset", void 0);
  75812. __decorate([
  75813. BABYLON.serialize()
  75814. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  75815. __decorate([
  75816. BABYLON.serialize()
  75817. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  75818. __decorate([
  75819. BABYLON.serializeAsMeshReference("lockedTargetId")
  75820. ], FollowCamera.prototype, "lockedTarget", void 0);
  75821. return FollowCamera;
  75822. }(BABYLON.TargetCamera));
  75823. BABYLON.FollowCamera = FollowCamera;
  75824. var ArcFollowCamera = /** @class */ (function (_super) {
  75825. __extends(ArcFollowCamera, _super);
  75826. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  75827. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  75828. _this.alpha = alpha;
  75829. _this.beta = beta;
  75830. _this.radius = radius;
  75831. _this.target = target;
  75832. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  75833. _this.follow();
  75834. return _this;
  75835. }
  75836. ArcFollowCamera.prototype.follow = function () {
  75837. if (!this.target) {
  75838. return;
  75839. }
  75840. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  75841. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  75842. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  75843. var targetPosition = this.target.getAbsolutePosition();
  75844. this.position = targetPosition.add(this._cartesianCoordinates);
  75845. this.setTarget(targetPosition);
  75846. };
  75847. /** @hidden */
  75848. ArcFollowCamera.prototype._checkInputs = function () {
  75849. _super.prototype._checkInputs.call(this);
  75850. this.follow();
  75851. };
  75852. ArcFollowCamera.prototype.getClassName = function () {
  75853. return "ArcFollowCamera";
  75854. };
  75855. return ArcFollowCamera;
  75856. }(BABYLON.TargetCamera));
  75857. BABYLON.ArcFollowCamera = ArcFollowCamera;
  75858. })(BABYLON || (BABYLON = {}));
  75859. //# sourceMappingURL=babylon.followCamera.js.map
  75860. var BABYLON;
  75861. (function (BABYLON) {
  75862. // We're mainly based on the logic defined into the FreeCamera code
  75863. var UniversalCamera = /** @class */ (function (_super) {
  75864. __extends(UniversalCamera, _super);
  75865. //-- end properties for backward compatibility for inputs
  75866. function UniversalCamera(name, position, scene) {
  75867. var _this = _super.call(this, name, position, scene) || this;
  75868. _this.inputs.addGamepad();
  75869. return _this;
  75870. }
  75871. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  75872. //-- Begin properties for backward compatibility for inputs
  75873. get: function () {
  75874. var gamepad = this.inputs.attached["gamepad"];
  75875. if (gamepad)
  75876. return gamepad.gamepadAngularSensibility;
  75877. return 0;
  75878. },
  75879. set: function (value) {
  75880. var gamepad = this.inputs.attached["gamepad"];
  75881. if (gamepad)
  75882. gamepad.gamepadAngularSensibility = value;
  75883. },
  75884. enumerable: true,
  75885. configurable: true
  75886. });
  75887. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  75888. get: function () {
  75889. var gamepad = this.inputs.attached["gamepad"];
  75890. if (gamepad)
  75891. return gamepad.gamepadMoveSensibility;
  75892. return 0;
  75893. },
  75894. set: function (value) {
  75895. var gamepad = this.inputs.attached["gamepad"];
  75896. if (gamepad)
  75897. gamepad.gamepadMoveSensibility = value;
  75898. },
  75899. enumerable: true,
  75900. configurable: true
  75901. });
  75902. UniversalCamera.prototype.getClassName = function () {
  75903. return "UniversalCamera";
  75904. };
  75905. return UniversalCamera;
  75906. }(BABYLON.TouchCamera));
  75907. BABYLON.UniversalCamera = UniversalCamera;
  75908. })(BABYLON || (BABYLON = {}));
  75909. //# sourceMappingURL=babylon.universalCamera.js.map
  75910. var BABYLON;
  75911. (function (BABYLON) {
  75912. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  75913. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  75914. });
  75915. // We're mainly based on the logic defined into the FreeCamera code
  75916. var GamepadCamera = /** @class */ (function (_super) {
  75917. __extends(GamepadCamera, _super);
  75918. //-- end properties for backward compatibility for inputs
  75919. function GamepadCamera(name, position, scene) {
  75920. return _super.call(this, name, position, scene) || this;
  75921. }
  75922. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  75923. //-- Begin properties for backward compatibility for inputs
  75924. get: function () {
  75925. var gamepad = this.inputs.attached["gamepad"];
  75926. if (gamepad)
  75927. return gamepad.gamepadAngularSensibility;
  75928. return 0;
  75929. },
  75930. set: function (value) {
  75931. var gamepad = this.inputs.attached["gamepad"];
  75932. if (gamepad)
  75933. gamepad.gamepadAngularSensibility = value;
  75934. },
  75935. enumerable: true,
  75936. configurable: true
  75937. });
  75938. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  75939. get: function () {
  75940. var gamepad = this.inputs.attached["gamepad"];
  75941. if (gamepad)
  75942. return gamepad.gamepadMoveSensibility;
  75943. return 0;
  75944. },
  75945. set: function (value) {
  75946. var gamepad = this.inputs.attached["gamepad"];
  75947. if (gamepad)
  75948. gamepad.gamepadMoveSensibility = value;
  75949. },
  75950. enumerable: true,
  75951. configurable: true
  75952. });
  75953. GamepadCamera.prototype.getClassName = function () {
  75954. return "GamepadCamera";
  75955. };
  75956. return GamepadCamera;
  75957. }(BABYLON.UniversalCamera));
  75958. BABYLON.GamepadCamera = GamepadCamera;
  75959. })(BABYLON || (BABYLON = {}));
  75960. //# sourceMappingURL=babylon.gamepadCamera.js.map
  75961. var BABYLON;
  75962. (function (BABYLON) {
  75963. var PostProcessRenderPipelineManager = /** @class */ (function () {
  75964. function PostProcessRenderPipelineManager() {
  75965. this._renderPipelines = {};
  75966. }
  75967. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  75968. this._renderPipelines[renderPipeline._name] = renderPipeline;
  75969. };
  75970. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  75971. if (unique === void 0) { unique = false; }
  75972. var renderPipeline = this._renderPipelines[renderPipelineName];
  75973. if (!renderPipeline) {
  75974. return;
  75975. }
  75976. renderPipeline._attachCameras(cameras, unique);
  75977. };
  75978. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  75979. var renderPipeline = this._renderPipelines[renderPipelineName];
  75980. if (!renderPipeline) {
  75981. return;
  75982. }
  75983. renderPipeline._detachCameras(cameras);
  75984. };
  75985. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  75986. var renderPipeline = this._renderPipelines[renderPipelineName];
  75987. if (!renderPipeline) {
  75988. return;
  75989. }
  75990. renderPipeline._enableEffect(renderEffectName, cameras);
  75991. };
  75992. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  75993. var renderPipeline = this._renderPipelines[renderPipelineName];
  75994. if (!renderPipeline) {
  75995. return;
  75996. }
  75997. renderPipeline._disableEffect(renderEffectName, cameras);
  75998. };
  75999. PostProcessRenderPipelineManager.prototype.update = function () {
  76000. for (var renderPipelineName in this._renderPipelines) {
  76001. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76002. var pipeline = this._renderPipelines[renderPipelineName];
  76003. if (!pipeline.isSupported) {
  76004. pipeline.dispose();
  76005. delete this._renderPipelines[renderPipelineName];
  76006. }
  76007. else {
  76008. pipeline._update();
  76009. }
  76010. }
  76011. }
  76012. };
  76013. /** @hidden */
  76014. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  76015. for (var renderPipelineName in this._renderPipelines) {
  76016. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76017. var pipeline = this._renderPipelines[renderPipelineName];
  76018. pipeline._rebuild();
  76019. }
  76020. }
  76021. };
  76022. PostProcessRenderPipelineManager.prototype.dispose = function () {
  76023. for (var renderPipelineName in this._renderPipelines) {
  76024. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76025. var pipeline = this._renderPipelines[renderPipelineName];
  76026. pipeline.dispose();
  76027. }
  76028. }
  76029. };
  76030. return PostProcessRenderPipelineManager;
  76031. }());
  76032. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  76033. })(BABYLON || (BABYLON = {}));
  76034. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  76035. var BABYLON;
  76036. (function (BABYLON) {
  76037. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  76038. get: function () {
  76039. if (!this._postProcessRenderPipelineManager) {
  76040. // Register the G Buffer component to the scene.
  76041. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  76042. if (!component) {
  76043. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  76044. this._addComponent(component);
  76045. }
  76046. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  76047. }
  76048. return this._postProcessRenderPipelineManager;
  76049. },
  76050. enumerable: true,
  76051. configurable: true
  76052. });
  76053. /**
  76054. * Defines the Render Pipeline scene component responsible to rendering pipelines
  76055. */
  76056. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  76057. /**
  76058. * Creates a new instance of the component for the given scene
  76059. * @param scene Defines the scene to register the component in
  76060. */
  76061. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  76062. /**
  76063. * The component name helpfull to identify the component in the list of scene components.
  76064. */
  76065. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  76066. this.scene = scene;
  76067. }
  76068. /**
  76069. * Registers the component in a given scene
  76070. */
  76071. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  76072. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  76073. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER, this, this._rebuildGeometry);
  76074. };
  76075. /**
  76076. * Rebuilds the elements related to this component in case of
  76077. * context lost for instance.
  76078. */
  76079. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  76080. // Nothing to do for this component
  76081. };
  76082. /**
  76083. * Disposes the component and the associated ressources
  76084. */
  76085. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  76086. if (this.scene._postProcessRenderPipelineManager) {
  76087. this.scene._postProcessRenderPipelineManager.dispose();
  76088. }
  76089. };
  76090. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76091. if (this.scene._postProcessRenderPipelineManager) {
  76092. this.scene._postProcessRenderPipelineManager.update();
  76093. }
  76094. };
  76095. PostProcessRenderPipelineManagerSceneComponent.prototype._rebuildGeometry = function () {
  76096. if (this.scene._postProcessRenderPipelineManager) {
  76097. this.scene._postProcessRenderPipelineManager._rebuild();
  76098. }
  76099. };
  76100. return PostProcessRenderPipelineManagerSceneComponent;
  76101. }());
  76102. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  76103. })(BABYLON || (BABYLON = {}));
  76104. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  76105. var BABYLON;
  76106. (function (BABYLON) {
  76107. /**
  76108. * This represents a set of one or more post processes in Babylon.
  76109. * A post process can be used to apply a shader to a texture after it is rendered.
  76110. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  76111. */
  76112. var PostProcessRenderEffect = /** @class */ (function () {
  76113. /**
  76114. * Instantiates a post process render effect.
  76115. * A post process can be used to apply a shader to a texture after it is rendered.
  76116. * @param engine The engine the effect is tied to
  76117. * @param name The name of the effect
  76118. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  76119. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  76120. */
  76121. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  76122. this._name = name;
  76123. this._singleInstance = singleInstance || true;
  76124. this._getPostProcesses = getPostProcesses;
  76125. this._cameras = {};
  76126. this._indicesForCamera = {};
  76127. this._postProcesses = {};
  76128. }
  76129. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  76130. /**
  76131. * Checks if all the post processes in the effect are supported.
  76132. */
  76133. get: function () {
  76134. for (var index in this._postProcesses) {
  76135. if (this._postProcesses.hasOwnProperty(index)) {
  76136. var pps = this._postProcesses[index];
  76137. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  76138. if (!pps[ppIndex].isSupported) {
  76139. return false;
  76140. }
  76141. }
  76142. }
  76143. }
  76144. return true;
  76145. },
  76146. enumerable: true,
  76147. configurable: true
  76148. });
  76149. /**
  76150. * Updates the current state of the effect
  76151. * @hidden
  76152. */
  76153. PostProcessRenderEffect.prototype._update = function () {
  76154. };
  76155. /**
  76156. * Attaches the effect on cameras
  76157. * @param cameras The camera to attach to.
  76158. * @hidden
  76159. */
  76160. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  76161. var _this = this;
  76162. var cameraKey;
  76163. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76164. if (!cams) {
  76165. return;
  76166. }
  76167. for (var i = 0; i < cams.length; i++) {
  76168. var camera = cams[i];
  76169. var cameraName = camera.name;
  76170. if (this._singleInstance) {
  76171. cameraKey = 0;
  76172. }
  76173. else {
  76174. cameraKey = cameraName;
  76175. }
  76176. if (!this._postProcesses[cameraKey]) {
  76177. var postProcess = this._getPostProcesses();
  76178. if (postProcess) {
  76179. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  76180. }
  76181. }
  76182. if (!this._indicesForCamera[cameraName]) {
  76183. this._indicesForCamera[cameraName] = [];
  76184. }
  76185. this._postProcesses[cameraKey].forEach(function (postProcess) {
  76186. var index = camera.attachPostProcess(postProcess);
  76187. _this._indicesForCamera[cameraName].push(index);
  76188. });
  76189. if (!this._cameras[cameraName]) {
  76190. this._cameras[cameraName] = camera;
  76191. }
  76192. }
  76193. };
  76194. /**
  76195. * Detatches the effect on cameras
  76196. * @param cameras The camera to detatch from.
  76197. * @hidden
  76198. */
  76199. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  76200. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76201. if (!cams) {
  76202. return;
  76203. }
  76204. for (var i = 0; i < cams.length; i++) {
  76205. var camera = cams[i];
  76206. var cameraName = camera.name;
  76207. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76208. camera.detachPostProcess(postProcess);
  76209. });
  76210. if (this._cameras[cameraName]) {
  76211. //this._indicesForCamera.splice(index, 1);
  76212. this._cameras[cameraName] = null;
  76213. }
  76214. }
  76215. };
  76216. /**
  76217. * Enables the effect on given cameras
  76218. * @param cameras The camera to enable.
  76219. * @hidden
  76220. */
  76221. PostProcessRenderEffect.prototype._enable = function (cameras) {
  76222. var _this = this;
  76223. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76224. if (!cams) {
  76225. return;
  76226. }
  76227. for (var i = 0; i < cams.length; i++) {
  76228. var camera = cams[i];
  76229. var cameraName = camera.name;
  76230. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  76231. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  76232. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76233. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  76234. });
  76235. }
  76236. }
  76237. }
  76238. };
  76239. /**
  76240. * Disables the effect on the given cameras
  76241. * @param cameras The camera to disable.
  76242. * @hidden
  76243. */
  76244. PostProcessRenderEffect.prototype._disable = function (cameras) {
  76245. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76246. if (!cams) {
  76247. return;
  76248. }
  76249. for (var i = 0; i < cams.length; i++) {
  76250. var camera = cams[i];
  76251. var cameraName = camera.name;
  76252. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76253. camera.detachPostProcess(postProcess);
  76254. });
  76255. }
  76256. };
  76257. /**
  76258. * Gets a list of the post processes contained in the effect.
  76259. * @param camera The camera to get the post processes on.
  76260. * @returns The list of the post processes in the effect.
  76261. */
  76262. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  76263. if (this._singleInstance) {
  76264. return this._postProcesses[0];
  76265. }
  76266. else {
  76267. if (!camera) {
  76268. return null;
  76269. }
  76270. return this._postProcesses[camera.name];
  76271. }
  76272. };
  76273. return PostProcessRenderEffect;
  76274. }());
  76275. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  76276. })(BABYLON || (BABYLON = {}));
  76277. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  76278. var BABYLON;
  76279. (function (BABYLON) {
  76280. var PostProcessRenderPipeline = /** @class */ (function () {
  76281. function PostProcessRenderPipeline(engine, name) {
  76282. this.engine = engine;
  76283. this._name = name;
  76284. this._renderEffects = {};
  76285. this._renderEffectsForIsolatedPass = new Array();
  76286. this._cameras = [];
  76287. }
  76288. PostProcessRenderPipeline.prototype.getClassName = function () {
  76289. return "PostProcessRenderPipeline";
  76290. };
  76291. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  76292. get: function () {
  76293. for (var renderEffectName in this._renderEffects) {
  76294. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76295. if (!this._renderEffects[renderEffectName].isSupported) {
  76296. return false;
  76297. }
  76298. }
  76299. }
  76300. return true;
  76301. },
  76302. enumerable: true,
  76303. configurable: true
  76304. });
  76305. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  76306. this._renderEffects[renderEffect._name] = renderEffect;
  76307. };
  76308. // private
  76309. /** @hidden */
  76310. PostProcessRenderPipeline.prototype._rebuild = function () {
  76311. };
  76312. /** @hidden */
  76313. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  76314. var renderEffects = this._renderEffects[renderEffectName];
  76315. if (!renderEffects) {
  76316. return;
  76317. }
  76318. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  76319. };
  76320. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  76321. var renderEffects = this._renderEffects[renderEffectName];
  76322. if (!renderEffects) {
  76323. return;
  76324. }
  76325. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  76326. };
  76327. /** @hidden */
  76328. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  76329. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76330. if (!cams) {
  76331. return;
  76332. }
  76333. var indicesToDelete = [];
  76334. var i;
  76335. for (i = 0; i < cams.length; i++) {
  76336. var camera = cams[i];
  76337. var cameraName = camera.name;
  76338. if (this._cameras.indexOf(camera) === -1) {
  76339. this._cameras[cameraName] = camera;
  76340. }
  76341. else if (unique) {
  76342. indicesToDelete.push(i);
  76343. }
  76344. }
  76345. for (i = 0; i < indicesToDelete.length; i++) {
  76346. cameras.splice(indicesToDelete[i], 1);
  76347. }
  76348. for (var renderEffectName in this._renderEffects) {
  76349. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76350. this._renderEffects[renderEffectName]._attachCameras(cams);
  76351. }
  76352. }
  76353. };
  76354. /** @hidden */
  76355. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  76356. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76357. if (!cams) {
  76358. return;
  76359. }
  76360. for (var renderEffectName in this._renderEffects) {
  76361. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76362. this._renderEffects[renderEffectName]._detachCameras(cams);
  76363. }
  76364. }
  76365. for (var i = 0; i < cams.length; i++) {
  76366. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  76367. }
  76368. };
  76369. /** @hidden */
  76370. PostProcessRenderPipeline.prototype._update = function () {
  76371. for (var renderEffectName in this._renderEffects) {
  76372. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76373. this._renderEffects[renderEffectName]._update();
  76374. }
  76375. }
  76376. for (var i = 0; i < this._cameras.length; i++) {
  76377. var cameraName = this._cameras[i].name;
  76378. if (this._renderEffectsForIsolatedPass[cameraName]) {
  76379. this._renderEffectsForIsolatedPass[cameraName]._update();
  76380. }
  76381. }
  76382. };
  76383. /** @hidden */
  76384. PostProcessRenderPipeline.prototype._reset = function () {
  76385. this._renderEffects = {};
  76386. this._renderEffectsForIsolatedPass = new Array();
  76387. };
  76388. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  76389. // 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)
  76390. var effectKeys = Object.keys(this._renderEffects);
  76391. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  76392. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  76393. if (postProcesses) {
  76394. postProcesses[0].samples = sampleCount;
  76395. return true;
  76396. }
  76397. }
  76398. return false;
  76399. };
  76400. PostProcessRenderPipeline.prototype.dispose = function () {
  76401. // Must be implemented by children
  76402. };
  76403. __decorate([
  76404. BABYLON.serialize()
  76405. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  76406. return PostProcessRenderPipeline;
  76407. }());
  76408. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  76409. })(BABYLON || (BABYLON = {}));
  76410. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  76411. var BABYLON;
  76412. (function (BABYLON) {
  76413. /**
  76414. * This represents a depth renderer in Babylon.
  76415. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  76416. */
  76417. var DepthRenderer = /** @class */ (function () {
  76418. /**
  76419. * Instantiates a depth renderer
  76420. * @param scene The scene the renderer belongs to
  76421. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  76422. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  76423. */
  76424. function DepthRenderer(scene, type, camera) {
  76425. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  76426. if (camera === void 0) { camera = null; }
  76427. var _this = this;
  76428. this._scene = scene;
  76429. // Register the G Buffer component to the scene.
  76430. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  76431. if (!component) {
  76432. component = new BABYLON.DepthRendererSceneComponent(scene);
  76433. scene._addComponent(component);
  76434. }
  76435. this._camera = camera;
  76436. var engine = scene.getEngine();
  76437. // Render target
  76438. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  76439. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76440. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76441. this._depthMap.refreshRate = 1;
  76442. this._depthMap.renderParticles = false;
  76443. this._depthMap.renderList = null;
  76444. // Camera to get depth map from to support multiple concurrent cameras
  76445. this._depthMap.activeCamera = this._camera;
  76446. this._depthMap.ignoreCameraViewport = true;
  76447. this._depthMap.useCameraPostProcesses = false;
  76448. // set default depth value to 1.0 (far away)
  76449. this._depthMap.onClearObservable.add(function (engine) {
  76450. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  76451. });
  76452. // Custom render function
  76453. var renderSubMesh = function (subMesh) {
  76454. var mesh = subMesh.getRenderingMesh();
  76455. var scene = _this._scene;
  76456. var engine = scene.getEngine();
  76457. var material = subMesh.getMaterial();
  76458. if (!material) {
  76459. return;
  76460. }
  76461. // Culling and reverse (right handed system)
  76462. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76463. // Managing instances
  76464. var batch = mesh._getInstancesRenderList(subMesh._id);
  76465. if (batch.mustReturn) {
  76466. return;
  76467. }
  76468. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76469. var camera = _this._camera || scene.activeCamera;
  76470. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  76471. engine.enableEffect(_this._effect);
  76472. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76473. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76474. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  76475. // Alpha test
  76476. if (material && material.needAlphaTesting()) {
  76477. var alphaTexture = material.getAlphaTestTexture();
  76478. if (alphaTexture) {
  76479. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76480. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76481. }
  76482. }
  76483. // Bones
  76484. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76485. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76486. }
  76487. // Draw
  76488. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76489. }
  76490. };
  76491. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76492. var index;
  76493. if (depthOnlySubMeshes.length) {
  76494. engine.setColorWrite(false);
  76495. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76496. renderSubMesh(depthOnlySubMeshes.data[index]);
  76497. }
  76498. engine.setColorWrite(true);
  76499. }
  76500. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76501. renderSubMesh(opaqueSubMeshes.data[index]);
  76502. }
  76503. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76504. renderSubMesh(alphaTestSubMeshes.data[index]);
  76505. }
  76506. };
  76507. }
  76508. /**
  76509. * Creates the depth rendering effect and checks if the effect is ready.
  76510. * @param subMesh The submesh to be used to render the depth map of
  76511. * @param useInstances If multiple world instances should be used
  76512. * @returns if the depth renderer is ready to render the depth map
  76513. */
  76514. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  76515. var material = subMesh.getMaterial();
  76516. if (material.disableDepthWrite) {
  76517. return false;
  76518. }
  76519. var defines = [];
  76520. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76521. var mesh = subMesh.getMesh();
  76522. // Alpha test
  76523. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  76524. defines.push("#define ALPHATEST");
  76525. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76526. attribs.push(BABYLON.VertexBuffer.UVKind);
  76527. defines.push("#define UV1");
  76528. }
  76529. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76530. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76531. defines.push("#define UV2");
  76532. }
  76533. }
  76534. // Bones
  76535. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76538. if (mesh.numBoneInfluencers > 4) {
  76539. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76540. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76541. }
  76542. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76543. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76544. }
  76545. else {
  76546. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76547. }
  76548. // Instances
  76549. if (useInstances) {
  76550. defines.push("#define INSTANCES");
  76551. attribs.push("world0");
  76552. attribs.push("world1");
  76553. attribs.push("world2");
  76554. attribs.push("world3");
  76555. }
  76556. // Get correct effect
  76557. var join = defines.join("\n");
  76558. if (this._cachedDefines !== join) {
  76559. this._cachedDefines = join;
  76560. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  76561. }
  76562. return this._effect.isReady();
  76563. };
  76564. /**
  76565. * Gets the texture which the depth map will be written to.
  76566. * @returns The depth map texture
  76567. */
  76568. DepthRenderer.prototype.getDepthMap = function () {
  76569. return this._depthMap;
  76570. };
  76571. /**
  76572. * Disposes of the depth renderer.
  76573. */
  76574. DepthRenderer.prototype.dispose = function () {
  76575. this._depthMap.dispose();
  76576. };
  76577. return DepthRenderer;
  76578. }());
  76579. BABYLON.DepthRenderer = DepthRenderer;
  76580. })(BABYLON || (BABYLON = {}));
  76581. //# sourceMappingURL=babylon.depthRenderer.js.map
  76582. var BABYLON;
  76583. (function (BABYLON) {
  76584. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  76585. camera = camera || this.activeCamera;
  76586. if (!camera) {
  76587. throw "No camera available to enable depth renderer";
  76588. }
  76589. if (!this._depthRenderer) {
  76590. this._depthRenderer = {};
  76591. }
  76592. if (!this._depthRenderer[camera.id]) {
  76593. var textureType = 0;
  76594. if (this.getEngine().getCaps().textureHalfFloatRender) {
  76595. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76596. }
  76597. else if (this.getEngine().getCaps().textureFloatRender) {
  76598. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76599. }
  76600. else {
  76601. throw "Depth renderer does not support int texture type";
  76602. }
  76603. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  76604. }
  76605. return this._depthRenderer[camera.id];
  76606. };
  76607. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  76608. camera = camera || this.activeCamera;
  76609. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  76610. return;
  76611. }
  76612. this._depthRenderer[camera.id].dispose();
  76613. delete this._depthRenderer[camera.id];
  76614. };
  76615. /**
  76616. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  76617. * in several rendering techniques.
  76618. */
  76619. var DepthRendererSceneComponent = /** @class */ (function () {
  76620. /**
  76621. * Creates a new instance of the component for the given scene
  76622. * @param scene Defines the scene to register the component in
  76623. */
  76624. function DepthRendererSceneComponent(scene) {
  76625. /**
  76626. * The component name helpfull to identify the component in the list of scene components.
  76627. */
  76628. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  76629. this.scene = scene;
  76630. }
  76631. /**
  76632. * Registers the component in a given scene
  76633. */
  76634. DepthRendererSceneComponent.prototype.register = function () {
  76635. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  76636. };
  76637. /**
  76638. * Rebuilds the elements related to this component in case of
  76639. * context lost for instance.
  76640. */
  76641. DepthRendererSceneComponent.prototype.rebuild = function () {
  76642. // Nothing to do for this component
  76643. };
  76644. /**
  76645. * Disposes the component and the associated ressources
  76646. */
  76647. DepthRendererSceneComponent.prototype.dispose = function () {
  76648. for (var key in this.scene._depthRenderer) {
  76649. this.scene._depthRenderer[key].dispose();
  76650. }
  76651. };
  76652. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76653. if (this.scene._depthRenderer) {
  76654. for (var key in this.scene._depthRenderer) {
  76655. renderTargets.push(this.scene._depthRenderer[key].getDepthMap());
  76656. }
  76657. }
  76658. };
  76659. return DepthRendererSceneComponent;
  76660. }());
  76661. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  76662. })(BABYLON || (BABYLON = {}));
  76663. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  76664. var BABYLON;
  76665. (function (BABYLON) {
  76666. /**
  76667. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76668. */
  76669. var GeometryBufferRenderer = /** @class */ (function () {
  76670. /**
  76671. * Creates a new G Buffer for the scene
  76672. * @param scene The scene the buffer belongs to
  76673. * @param ratio How big is the buffer related to the main canvas.
  76674. */
  76675. function GeometryBufferRenderer(scene, ratio) {
  76676. if (ratio === void 0) { ratio = 1; }
  76677. this._enablePosition = false;
  76678. this._scene = scene;
  76679. this._ratio = ratio;
  76680. // Register the G Buffer component to the scene.
  76681. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  76682. if (!component) {
  76683. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  76684. scene._addComponent(component);
  76685. }
  76686. // Render target
  76687. this._createRenderTargets();
  76688. }
  76689. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76690. /**
  76691. * Set the render list (meshes to be rendered) used in the G buffer.
  76692. */
  76693. set: function (meshes) {
  76694. this._multiRenderTarget.renderList = meshes;
  76695. },
  76696. enumerable: true,
  76697. configurable: true
  76698. });
  76699. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76700. /**
  76701. * Gets wether or not G buffer are supported by the running hardware.
  76702. * This requires draw buffer supports
  76703. */
  76704. get: function () {
  76705. return this._multiRenderTarget.isSupported;
  76706. },
  76707. enumerable: true,
  76708. configurable: true
  76709. });
  76710. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76711. /**
  76712. * Gets wether or not position are enabled for the G buffer.
  76713. */
  76714. get: function () {
  76715. return this._enablePosition;
  76716. },
  76717. /**
  76718. * Sets wether or not position are enabled for the G buffer.
  76719. */
  76720. set: function (enable) {
  76721. this._enablePosition = enable;
  76722. this.dispose();
  76723. this._createRenderTargets();
  76724. },
  76725. enumerable: true,
  76726. configurable: true
  76727. });
  76728. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76729. /**
  76730. * Gets the scene associated with the buffer.
  76731. */
  76732. get: function () {
  76733. return this._scene;
  76734. },
  76735. enumerable: true,
  76736. configurable: true
  76737. });
  76738. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76739. /**
  76740. * Gets the ratio used by the buffer during its creation.
  76741. * How big is the buffer related to the main canvas.
  76742. */
  76743. get: function () {
  76744. return this._ratio;
  76745. },
  76746. enumerable: true,
  76747. configurable: true
  76748. });
  76749. /**
  76750. * Checks wether everything is ready to render a submesh to the G buffer.
  76751. * @param subMesh the submesh to check readiness for
  76752. * @param useInstances is the mesh drawn using instance or not
  76753. * @returns true if ready otherwise false
  76754. */
  76755. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76756. var material = subMesh.getMaterial();
  76757. if (material && material.disableDepthWrite) {
  76758. return false;
  76759. }
  76760. var defines = [];
  76761. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76762. var mesh = subMesh.getMesh();
  76763. // Alpha test
  76764. if (material && material.needAlphaTesting()) {
  76765. defines.push("#define ALPHATEST");
  76766. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76767. attribs.push(BABYLON.VertexBuffer.UVKind);
  76768. defines.push("#define UV1");
  76769. }
  76770. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76771. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76772. defines.push("#define UV2");
  76773. }
  76774. }
  76775. // Buffers
  76776. if (this._enablePosition) {
  76777. defines.push("#define POSITION");
  76778. }
  76779. // Bones
  76780. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76781. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76782. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76783. if (mesh.numBoneInfluencers > 4) {
  76784. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76785. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76786. }
  76787. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76788. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76789. }
  76790. else {
  76791. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76792. }
  76793. // Instances
  76794. if (useInstances) {
  76795. defines.push("#define INSTANCES");
  76796. attribs.push("world0");
  76797. attribs.push("world1");
  76798. attribs.push("world2");
  76799. attribs.push("world3");
  76800. }
  76801. // Get correct effect
  76802. var join = defines.join("\n");
  76803. if (this._cachedDefines !== join) {
  76804. this._cachedDefines = join;
  76805. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76806. }
  76807. return this._effect.isReady();
  76808. };
  76809. /**
  76810. * Gets the current underlying G Buffer.
  76811. * @returns the buffer
  76812. */
  76813. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76814. return this._multiRenderTarget;
  76815. };
  76816. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76817. /**
  76818. * Gets the number of samples used to render the buffer (anti aliasing).
  76819. */
  76820. get: function () {
  76821. return this._multiRenderTarget.samples;
  76822. },
  76823. /**
  76824. * Sets the number of samples used to render the buffer (anti aliasing).
  76825. */
  76826. set: function (value) {
  76827. this._multiRenderTarget.samples = value;
  76828. },
  76829. enumerable: true,
  76830. configurable: true
  76831. });
  76832. /**
  76833. * Disposes the renderer and frees up associated resources.
  76834. */
  76835. GeometryBufferRenderer.prototype.dispose = function () {
  76836. this.getGBuffer().dispose();
  76837. };
  76838. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76839. var _this = this;
  76840. var engine = this._scene.getEngine();
  76841. var count = this._enablePosition ? 3 : 2;
  76842. 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 });
  76843. if (!this.isSupported) {
  76844. return;
  76845. }
  76846. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76847. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76848. this._multiRenderTarget.refreshRate = 1;
  76849. this._multiRenderTarget.renderParticles = false;
  76850. this._multiRenderTarget.renderList = null;
  76851. // set default depth value to 1.0 (far away)
  76852. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76853. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76854. });
  76855. // Custom render function
  76856. var renderSubMesh = function (subMesh) {
  76857. var mesh = subMesh.getRenderingMesh();
  76858. var scene = _this._scene;
  76859. var engine = scene.getEngine();
  76860. var material = subMesh.getMaterial();
  76861. if (!material) {
  76862. return;
  76863. }
  76864. // Culling
  76865. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76866. // Managing instances
  76867. var batch = mesh._getInstancesRenderList(subMesh._id);
  76868. if (batch.mustReturn) {
  76869. return;
  76870. }
  76871. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76872. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76873. engine.enableEffect(_this._effect);
  76874. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76875. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76876. _this._effect.setMatrix("view", scene.getViewMatrix());
  76877. // Alpha test
  76878. if (material && material.needAlphaTesting()) {
  76879. var alphaTexture = material.getAlphaTestTexture();
  76880. if (alphaTexture) {
  76881. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76882. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76883. }
  76884. }
  76885. // Bones
  76886. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76887. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76888. }
  76889. // Draw
  76890. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76891. }
  76892. };
  76893. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76894. var index;
  76895. if (depthOnlySubMeshes.length) {
  76896. engine.setColorWrite(false);
  76897. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76898. renderSubMesh(depthOnlySubMeshes.data[index]);
  76899. }
  76900. engine.setColorWrite(true);
  76901. }
  76902. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76903. renderSubMesh(opaqueSubMeshes.data[index]);
  76904. }
  76905. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76906. renderSubMesh(alphaTestSubMeshes.data[index]);
  76907. }
  76908. };
  76909. };
  76910. return GeometryBufferRenderer;
  76911. }());
  76912. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76913. })(BABYLON || (BABYLON = {}));
  76914. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76915. var BABYLON;
  76916. (function (BABYLON) {
  76917. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  76918. get: function () {
  76919. this._geometryBufferRenderer;
  76920. },
  76921. set: function (value) {
  76922. if (value && value.isSupported) {
  76923. this._geometryBufferRenderer = value;
  76924. }
  76925. ;
  76926. },
  76927. enumerable: true,
  76928. configurable: true
  76929. });
  76930. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  76931. if (ratio === void 0) { ratio = 1; }
  76932. if (this._geometryBufferRenderer) {
  76933. return this._geometryBufferRenderer;
  76934. }
  76935. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  76936. if (!this._geometryBufferRenderer.isSupported) {
  76937. this._geometryBufferRenderer = null;
  76938. }
  76939. return this._geometryBufferRenderer;
  76940. };
  76941. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  76942. if (!this._geometryBufferRenderer) {
  76943. return;
  76944. }
  76945. this._geometryBufferRenderer.dispose();
  76946. this._geometryBufferRenderer = null;
  76947. };
  76948. /**
  76949. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer usefull
  76950. * in several rendering techniques.
  76951. */
  76952. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  76953. /**
  76954. * Creates a new instance of the component for the given scene
  76955. * @param scene Defines the scene to register the component in
  76956. */
  76957. function GeometryBufferRendererSceneComponent(scene) {
  76958. /**
  76959. * The component name helpfull to identify the component in the list of scene components.
  76960. */
  76961. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  76962. this.scene = scene;
  76963. }
  76964. /**
  76965. * Registers the component in a given scene
  76966. */
  76967. GeometryBufferRendererSceneComponent.prototype.register = function () {
  76968. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  76969. };
  76970. /**
  76971. * Rebuilds the elements related to this component in case of
  76972. * context lost for instance.
  76973. */
  76974. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  76975. // Nothing to do for this component
  76976. };
  76977. /**
  76978. * Disposes the component and the associated ressources
  76979. */
  76980. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  76981. // Nothing to do for this component
  76982. };
  76983. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76984. if (this.scene._geometryBufferRenderer) {
  76985. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  76986. }
  76987. };
  76988. return GeometryBufferRendererSceneComponent;
  76989. }());
  76990. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  76991. })(BABYLON || (BABYLON = {}));
  76992. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  76993. var BABYLON;
  76994. (function (BABYLON) {
  76995. var SSAORenderingPipeline = /** @class */ (function (_super) {
  76996. __extends(SSAORenderingPipeline, _super);
  76997. /**
  76998. * @constructor
  76999. * @param {string} name - The rendering pipeline name
  77000. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77001. * @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 }
  77002. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77003. */
  77004. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  77005. var _this = _super.call(this, scene.getEngine(), name) || this;
  77006. // Members
  77007. /**
  77008. * The PassPostProcess id in the pipeline that contains the original scene color
  77009. */
  77010. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  77011. /**
  77012. * The SSAO PostProcess id in the pipeline
  77013. */
  77014. _this.SSAORenderEffect = "SSAORenderEffect";
  77015. /**
  77016. * The horizontal blur PostProcess id in the pipeline
  77017. */
  77018. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77019. /**
  77020. * The vertical blur PostProcess id in the pipeline
  77021. */
  77022. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77023. /**
  77024. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77025. */
  77026. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77027. /**
  77028. * The output strength of the SSAO post-process. Default value is 1.0.
  77029. */
  77030. _this.totalStrength = 1.0;
  77031. /**
  77032. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  77033. */
  77034. _this.radius = 0.0001;
  77035. /**
  77036. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  77037. * Must not be equal to fallOff and superior to fallOff.
  77038. * Default value is 0.975
  77039. */
  77040. _this.area = 0.0075;
  77041. /**
  77042. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  77043. * Must not be equal to area and inferior to area.
  77044. * Default value is 0.0
  77045. */
  77046. _this.fallOff = 0.000001;
  77047. /**
  77048. * The base color of the SSAO post-process
  77049. * The final result is "base + ssao" between [0, 1]
  77050. */
  77051. _this.base = 0.5;
  77052. _this._firstUpdate = true;
  77053. _this._scene = scene;
  77054. // Set up assets
  77055. _this._createRandomTexture();
  77056. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  77057. var ssaoRatio = ratio.ssaoRatio || ratio;
  77058. var combineRatio = ratio.combineRatio || ratio;
  77059. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77060. _this._createSSAOPostProcess(ssaoRatio);
  77061. _this._createBlurPostProcess(ssaoRatio);
  77062. _this._createSSAOCombinePostProcess(combineRatio);
  77063. // Set up pipeline
  77064. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77065. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77066. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77067. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77068. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77069. // Finish
  77070. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77071. if (cameras)
  77072. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77073. return _this;
  77074. }
  77075. // Public Methods
  77076. /**
  77077. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  77078. */
  77079. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  77080. if (disableDepthRender === void 0) { disableDepthRender = false; }
  77081. for (var i = 0; i < this._scene.cameras.length; i++) {
  77082. var camera = this._scene.cameras[i];
  77083. this._originalColorPostProcess.dispose(camera);
  77084. this._ssaoPostProcess.dispose(camera);
  77085. this._blurHPostProcess.dispose(camera);
  77086. this._blurVPostProcess.dispose(camera);
  77087. this._ssaoCombinePostProcess.dispose(camera);
  77088. }
  77089. this._randomTexture.dispose();
  77090. if (disableDepthRender)
  77091. this._scene.disableDepthRenderer();
  77092. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77093. _super.prototype.dispose.call(this);
  77094. };
  77095. // Private Methods
  77096. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  77097. var _this = this;
  77098. var size = 16;
  77099. 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);
  77100. 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);
  77101. this._blurHPostProcess.onActivateObservable.add(function () {
  77102. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  77103. _this._blurHPostProcess.kernel = size * dw;
  77104. });
  77105. this._blurVPostProcess.onActivateObservable.add(function () {
  77106. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  77107. _this._blurVPostProcess.kernel = size * dw;
  77108. });
  77109. };
  77110. /** @hidden */
  77111. SSAORenderingPipeline.prototype._rebuild = function () {
  77112. this._firstUpdate = true;
  77113. _super.prototype._rebuild.call(this);
  77114. };
  77115. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  77116. var _this = this;
  77117. var numSamples = 16;
  77118. var sampleSphere = [
  77119. 0.5381, 0.1856, -0.4319,
  77120. 0.1379, 0.2486, 0.4430,
  77121. 0.3371, 0.5679, -0.0057,
  77122. -0.6999, -0.0451, -0.0019,
  77123. 0.0689, -0.1598, -0.8547,
  77124. 0.0560, 0.0069, -0.1843,
  77125. -0.0146, 0.1402, 0.0762,
  77126. 0.0100, -0.1924, -0.0344,
  77127. -0.3577, -0.5301, -0.4358,
  77128. -0.3169, 0.1063, 0.0158,
  77129. 0.0103, -0.5869, 0.0046,
  77130. -0.0897, -0.4940, 0.3287,
  77131. 0.7119, -0.0154, -0.0918,
  77132. -0.0533, 0.0596, -0.5411,
  77133. 0.0352, -0.0631, 0.5460,
  77134. -0.4776, 0.2847, -0.0271
  77135. ];
  77136. var samplesFactor = 1.0 / numSamples;
  77137. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  77138. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  77139. "area", "fallOff", "base", "range", "viewport"
  77140. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  77141. this._ssaoPostProcess.onApply = function (effect) {
  77142. if (_this._firstUpdate) {
  77143. effect.setArray3("sampleSphere", sampleSphere);
  77144. effect.setFloat("samplesFactor", samplesFactor);
  77145. effect.setFloat("randTextureTiles", 4.0);
  77146. }
  77147. effect.setFloat("totalStrength", _this.totalStrength);
  77148. effect.setFloat("radius", _this.radius);
  77149. effect.setFloat("area", _this.area);
  77150. effect.setFloat("fallOff", _this.fallOff);
  77151. effect.setFloat("base", _this.base);
  77152. effect.setTexture("textureSampler", _this._depthTexture);
  77153. effect.setTexture("randomSampler", _this._randomTexture);
  77154. };
  77155. };
  77156. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  77157. var _this = this;
  77158. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77159. this._ssaoCombinePostProcess.onApply = function (effect) {
  77160. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  77161. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  77162. };
  77163. };
  77164. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  77165. var size = 512;
  77166. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77167. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77168. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77169. var context = this._randomTexture.getContext();
  77170. var rand = function (min, max) {
  77171. return Math.random() * (max - min) + min;
  77172. };
  77173. var randVector = BABYLON.Vector3.Zero();
  77174. for (var x = 0; x < size; x++) {
  77175. for (var y = 0; y < size; y++) {
  77176. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  77177. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  77178. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  77179. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  77180. context.fillRect(x, y, 1, 1);
  77181. }
  77182. }
  77183. this._randomTexture.update(false);
  77184. };
  77185. __decorate([
  77186. BABYLON.serialize()
  77187. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  77188. __decorate([
  77189. BABYLON.serialize()
  77190. ], SSAORenderingPipeline.prototype, "radius", void 0);
  77191. __decorate([
  77192. BABYLON.serialize()
  77193. ], SSAORenderingPipeline.prototype, "area", void 0);
  77194. __decorate([
  77195. BABYLON.serialize()
  77196. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  77197. __decorate([
  77198. BABYLON.serialize()
  77199. ], SSAORenderingPipeline.prototype, "base", void 0);
  77200. return SSAORenderingPipeline;
  77201. }(BABYLON.PostProcessRenderPipeline));
  77202. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  77203. })(BABYLON || (BABYLON = {}));
  77204. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  77205. var BABYLON;
  77206. (function (BABYLON) {
  77207. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  77208. __extends(SSAO2RenderingPipeline, _super);
  77209. /**
  77210. * @constructor
  77211. * @param {string} name - The rendering pipeline name
  77212. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77213. * @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 }
  77214. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77215. */
  77216. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  77217. var _this = _super.call(this, scene.getEngine(), name) || this;
  77218. // Members
  77219. /**
  77220. * The PassPostProcess id in the pipeline that contains the original scene color
  77221. */
  77222. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  77223. /**
  77224. * The SSAO PostProcess id in the pipeline
  77225. */
  77226. _this.SSAORenderEffect = "SSAORenderEffect";
  77227. /**
  77228. * The horizontal blur PostProcess id in the pipeline
  77229. */
  77230. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77231. /**
  77232. * The vertical blur PostProcess id in the pipeline
  77233. */
  77234. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77235. /**
  77236. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77237. */
  77238. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77239. /**
  77240. * The output strength of the SSAO post-process. Default value is 1.0.
  77241. */
  77242. _this.totalStrength = 1.0;
  77243. /**
  77244. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  77245. */
  77246. _this.maxZ = 100.0;
  77247. /**
  77248. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  77249. */
  77250. _this.minZAspect = 0.2;
  77251. _this._samples = 8;
  77252. _this._textureSamples = 1;
  77253. /**
  77254. * Are we using bilateral blur ?
  77255. */
  77256. _this._expensiveBlur = true;
  77257. /**
  77258. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  77259. */
  77260. _this.radius = 2.0;
  77261. /**
  77262. * The base color of the SSAO post-process
  77263. * The final result is "base + ssao" between [0, 1]
  77264. */
  77265. _this.base = 0;
  77266. _this._firstUpdate = true;
  77267. _this._bits = new Uint32Array(1);
  77268. _this._scene = scene;
  77269. _this._ratio = ratio;
  77270. if (!_this.isSupported) {
  77271. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  77272. return _this;
  77273. }
  77274. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  77275. var blurRatio = _this._ratio.blurRatio || ratio;
  77276. // Set up assets
  77277. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  77278. _this._createRandomTexture();
  77279. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  77280. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  77281. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77282. _this._originalColorPostProcess.samples = _this.textureSamples;
  77283. _this._createSSAOPostProcess(1.0);
  77284. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  77285. _this._createSSAOCombinePostProcess(blurRatio);
  77286. // Set up pipeline
  77287. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77288. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77289. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77290. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77291. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77292. // Finish
  77293. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77294. if (cameras)
  77295. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77296. return _this;
  77297. }
  77298. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  77299. get: function () {
  77300. return this._samples;
  77301. },
  77302. /**
  77303. * Number of samples used for the SSAO calculations. Default value is 8
  77304. */
  77305. set: function (n) {
  77306. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  77307. this._samples = n;
  77308. this._sampleSphere = this._generateHemisphere();
  77309. this._firstUpdate = true;
  77310. },
  77311. enumerable: true,
  77312. configurable: true
  77313. });
  77314. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  77315. get: function () {
  77316. return this._textureSamples;
  77317. },
  77318. /**
  77319. * Number of samples to use for antialiasing
  77320. */
  77321. set: function (n) {
  77322. this._textureSamples = n;
  77323. this._originalColorPostProcess.samples = n;
  77324. this._blurHPostProcess.samples = n;
  77325. this._blurVPostProcess.samples = n;
  77326. this._ssaoPostProcess.samples = n;
  77327. this._ssaoCombinePostProcess.samples = n;
  77328. },
  77329. enumerable: true,
  77330. configurable: true
  77331. });
  77332. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  77333. get: function () {
  77334. return this._expensiveBlur;
  77335. },
  77336. set: function (b) {
  77337. 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"]);
  77338. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  77339. this._expensiveBlur = b;
  77340. this._firstUpdate = true;
  77341. },
  77342. enumerable: true,
  77343. configurable: true
  77344. });
  77345. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  77346. /**
  77347. * Support test.
  77348. */
  77349. get: function () {
  77350. var engine = BABYLON.Engine.LastCreatedEngine;
  77351. if (!engine) {
  77352. return false;
  77353. }
  77354. return engine.getCaps().drawBuffersExtension;
  77355. },
  77356. enumerable: true,
  77357. configurable: true
  77358. });
  77359. // Public Methods
  77360. /**
  77361. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  77362. */
  77363. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  77364. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  77365. for (var i = 0; i < this._scene.cameras.length; i++) {
  77366. var camera = this._scene.cameras[i];
  77367. this._originalColorPostProcess.dispose(camera);
  77368. this._ssaoPostProcess.dispose(camera);
  77369. this._blurHPostProcess.dispose(camera);
  77370. this._blurVPostProcess.dispose(camera);
  77371. this._ssaoCombinePostProcess.dispose(camera);
  77372. }
  77373. this._randomTexture.dispose();
  77374. if (disableGeometryBufferRenderer)
  77375. this._scene.disableGeometryBufferRenderer();
  77376. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77377. _super.prototype.dispose.call(this);
  77378. };
  77379. // Private Methods
  77380. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  77381. var _this = this;
  77382. this._samplerOffsets = [];
  77383. var expensive = this.expensiveBlur;
  77384. for (var i = -8; i < 8; i++) {
  77385. this._samplerOffsets.push(i * 2 + 0.5);
  77386. }
  77387. 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");
  77388. this._blurHPostProcess.onApply = function (effect) {
  77389. if (!_this._scene.activeCamera) {
  77390. return;
  77391. }
  77392. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  77393. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77394. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77395. effect.setFloat("radius", _this.radius);
  77396. effect.setTexture("depthSampler", _this._depthTexture);
  77397. if (_this._firstUpdate) {
  77398. effect.setArray("samplerOffsets", _this._samplerOffsets);
  77399. }
  77400. };
  77401. 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");
  77402. this._blurVPostProcess.onApply = function (effect) {
  77403. if (!_this._scene.activeCamera) {
  77404. return;
  77405. }
  77406. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  77407. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77408. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77409. effect.setFloat("radius", _this.radius);
  77410. effect.setTexture("depthSampler", _this._depthTexture);
  77411. if (_this._firstUpdate) {
  77412. effect.setArray("samplerOffsets", _this._samplerOffsets);
  77413. _this._firstUpdate = false;
  77414. }
  77415. };
  77416. this._blurHPostProcess.samples = this.textureSamples;
  77417. this._blurVPostProcess.samples = this.textureSamples;
  77418. };
  77419. /** @hidden */
  77420. SSAO2RenderingPipeline.prototype._rebuild = function () {
  77421. this._firstUpdate = true;
  77422. _super.prototype._rebuild.call(this);
  77423. };
  77424. //Van der Corput radical inverse
  77425. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  77426. this._bits[0] = i;
  77427. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  77428. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  77429. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  77430. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  77431. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  77432. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  77433. };
  77434. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  77435. return [i / n, this._radicalInverse_VdC(i)];
  77436. };
  77437. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  77438. var phi = v * 2.0 * Math.PI;
  77439. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  77440. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  77441. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  77442. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  77443. };
  77444. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  77445. var numSamples = this.samples;
  77446. var result = [];
  77447. var vector;
  77448. var i = 0;
  77449. while (i < numSamples) {
  77450. if (numSamples < 16) {
  77451. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  77452. }
  77453. else {
  77454. var rand = this._hammersley(i, numSamples);
  77455. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  77456. }
  77457. result.push(vector.x, vector.y, vector.z);
  77458. i++;
  77459. }
  77460. return result;
  77461. };
  77462. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  77463. var _this = this;
  77464. var numSamples = this.samples;
  77465. this._sampleSphere = this._generateHemisphere();
  77466. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  77467. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  77468. "base", "range", "projection", "near", "far", "texelSize",
  77469. "xViewport", "yViewport", "maxZ", "minZAspect"
  77470. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  77471. this._ssaoPostProcess.onApply = function (effect) {
  77472. if (_this._firstUpdate) {
  77473. effect.setArray3("sampleSphere", _this._sampleSphere);
  77474. effect.setFloat("randTextureTiles", 32.0);
  77475. }
  77476. if (!_this._scene.activeCamera) {
  77477. return;
  77478. }
  77479. effect.setFloat("samplesFactor", 1 / _this.samples);
  77480. effect.setFloat("totalStrength", _this.totalStrength);
  77481. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  77482. effect.setFloat("radius", _this.radius);
  77483. effect.setFloat("maxZ", _this.maxZ);
  77484. effect.setFloat("minZAspect", _this.minZAspect);
  77485. effect.setFloat("base", _this.base);
  77486. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77487. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77488. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  77489. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  77490. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  77491. effect.setTexture("textureSampler", _this._depthTexture);
  77492. effect.setTexture("normalSampler", _this._normalTexture);
  77493. effect.setTexture("randomSampler", _this._randomTexture);
  77494. };
  77495. this._ssaoPostProcess.samples = this.textureSamples;
  77496. };
  77497. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  77498. var _this = this;
  77499. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77500. this._ssaoCombinePostProcess.onApply = function (effect) {
  77501. var viewport = _this._scene.activeCamera.viewport;
  77502. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  77503. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  77504. };
  77505. this._ssaoCombinePostProcess.samples = this.textureSamples;
  77506. };
  77507. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  77508. var size = 128;
  77509. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77510. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77511. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77512. var context = this._randomTexture.getContext();
  77513. var rand = function (min, max) {
  77514. return Math.random() * (max - min) + min;
  77515. };
  77516. var randVector = BABYLON.Vector3.Zero();
  77517. for (var x = 0; x < size; x++) {
  77518. for (var y = 0; y < size; y++) {
  77519. randVector.x = rand(0.0, 1.0);
  77520. randVector.y = rand(0.0, 1.0);
  77521. randVector.z = 0.0;
  77522. randVector.normalize();
  77523. randVector.scaleInPlace(255);
  77524. randVector.x = Math.floor(randVector.x);
  77525. randVector.y = Math.floor(randVector.y);
  77526. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  77527. context.fillRect(x, y, 1, 1);
  77528. }
  77529. }
  77530. this._randomTexture.update(false);
  77531. };
  77532. /**
  77533. * Serialize the rendering pipeline (Used when exporting)
  77534. * @returns the serialized object
  77535. */
  77536. SSAO2RenderingPipeline.prototype.serialize = function () {
  77537. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77538. serializationObject.customType = "SSAO2RenderingPipeline";
  77539. return serializationObject;
  77540. };
  77541. /**
  77542. * Parse the serialized pipeline
  77543. * @param source Source pipeline.
  77544. * @param scene The scene to load the pipeline to.
  77545. * @param rootUrl The URL of the serialized pipeline.
  77546. * @returns An instantiated pipeline from the serialized object.
  77547. */
  77548. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  77549. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  77550. };
  77551. __decorate([
  77552. BABYLON.serialize()
  77553. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  77554. __decorate([
  77555. BABYLON.serialize()
  77556. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  77557. __decorate([
  77558. BABYLON.serialize()
  77559. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  77560. __decorate([
  77561. BABYLON.serialize("samples")
  77562. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  77563. __decorate([
  77564. BABYLON.serialize("textureSamples")
  77565. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  77566. __decorate([
  77567. BABYLON.serialize()
  77568. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  77569. __decorate([
  77570. BABYLON.serialize("expensiveBlur")
  77571. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  77572. __decorate([
  77573. BABYLON.serialize()
  77574. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  77575. __decorate([
  77576. BABYLON.serialize()
  77577. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  77578. return SSAO2RenderingPipeline;
  77579. }(BABYLON.PostProcessRenderPipeline));
  77580. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  77581. })(BABYLON || (BABYLON = {}));
  77582. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  77583. // BABYLON.JS Chromatic Aberration GLSL Shader
  77584. // Author: Olivier Guyot
  77585. // Separates very slightly R, G and B colors on the edges of the screen
  77586. // Inspired by Francois Tarlier & Martins Upitis
  77587. var BABYLON;
  77588. (function (BABYLON) {
  77589. var LensRenderingPipeline = /** @class */ (function (_super) {
  77590. __extends(LensRenderingPipeline, _super);
  77591. /**
  77592. * @constructor
  77593. *
  77594. * Effect parameters are as follow:
  77595. * {
  77596. * chromatic_aberration: number; // from 0 to x (1 for realism)
  77597. * edge_blur: number; // from 0 to x (1 for realism)
  77598. * distortion: number; // from 0 to x (1 for realism)
  77599. * grain_amount: number; // from 0 to 1
  77600. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  77601. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  77602. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  77603. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  77604. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  77605. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  77606. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  77607. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  77608. * }
  77609. * Note: if an effect parameter is unset, effect is disabled
  77610. *
  77611. * @param {string} name - The rendering pipeline name
  77612. * @param {object} parameters - An object containing all parameters (see above)
  77613. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77614. * @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)
  77615. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77616. */
  77617. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  77618. if (ratio === void 0) { ratio = 1.0; }
  77619. var _this = _super.call(this, scene.getEngine(), name) || this;
  77620. // Lens effects can be of the following:
  77621. // - chromatic aberration (slight shift of RGB colors)
  77622. // - blur on the edge of the lens
  77623. // - lens distortion
  77624. // - depth-of-field blur & highlights enhancing
  77625. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  77626. // - grain effect (noise or custom texture)
  77627. // Two additional texture samplers are needed:
  77628. // - depth map (for depth-of-field)
  77629. // - grain texture
  77630. /**
  77631. * The chromatic aberration PostProcess id in the pipeline
  77632. */
  77633. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  77634. /**
  77635. * The highlights enhancing PostProcess id in the pipeline
  77636. */
  77637. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  77638. /**
  77639. * The depth-of-field PostProcess id in the pipeline
  77640. */
  77641. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  77642. _this._scene = scene;
  77643. // Fetch texture samplers
  77644. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  77645. if (parameters.grain_texture) {
  77646. _this._grainTexture = parameters.grain_texture;
  77647. }
  77648. else {
  77649. _this._createGrainTexture();
  77650. }
  77651. // save parameters
  77652. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  77653. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  77654. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  77655. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  77656. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  77657. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  77658. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  77659. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  77660. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  77661. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  77662. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  77663. // Create effects
  77664. _this._createChromaticAberrationPostProcess(ratio);
  77665. _this._createHighlightsPostProcess(ratio);
  77666. _this._createDepthOfFieldPostProcess(ratio / 4);
  77667. // Set up pipeline
  77668. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  77669. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  77670. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  77671. if (_this._highlightsGain === -1) {
  77672. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  77673. }
  77674. // Finish
  77675. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77676. if (cameras) {
  77677. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77678. }
  77679. return _this;
  77680. }
  77681. // public methods (self explanatory)
  77682. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  77683. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  77684. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  77685. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  77686. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  77687. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  77688. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  77689. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  77690. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  77691. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  77692. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  77693. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  77694. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  77695. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  77696. };
  77697. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  77698. this._highlightsPostProcess.updateEffect();
  77699. };
  77700. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  77701. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  77702. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  77703. this._highlightsGain = amount;
  77704. };
  77705. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  77706. if (this._highlightsGain === -1) {
  77707. this._highlightsGain = 1.0;
  77708. }
  77709. this._highlightsThreshold = amount;
  77710. };
  77711. LensRenderingPipeline.prototype.disableHighlights = function () {
  77712. this._highlightsGain = -1;
  77713. };
  77714. /**
  77715. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  77716. */
  77717. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  77718. if (disableDepthRender === void 0) { disableDepthRender = false; }
  77719. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77720. this._chromaticAberrationPostProcess = null;
  77721. this._highlightsPostProcess = null;
  77722. this._depthOfFieldPostProcess = null;
  77723. this._grainTexture.dispose();
  77724. if (disableDepthRender)
  77725. this._scene.disableDepthRenderer();
  77726. };
  77727. // colors shifting and distortion
  77728. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  77729. var _this = this;
  77730. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  77731. [], // samplers
  77732. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77733. this._chromaticAberrationPostProcess.onApply = function (effect) {
  77734. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  77735. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77736. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77737. effect.setFloat('radialIntensity', 1);
  77738. effect.setFloat2('direction', 17, 17);
  77739. effect.setFloat2('centerPosition', 0.5, 0.5);
  77740. };
  77741. };
  77742. // highlights enhancing
  77743. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  77744. var _this = this;
  77745. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  77746. [], // samplers
  77747. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  77748. this._highlightsPostProcess.onApply = function (effect) {
  77749. effect.setFloat('gain', _this._highlightsGain);
  77750. effect.setFloat('threshold', _this._highlightsThreshold);
  77751. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  77752. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77753. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77754. };
  77755. };
  77756. // colors shifting and distortion
  77757. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  77758. var _this = this;
  77759. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  77760. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  77761. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  77762. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77763. this._depthOfFieldPostProcess.onApply = function (effect) {
  77764. effect.setTexture("depthSampler", _this._depthTexture);
  77765. effect.setTexture("grainSampler", _this._grainTexture);
  77766. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  77767. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  77768. effect.setFloat('grain_amount', _this._grainAmount);
  77769. effect.setBool('blur_noise', _this._blurNoise);
  77770. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77771. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77772. effect.setFloat('distortion', _this._distortion);
  77773. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  77774. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  77775. effect.setFloat('aperture', _this._dofAperture);
  77776. effect.setFloat('darken', _this._dofDarken);
  77777. effect.setFloat('edge_blur', _this._edgeBlur);
  77778. effect.setBool('highlights', (_this._highlightsGain !== -1));
  77779. if (_this._scene.activeCamera) {
  77780. effect.setFloat('near', _this._scene.activeCamera.minZ);
  77781. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  77782. }
  77783. };
  77784. };
  77785. // creates a black and white random noise texture, 512x512
  77786. LensRenderingPipeline.prototype._createGrainTexture = function () {
  77787. var size = 512;
  77788. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77789. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77790. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77791. var context = this._grainTexture.getContext();
  77792. var rand = function (min, max) {
  77793. return Math.random() * (max - min) + min;
  77794. };
  77795. var value;
  77796. for (var x = 0; x < size; x++) {
  77797. for (var y = 0; y < size; y++) {
  77798. value = Math.floor(rand(0.42, 0.58) * 255);
  77799. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  77800. context.fillRect(x, y, 1, 1);
  77801. }
  77802. }
  77803. this._grainTexture.update(false);
  77804. };
  77805. return LensRenderingPipeline;
  77806. }(BABYLON.PostProcessRenderPipeline));
  77807. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  77808. })(BABYLON || (BABYLON = {}));
  77809. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  77810. var BABYLON;
  77811. (function (BABYLON) {
  77812. var StandardRenderingPipeline = /** @class */ (function (_super) {
  77813. __extends(StandardRenderingPipeline, _super);
  77814. /**
  77815. * @constructor
  77816. * @param {string} name - The rendering pipeline name
  77817. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77818. * @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)
  77819. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  77820. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77821. */
  77822. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  77823. if (originalPostProcess === void 0) { originalPostProcess = null; }
  77824. var _this = _super.call(this, scene.getEngine(), name) || this;
  77825. _this.downSampleX4PostProcess = null;
  77826. _this.brightPassPostProcess = null;
  77827. _this.blurHPostProcesses = [];
  77828. _this.blurVPostProcesses = [];
  77829. _this.textureAdderPostProcess = null;
  77830. _this.volumetricLightPostProcess = null;
  77831. _this.volumetricLightSmoothXPostProcess = null;
  77832. _this.volumetricLightSmoothYPostProcess = null;
  77833. _this.volumetricLightMergePostProces = null;
  77834. _this.volumetricLightFinalPostProcess = null;
  77835. _this.luminancePostProcess = null;
  77836. _this.luminanceDownSamplePostProcesses = [];
  77837. _this.hdrPostProcess = null;
  77838. _this.textureAdderFinalPostProcess = null;
  77839. _this.lensFlareFinalPostProcess = null;
  77840. _this.hdrFinalPostProcess = null;
  77841. _this.lensFlarePostProcess = null;
  77842. _this.lensFlareComposePostProcess = null;
  77843. _this.motionBlurPostProcess = null;
  77844. _this.depthOfFieldPostProcess = null;
  77845. // Values
  77846. _this.brightThreshold = 1.0;
  77847. _this.blurWidth = 512.0;
  77848. _this.horizontalBlur = false;
  77849. _this.exposure = 1.0;
  77850. _this.lensTexture = null;
  77851. _this.volumetricLightCoefficient = 0.2;
  77852. _this.volumetricLightPower = 4.0;
  77853. _this.volumetricLightBlurScale = 64.0;
  77854. _this.sourceLight = null;
  77855. _this.hdrMinimumLuminance = 1.0;
  77856. _this.hdrDecreaseRate = 0.5;
  77857. _this.hdrIncreaseRate = 0.5;
  77858. _this.lensColorTexture = null;
  77859. _this.lensFlareStrength = 20.0;
  77860. _this.lensFlareGhostDispersal = 1.4;
  77861. _this.lensFlareHaloWidth = 0.7;
  77862. _this.lensFlareDistortionStrength = 16.0;
  77863. _this.lensStarTexture = null;
  77864. _this.lensFlareDirtTexture = null;
  77865. _this.depthOfFieldDistance = 10.0;
  77866. _this.depthOfFieldBlurWidth = 64.0;
  77867. _this.motionStrength = 1.0;
  77868. // IAnimatable
  77869. _this.animations = [];
  77870. _this._currentDepthOfFieldSource = null;
  77871. _this._hdrCurrentLuminance = 1.0;
  77872. // Getters and setters
  77873. _this._bloomEnabled = true;
  77874. _this._depthOfFieldEnabled = false;
  77875. _this._vlsEnabled = false;
  77876. _this._lensFlareEnabled = false;
  77877. _this._hdrEnabled = false;
  77878. _this._motionBlurEnabled = false;
  77879. _this._motionBlurSamples = 64.0;
  77880. _this._volumetricLightStepsCount = 50.0;
  77881. _this._cameras = cameras || [];
  77882. // Initialize
  77883. _this._scene = scene;
  77884. _this._basePostProcess = originalPostProcess;
  77885. _this._ratio = ratio;
  77886. // Misc
  77887. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77888. // Finish
  77889. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77890. _this._buildPipeline();
  77891. return _this;
  77892. }
  77893. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  77894. get: function () {
  77895. return this._bloomEnabled;
  77896. },
  77897. set: function (enabled) {
  77898. if (this._bloomEnabled === enabled) {
  77899. return;
  77900. }
  77901. this._bloomEnabled = enabled;
  77902. this._buildPipeline();
  77903. },
  77904. enumerable: true,
  77905. configurable: true
  77906. });
  77907. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  77908. get: function () {
  77909. return this._depthOfFieldEnabled;
  77910. },
  77911. set: function (enabled) {
  77912. if (this._depthOfFieldEnabled === enabled) {
  77913. return;
  77914. }
  77915. this._depthOfFieldEnabled = enabled;
  77916. this._buildPipeline();
  77917. },
  77918. enumerable: true,
  77919. configurable: true
  77920. });
  77921. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  77922. get: function () {
  77923. return this._lensFlareEnabled;
  77924. },
  77925. set: function (enabled) {
  77926. if (this._lensFlareEnabled === enabled) {
  77927. return;
  77928. }
  77929. this._lensFlareEnabled = enabled;
  77930. this._buildPipeline();
  77931. },
  77932. enumerable: true,
  77933. configurable: true
  77934. });
  77935. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  77936. get: function () {
  77937. return this._hdrEnabled;
  77938. },
  77939. set: function (enabled) {
  77940. if (this._hdrEnabled === enabled) {
  77941. return;
  77942. }
  77943. this._hdrEnabled = enabled;
  77944. this._buildPipeline();
  77945. },
  77946. enumerable: true,
  77947. configurable: true
  77948. });
  77949. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  77950. get: function () {
  77951. return this._vlsEnabled;
  77952. },
  77953. set: function (enabled) {
  77954. if (this._vlsEnabled === enabled) {
  77955. return;
  77956. }
  77957. if (enabled) {
  77958. var geometry = this._scene.enableGeometryBufferRenderer();
  77959. if (!geometry) {
  77960. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  77961. return;
  77962. }
  77963. }
  77964. this._vlsEnabled = enabled;
  77965. this._buildPipeline();
  77966. },
  77967. enumerable: true,
  77968. configurable: true
  77969. });
  77970. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  77971. get: function () {
  77972. return this._motionBlurEnabled;
  77973. },
  77974. set: function (enabled) {
  77975. if (this._motionBlurEnabled === enabled) {
  77976. return;
  77977. }
  77978. this._motionBlurEnabled = enabled;
  77979. this._buildPipeline();
  77980. },
  77981. enumerable: true,
  77982. configurable: true
  77983. });
  77984. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  77985. get: function () {
  77986. return this._volumetricLightStepsCount;
  77987. },
  77988. set: function (count) {
  77989. if (this.volumetricLightPostProcess) {
  77990. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  77991. }
  77992. this._volumetricLightStepsCount = count;
  77993. },
  77994. enumerable: true,
  77995. configurable: true
  77996. });
  77997. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  77998. get: function () {
  77999. return this._motionBlurSamples;
  78000. },
  78001. set: function (samples) {
  78002. if (this.motionBlurPostProcess) {
  78003. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  78004. }
  78005. this._motionBlurSamples = samples;
  78006. },
  78007. enumerable: true,
  78008. configurable: true
  78009. });
  78010. StandardRenderingPipeline.prototype._buildPipeline = function () {
  78011. var _this = this;
  78012. var ratio = this._ratio;
  78013. var scene = this._scene;
  78014. this._disposePostProcesses();
  78015. this._reset();
  78016. // Create pass post-process
  78017. if (!this._basePostProcess) {
  78018. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  78019. this.originalPostProcess.onApply = function (effect) {
  78020. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  78021. };
  78022. }
  78023. else {
  78024. this.originalPostProcess = this._basePostProcess;
  78025. }
  78026. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  78027. this._currentDepthOfFieldSource = this.originalPostProcess;
  78028. if (this._bloomEnabled) {
  78029. // Create down sample X4 post-process
  78030. this._createDownSampleX4PostProcess(scene, ratio / 2);
  78031. // Create bright pass post-process
  78032. this._createBrightPassPostProcess(scene, ratio / 2);
  78033. // Create gaussian blur post-processes (down sampling blurs)
  78034. this._createBlurPostProcesses(scene, ratio / 4, 1);
  78035. // Create texture adder post-process
  78036. this._createTextureAdderPostProcess(scene, ratio);
  78037. // Create depth-of-field source post-process
  78038. 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);
  78039. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  78040. }
  78041. if (this._vlsEnabled) {
  78042. // Create volumetric light
  78043. this._createVolumetricLightPostProcess(scene, ratio);
  78044. // Create volumetric light final post-process
  78045. 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);
  78046. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  78047. }
  78048. if (this._lensFlareEnabled) {
  78049. // Create lens flare post-process
  78050. this._createLensFlarePostProcess(scene, ratio);
  78051. // Create depth-of-field source post-process post lens-flare and disable it now
  78052. 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);
  78053. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  78054. }
  78055. if (this._hdrEnabled) {
  78056. // Create luminance
  78057. this._createLuminancePostProcesses(scene, this._floatTextureType);
  78058. // Create HDR
  78059. this._createHdrPostProcess(scene, ratio);
  78060. // Create depth-of-field source post-process post hdr and disable it now
  78061. 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);
  78062. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  78063. }
  78064. if (this._depthOfFieldEnabled) {
  78065. // Create gaussian blur used by depth-of-field
  78066. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  78067. // Create depth-of-field post-process
  78068. this._createDepthOfFieldPostProcess(scene, ratio);
  78069. }
  78070. if (this._motionBlurEnabled) {
  78071. // Create motion blur post-process
  78072. this._createMotionBlurPostProcess(scene, ratio);
  78073. }
  78074. if (this._cameras !== null) {
  78075. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78076. }
  78077. };
  78078. // Down Sample X4 Post-Processs
  78079. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  78080. var _this = this;
  78081. var downSampleX4Offsets = new Array(32);
  78082. 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);
  78083. this.downSampleX4PostProcess.onApply = function (effect) {
  78084. var id = 0;
  78085. var width = _this.downSampleX4PostProcess.width;
  78086. var height = _this.downSampleX4PostProcess.height;
  78087. for (var i = -2; i < 2; i++) {
  78088. for (var j = -2; j < 2; j++) {
  78089. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  78090. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  78091. id += 2;
  78092. }
  78093. }
  78094. effect.setArray2("dsOffsets", downSampleX4Offsets);
  78095. };
  78096. // Add to pipeline
  78097. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  78098. };
  78099. // Brightpass Post-Process
  78100. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  78101. var _this = this;
  78102. var brightOffsets = new Array(8);
  78103. 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);
  78104. this.brightPassPostProcess.onApply = function (effect) {
  78105. var sU = (1.0 / _this.brightPassPostProcess.width);
  78106. var sV = (1.0 / _this.brightPassPostProcess.height);
  78107. brightOffsets[0] = -0.5 * sU;
  78108. brightOffsets[1] = 0.5 * sV;
  78109. brightOffsets[2] = 0.5 * sU;
  78110. brightOffsets[3] = 0.5 * sV;
  78111. brightOffsets[4] = -0.5 * sU;
  78112. brightOffsets[5] = -0.5 * sV;
  78113. brightOffsets[6] = 0.5 * sU;
  78114. brightOffsets[7] = -0.5 * sV;
  78115. effect.setArray2("dsOffsets", brightOffsets);
  78116. effect.setFloat("brightThreshold", _this.brightThreshold);
  78117. };
  78118. // Add to pipeline
  78119. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  78120. };
  78121. // Create blur H&V post-processes
  78122. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  78123. var _this = this;
  78124. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  78125. var engine = scene.getEngine();
  78126. 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);
  78127. 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);
  78128. blurX.onActivateObservable.add(function () {
  78129. var dw = blurX.width / engine.getRenderWidth();
  78130. blurX.kernel = _this[blurWidthKey] * dw;
  78131. });
  78132. blurY.onActivateObservable.add(function () {
  78133. var dw = blurY.height / engine.getRenderHeight();
  78134. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  78135. });
  78136. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  78137. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  78138. this.blurHPostProcesses.push(blurX);
  78139. this.blurVPostProcesses.push(blurY);
  78140. };
  78141. // Create texture adder post-process
  78142. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  78143. var _this = this;
  78144. 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);
  78145. this.textureAdderPostProcess.onApply = function (effect) {
  78146. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  78147. effect.setTexture("lensSampler", _this.lensTexture);
  78148. effect.setFloat("exposure", _this.exposure);
  78149. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  78150. };
  78151. // Add to pipeline
  78152. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  78153. };
  78154. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  78155. var _this = this;
  78156. var geometryRenderer = scene.enableGeometryBufferRenderer();
  78157. geometryRenderer.enablePosition = true;
  78158. var geometry = geometryRenderer.getGBuffer();
  78159. // Base post-process
  78160. 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));
  78161. var depthValues = BABYLON.Vector2.Zero();
  78162. this.volumetricLightPostProcess.onApply = function (effect) {
  78163. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  78164. var generator = _this.sourceLight.getShadowGenerator();
  78165. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  78166. effect.setTexture("positionSampler", geometry.textures[2]);
  78167. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  78168. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  78169. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  78170. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  78171. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  78172. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  78173. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  78174. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  78175. effect.setVector2("depthValues", depthValues);
  78176. }
  78177. };
  78178. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  78179. // Smooth
  78180. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  78181. // Merge
  78182. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  78183. this.volumetricLightMergePostProces.onApply = function (effect) {
  78184. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  78185. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  78186. };
  78187. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  78188. };
  78189. // Create luminance
  78190. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  78191. var _this = this;
  78192. // Create luminance
  78193. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  78194. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  78195. var offsets = [];
  78196. this.luminancePostProcess.onApply = function (effect) {
  78197. var sU = (1.0 / _this.luminancePostProcess.width);
  78198. var sV = (1.0 / _this.luminancePostProcess.height);
  78199. offsets[0] = -0.5 * sU;
  78200. offsets[1] = 0.5 * sV;
  78201. offsets[2] = 0.5 * sU;
  78202. offsets[3] = 0.5 * sV;
  78203. offsets[4] = -0.5 * sU;
  78204. offsets[5] = -0.5 * sV;
  78205. offsets[6] = 0.5 * sU;
  78206. offsets[7] = -0.5 * sV;
  78207. effect.setArray2("lumOffsets", offsets);
  78208. };
  78209. // Add to pipeline
  78210. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  78211. // Create down sample luminance
  78212. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  78213. var size = Math.pow(3, i);
  78214. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  78215. if (i === 0) {
  78216. defines += "#define FINAL_DOWN_SAMPLER";
  78217. }
  78218. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  78219. this.luminanceDownSamplePostProcesses.push(postProcess);
  78220. }
  78221. // Create callbacks and add effects
  78222. var lastLuminance = this.luminancePostProcess;
  78223. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  78224. var downSampleOffsets = new Array(18);
  78225. pp.onApply = function (effect) {
  78226. if (!lastLuminance) {
  78227. return;
  78228. }
  78229. var id = 0;
  78230. for (var x = -1; x < 2; x++) {
  78231. for (var y = -1; y < 2; y++) {
  78232. downSampleOffsets[id] = x / lastLuminance.width;
  78233. downSampleOffsets[id + 1] = y / lastLuminance.height;
  78234. id += 2;
  78235. }
  78236. }
  78237. effect.setArray2("dsOffsets", downSampleOffsets);
  78238. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  78239. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  78240. lastLuminance = _this.luminancePostProcess;
  78241. }
  78242. else {
  78243. lastLuminance = pp;
  78244. }
  78245. };
  78246. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  78247. pp.onAfterRender = function (effect) {
  78248. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  78249. 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);
  78250. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  78251. };
  78252. }
  78253. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  78254. });
  78255. };
  78256. // Create HDR post-process
  78257. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  78258. var _this = this;
  78259. 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);
  78260. var outputLiminance = 1;
  78261. var time = 0;
  78262. var lastTime = 0;
  78263. this.hdrPostProcess.onApply = function (effect) {
  78264. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  78265. time += scene.getEngine().getDeltaTime();
  78266. if (outputLiminance < 0) {
  78267. outputLiminance = _this._hdrCurrentLuminance;
  78268. }
  78269. else {
  78270. var dt = (lastTime - time) / 1000.0;
  78271. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  78272. outputLiminance += _this.hdrDecreaseRate * dt;
  78273. }
  78274. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  78275. outputLiminance -= _this.hdrIncreaseRate * dt;
  78276. }
  78277. else {
  78278. outputLiminance = _this._hdrCurrentLuminance;
  78279. }
  78280. }
  78281. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  78282. effect.setFloat("averageLuminance", outputLiminance);
  78283. lastTime = time;
  78284. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  78285. };
  78286. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  78287. };
  78288. // Create lens flare post-process
  78289. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  78290. var _this = this;
  78291. 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);
  78292. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  78293. this._createBlurPostProcesses(scene, ratio / 4, 2);
  78294. 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);
  78295. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  78296. var resolution = new BABYLON.Vector2(0, 0);
  78297. // Lens flare
  78298. this.lensFlarePostProcess.onApply = function (effect) {
  78299. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  78300. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  78301. effect.setFloat("strength", _this.lensFlareStrength);
  78302. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  78303. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  78304. // Shift
  78305. resolution.x = _this.lensFlarePostProcess.width;
  78306. resolution.y = _this.lensFlarePostProcess.height;
  78307. effect.setVector2("resolution", resolution);
  78308. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  78309. };
  78310. // Compose
  78311. 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);
  78312. 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);
  78313. this.lensFlareComposePostProcess.onApply = function (effect) {
  78314. if (!_this._scene.activeCamera) {
  78315. return;
  78316. }
  78317. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  78318. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  78319. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  78320. // Lens start rotation matrix
  78321. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  78322. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  78323. 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));
  78324. camRot *= 4.0;
  78325. 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);
  78326. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  78327. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  78328. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  78329. };
  78330. };
  78331. // Create depth-of-field post-process
  78332. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  78333. var _this = this;
  78334. 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);
  78335. this.depthOfFieldPostProcess.onApply = function (effect) {
  78336. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  78337. effect.setTexture("depthSampler", _this._getDepthTexture());
  78338. effect.setFloat("distance", _this.depthOfFieldDistance);
  78339. };
  78340. // Add to pipeline
  78341. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  78342. };
  78343. // Create motion blur post-process
  78344. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  78345. var _this = this;
  78346. 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);
  78347. var motionScale = 0;
  78348. var prevViewProjection = BABYLON.Matrix.Identity();
  78349. var invViewProjection = BABYLON.Matrix.Identity();
  78350. var viewProjection = BABYLON.Matrix.Identity();
  78351. var screenSize = BABYLON.Vector2.Zero();
  78352. this.motionBlurPostProcess.onApply = function (effect) {
  78353. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  78354. viewProjection.invertToRef(invViewProjection);
  78355. effect.setMatrix("inverseViewProjection", invViewProjection);
  78356. effect.setMatrix("prevViewProjection", prevViewProjection);
  78357. prevViewProjection = viewProjection;
  78358. screenSize.x = _this.motionBlurPostProcess.width;
  78359. screenSize.y = _this.motionBlurPostProcess.height;
  78360. effect.setVector2("screenSize", screenSize);
  78361. motionScale = scene.getEngine().getFps() / 60.0;
  78362. effect.setFloat("motionScale", motionScale);
  78363. effect.setFloat("motionStrength", _this.motionStrength);
  78364. effect.setTexture("depthSampler", _this._getDepthTexture());
  78365. };
  78366. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  78367. };
  78368. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  78369. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  78370. var renderer = this._scene.enableGeometryBufferRenderer();
  78371. return renderer.getGBuffer().textures[0];
  78372. }
  78373. return this._scene.enableDepthRenderer().getDepthMap();
  78374. };
  78375. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  78376. for (var i = 0; i < this._cameras.length; i++) {
  78377. var camera = this._cameras[i];
  78378. if (this.originalPostProcess) {
  78379. this.originalPostProcess.dispose(camera);
  78380. }
  78381. if (this.downSampleX4PostProcess) {
  78382. this.downSampleX4PostProcess.dispose(camera);
  78383. }
  78384. if (this.brightPassPostProcess) {
  78385. this.brightPassPostProcess.dispose(camera);
  78386. }
  78387. if (this.textureAdderPostProcess) {
  78388. this.textureAdderPostProcess.dispose(camera);
  78389. }
  78390. if (this.textureAdderFinalPostProcess) {
  78391. this.textureAdderFinalPostProcess.dispose(camera);
  78392. }
  78393. if (this.volumetricLightPostProcess) {
  78394. this.volumetricLightPostProcess.dispose(camera);
  78395. }
  78396. if (this.volumetricLightSmoothXPostProcess) {
  78397. this.volumetricLightSmoothXPostProcess.dispose(camera);
  78398. }
  78399. if (this.volumetricLightSmoothYPostProcess) {
  78400. this.volumetricLightSmoothYPostProcess.dispose(camera);
  78401. }
  78402. if (this.volumetricLightMergePostProces) {
  78403. this.volumetricLightMergePostProces.dispose(camera);
  78404. }
  78405. if (this.volumetricLightFinalPostProcess) {
  78406. this.volumetricLightFinalPostProcess.dispose(camera);
  78407. }
  78408. if (this.lensFlarePostProcess) {
  78409. this.lensFlarePostProcess.dispose(camera);
  78410. }
  78411. if (this.lensFlareComposePostProcess) {
  78412. this.lensFlareComposePostProcess.dispose(camera);
  78413. }
  78414. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  78415. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  78416. }
  78417. if (this.luminancePostProcess) {
  78418. this.luminancePostProcess.dispose(camera);
  78419. }
  78420. if (this.hdrPostProcess) {
  78421. this.hdrPostProcess.dispose(camera);
  78422. }
  78423. if (this.hdrFinalPostProcess) {
  78424. this.hdrFinalPostProcess.dispose(camera);
  78425. }
  78426. if (this.depthOfFieldPostProcess) {
  78427. this.depthOfFieldPostProcess.dispose(camera);
  78428. }
  78429. if (this.motionBlurPostProcess) {
  78430. this.motionBlurPostProcess.dispose(camera);
  78431. }
  78432. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  78433. this.blurHPostProcesses[j].dispose(camera);
  78434. }
  78435. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  78436. this.blurVPostProcesses[j].dispose(camera);
  78437. }
  78438. }
  78439. this.originalPostProcess = null;
  78440. this.downSampleX4PostProcess = null;
  78441. this.brightPassPostProcess = null;
  78442. this.textureAdderPostProcess = null;
  78443. this.textureAdderFinalPostProcess = null;
  78444. this.volumetricLightPostProcess = null;
  78445. this.volumetricLightSmoothXPostProcess = null;
  78446. this.volumetricLightSmoothYPostProcess = null;
  78447. this.volumetricLightMergePostProces = null;
  78448. this.volumetricLightFinalPostProcess = null;
  78449. this.lensFlarePostProcess = null;
  78450. this.lensFlareComposePostProcess = null;
  78451. this.luminancePostProcess = null;
  78452. this.hdrPostProcess = null;
  78453. this.hdrFinalPostProcess = null;
  78454. this.depthOfFieldPostProcess = null;
  78455. this.motionBlurPostProcess = null;
  78456. this.luminanceDownSamplePostProcesses = [];
  78457. this.blurHPostProcesses = [];
  78458. this.blurVPostProcesses = [];
  78459. };
  78460. /**
  78461. * Dispose of the pipeline and stop all post processes
  78462. */
  78463. StandardRenderingPipeline.prototype.dispose = function () {
  78464. this._disposePostProcesses();
  78465. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78466. _super.prototype.dispose.call(this);
  78467. };
  78468. /**
  78469. * Serialize the rendering pipeline (Used when exporting)
  78470. * @returns the serialized object
  78471. */
  78472. StandardRenderingPipeline.prototype.serialize = function () {
  78473. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78474. if (this.sourceLight) {
  78475. serializationObject.sourceLightId = this.sourceLight.id;
  78476. }
  78477. serializationObject.customType = "StandardRenderingPipeline";
  78478. return serializationObject;
  78479. };
  78480. /**
  78481. * Parse the serialized pipeline
  78482. * @param source Source pipeline.
  78483. * @param scene The scene to load the pipeline to.
  78484. * @param rootUrl The URL of the serialized pipeline.
  78485. * @returns An instantiated pipeline from the serialized object.
  78486. */
  78487. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  78488. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  78489. if (source.sourceLightId) {
  78490. p.sourceLight = scene.getLightByID(source.sourceLightId);
  78491. }
  78492. return p;
  78493. };
  78494. // Luminance steps
  78495. StandardRenderingPipeline.LuminanceSteps = 6;
  78496. __decorate([
  78497. BABYLON.serialize()
  78498. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  78499. __decorate([
  78500. BABYLON.serialize()
  78501. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  78502. __decorate([
  78503. BABYLON.serialize()
  78504. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  78505. __decorate([
  78506. BABYLON.serialize()
  78507. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  78508. __decorate([
  78509. BABYLON.serializeAsTexture("lensTexture")
  78510. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  78511. __decorate([
  78512. BABYLON.serialize()
  78513. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  78514. __decorate([
  78515. BABYLON.serialize()
  78516. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  78517. __decorate([
  78518. BABYLON.serialize()
  78519. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  78520. __decorate([
  78521. BABYLON.serialize()
  78522. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  78523. __decorate([
  78524. BABYLON.serialize()
  78525. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  78526. __decorate([
  78527. BABYLON.serialize()
  78528. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  78529. __decorate([
  78530. BABYLON.serializeAsTexture("lensColorTexture")
  78531. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  78532. __decorate([
  78533. BABYLON.serialize()
  78534. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  78535. __decorate([
  78536. BABYLON.serialize()
  78537. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  78538. __decorate([
  78539. BABYLON.serialize()
  78540. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  78541. __decorate([
  78542. BABYLON.serialize()
  78543. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  78544. __decorate([
  78545. BABYLON.serializeAsTexture("lensStarTexture")
  78546. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  78547. __decorate([
  78548. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  78549. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  78550. __decorate([
  78551. BABYLON.serialize()
  78552. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  78553. __decorate([
  78554. BABYLON.serialize()
  78555. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  78556. __decorate([
  78557. BABYLON.serialize()
  78558. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  78559. __decorate([
  78560. BABYLON.serialize()
  78561. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  78562. __decorate([
  78563. BABYLON.serialize()
  78564. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  78565. __decorate([
  78566. BABYLON.serialize()
  78567. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  78568. __decorate([
  78569. BABYLON.serialize()
  78570. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  78571. __decorate([
  78572. BABYLON.serialize()
  78573. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  78574. __decorate([
  78575. BABYLON.serialize()
  78576. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  78577. __decorate([
  78578. BABYLON.serialize()
  78579. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  78580. __decorate([
  78581. BABYLON.serialize()
  78582. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  78583. __decorate([
  78584. BABYLON.serialize()
  78585. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  78586. return StandardRenderingPipeline;
  78587. }(BABYLON.PostProcessRenderPipeline));
  78588. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  78589. })(BABYLON || (BABYLON = {}));
  78590. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  78591. var BABYLON;
  78592. (function (BABYLON) {
  78593. var FxaaPostProcess = /** @class */ (function (_super) {
  78594. __extends(FxaaPostProcess, _super);
  78595. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78596. if (camera === void 0) { camera = null; }
  78597. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78598. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  78599. var defines = _this._getDefines();
  78600. _this.updateEffect(defines);
  78601. _this.onApplyObservable.add(function (effect) {
  78602. var texelSize = _this.texelSize;
  78603. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  78604. });
  78605. return _this;
  78606. }
  78607. FxaaPostProcess.prototype._getDefines = function () {
  78608. var engine = this.getEngine();
  78609. if (!engine) {
  78610. return null;
  78611. }
  78612. var glInfo = engine.getGlInfo();
  78613. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  78614. return "#define MALI 1\n";
  78615. }
  78616. return null;
  78617. };
  78618. return FxaaPostProcess;
  78619. }(BABYLON.PostProcess));
  78620. BABYLON.FxaaPostProcess = FxaaPostProcess;
  78621. })(BABYLON || (BABYLON = {}));
  78622. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  78623. var BABYLON;
  78624. (function (BABYLON) {
  78625. /**
  78626. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  78627. */
  78628. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  78629. __extends(ChromaticAberrationPostProcess, _super);
  78630. /**
  78631. * Creates a new instance ChromaticAberrationPostProcess
  78632. * @param name The name of the effect.
  78633. * @param screenWidth The width of the screen to apply the effect on.
  78634. * @param screenHeight The height of the screen to apply the effect on.
  78635. * @param options The required width/height ratio to downsize to before computing the render pass.
  78636. * @param camera The camera to apply the render pass to.
  78637. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78638. * @param engine The engine which the post process will be applied. (default: current engine)
  78639. * @param reusable If the post process can be reused on the same frame. (default: false)
  78640. * @param textureType Type of textures used when performing the post process. (default: 0)
  78641. * @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)
  78642. */
  78643. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78644. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78645. if (blockCompilation === void 0) { blockCompilation = false; }
  78646. 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;
  78647. /**
  78648. * The amount of seperation of rgb channels (default: 30)
  78649. */
  78650. _this.aberrationAmount = 30;
  78651. /**
  78652. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  78653. */
  78654. _this.radialIntensity = 0;
  78655. /**
  78656. * 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))
  78657. */
  78658. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  78659. /**
  78660. * 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))
  78661. */
  78662. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  78663. _this.onApplyObservable.add(function (effect) {
  78664. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  78665. effect.setFloat('screen_width', screenWidth);
  78666. effect.setFloat('screen_height', screenHeight);
  78667. effect.setFloat('radialIntensity', _this.radialIntensity);
  78668. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  78669. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  78670. });
  78671. return _this;
  78672. }
  78673. return ChromaticAberrationPostProcess;
  78674. }(BABYLON.PostProcess));
  78675. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  78676. })(BABYLON || (BABYLON = {}));
  78677. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  78678. var BABYLON;
  78679. (function (BABYLON) {
  78680. /**
  78681. * The GrainPostProcess adds noise to the image at mid luminance levels
  78682. */
  78683. var GrainPostProcess = /** @class */ (function (_super) {
  78684. __extends(GrainPostProcess, _super);
  78685. /**
  78686. * Creates a new instance of @see GrainPostProcess
  78687. * @param name The name of the effect.
  78688. * @param options The required width/height ratio to downsize to before computing the render pass.
  78689. * @param camera The camera to apply the render pass to.
  78690. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78691. * @param engine The engine which the post process will be applied. (default: current engine)
  78692. * @param reusable If the post process can be reused on the same frame. (default: false)
  78693. * @param textureType Type of textures used when performing the post process. (default: 0)
  78694. * @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)
  78695. */
  78696. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78697. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78698. if (blockCompilation === void 0) { blockCompilation = false; }
  78699. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78700. /**
  78701. * The intensity of the grain added (default: 30)
  78702. */
  78703. _this.intensity = 30;
  78704. /**
  78705. * If the grain should be randomized on every frame
  78706. */
  78707. _this.animated = false;
  78708. _this.onApplyObservable.add(function (effect) {
  78709. effect.setFloat('intensity', _this.intensity);
  78710. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  78711. });
  78712. return _this;
  78713. }
  78714. return GrainPostProcess;
  78715. }(BABYLON.PostProcess));
  78716. BABYLON.GrainPostProcess = GrainPostProcess;
  78717. })(BABYLON || (BABYLON = {}));
  78718. //# sourceMappingURL=babylon.grainPostProcess.js.map
  78719. var BABYLON;
  78720. (function (BABYLON) {
  78721. /**
  78722. * The SharpenPostProcess applies a sharpen kernel to every pixel
  78723. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78724. */
  78725. var SharpenPostProcess = /** @class */ (function (_super) {
  78726. __extends(SharpenPostProcess, _super);
  78727. /**
  78728. * Creates a new instance ConvolutionPostProcess
  78729. * @param name The name of the effect.
  78730. * @param options The required width/height ratio to downsize to before computing the render pass.
  78731. * @param camera The camera to apply the render pass to.
  78732. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78733. * @param engine The engine which the post process will be applied. (default: current engine)
  78734. * @param reusable If the post process can be reused on the same frame. (default: false)
  78735. * @param textureType Type of textures used when performing the post process. (default: 0)
  78736. * @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)
  78737. */
  78738. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78739. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78740. if (blockCompilation === void 0) { blockCompilation = false; }
  78741. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78742. /**
  78743. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  78744. */
  78745. _this.colorAmount = 1.0;
  78746. /**
  78747. * How much sharpness should be applied (default: 0.3)
  78748. */
  78749. _this.edgeAmount = 0.3;
  78750. _this.onApply = function (effect) {
  78751. effect.setFloat2("screenSize", _this.width, _this.height);
  78752. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  78753. };
  78754. return _this;
  78755. }
  78756. return SharpenPostProcess;
  78757. }(BABYLON.PostProcess));
  78758. BABYLON.SharpenPostProcess = SharpenPostProcess;
  78759. })(BABYLON || (BABYLON = {}));
  78760. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  78761. var BABYLON;
  78762. (function (BABYLON) {
  78763. /**
  78764. * The Blur Post Process which blurs an image based on a kernel and direction.
  78765. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  78766. */
  78767. var BlurPostProcess = /** @class */ (function (_super) {
  78768. __extends(BlurPostProcess, _super);
  78769. /**
  78770. * Creates a new instance BlurPostProcess
  78771. * @param name The name of the effect.
  78772. * @param direction The direction in which to blur the image.
  78773. * @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.
  78774. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  78775. * @param camera The camera to apply the render pass to.
  78776. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78777. * @param engine The engine which the post process will be applied. (default: current engine)
  78778. * @param reusable If the post process can be reused on the same frame. (default: false)
  78779. * @param textureType Type of textures used when performing the post process. (default: 0)
  78780. * @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)
  78781. */
  78782. function BlurPostProcess(name,
  78783. /** The direction in which to blur the image. */
  78784. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  78785. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78786. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78787. if (defines === void 0) { defines = ""; }
  78788. if (blockCompilation === void 0) { blockCompilation = false; }
  78789. 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;
  78790. _this.direction = direction;
  78791. _this.blockCompilation = blockCompilation;
  78792. _this._packedFloat = false;
  78793. _this._staticDefines = "";
  78794. _this._staticDefines = defines;
  78795. _this.onApplyObservable.add(function (effect) {
  78796. if (_this._outputTexture) {
  78797. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  78798. }
  78799. else {
  78800. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  78801. }
  78802. });
  78803. _this.kernel = kernel;
  78804. return _this;
  78805. }
  78806. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  78807. /**
  78808. * Gets the length in pixels of the blur sample region
  78809. */
  78810. get: function () {
  78811. return this._idealKernel;
  78812. },
  78813. /**
  78814. * Sets the length in pixels of the blur sample region
  78815. */
  78816. set: function (v) {
  78817. if (this._idealKernel === v) {
  78818. return;
  78819. }
  78820. v = Math.max(v, 1);
  78821. this._idealKernel = v;
  78822. this._kernel = this._nearestBestKernel(v);
  78823. if (!this.blockCompilation) {
  78824. this._updateParameters();
  78825. }
  78826. },
  78827. enumerable: true,
  78828. configurable: true
  78829. });
  78830. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  78831. /**
  78832. * Gets wether or not the blur is unpacking/repacking floats
  78833. */
  78834. get: function () {
  78835. return this._packedFloat;
  78836. },
  78837. /**
  78838. * Sets wether or not the blur needs to unpack/repack floats
  78839. */
  78840. set: function (v) {
  78841. if (this._packedFloat === v) {
  78842. return;
  78843. }
  78844. this._packedFloat = v;
  78845. if (!this.blockCompilation) {
  78846. this._updateParameters();
  78847. }
  78848. },
  78849. enumerable: true,
  78850. configurable: true
  78851. });
  78852. /**
  78853. * Updates the effect with the current post process compile time values and recompiles the shader.
  78854. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  78855. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  78856. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  78857. * @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
  78858. * @param onCompiled Called when the shader has been compiled.
  78859. * @param onError Called if there is an error when compiling a shader.
  78860. */
  78861. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  78862. if (defines === void 0) { defines = null; }
  78863. if (uniforms === void 0) { uniforms = null; }
  78864. if (samplers === void 0) { samplers = null; }
  78865. this._updateParameters(onCompiled, onError);
  78866. };
  78867. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  78868. // Generate sampling offsets and weights
  78869. var N = this._kernel;
  78870. var centerIndex = (N - 1) / 2;
  78871. // Generate Gaussian sampling weights over kernel
  78872. var offsets = [];
  78873. var weights = [];
  78874. var totalWeight = 0;
  78875. for (var i = 0; i < N; i++) {
  78876. var u = i / (N - 1);
  78877. var w = this._gaussianWeight(u * 2.0 - 1);
  78878. offsets[i] = (i - centerIndex);
  78879. weights[i] = w;
  78880. totalWeight += w;
  78881. }
  78882. // Normalize weights
  78883. for (var i = 0; i < weights.length; i++) {
  78884. weights[i] /= totalWeight;
  78885. }
  78886. // Optimize: combine samples to take advantage of hardware linear sampling
  78887. // Walk from left to center, combining pairs (symmetrically)
  78888. var linearSamplingWeights = [];
  78889. var linearSamplingOffsets = [];
  78890. var linearSamplingMap = [];
  78891. for (var i = 0; i <= centerIndex; i += 2) {
  78892. var j = Math.min(i + 1, Math.floor(centerIndex));
  78893. var singleCenterSample = i === j;
  78894. if (singleCenterSample) {
  78895. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  78896. }
  78897. else {
  78898. var sharedCell = j === centerIndex;
  78899. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  78900. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  78901. if (offsetLinear === 0) {
  78902. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  78903. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  78904. }
  78905. else {
  78906. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  78907. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  78908. }
  78909. }
  78910. }
  78911. for (var i = 0; i < linearSamplingMap.length; i++) {
  78912. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  78913. linearSamplingWeights[i] = linearSamplingMap[i].w;
  78914. }
  78915. // Replace with optimized
  78916. offsets = linearSamplingOffsets;
  78917. weights = linearSamplingWeights;
  78918. // Generate shaders
  78919. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  78920. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  78921. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  78922. var defines = "";
  78923. defines += this._staticDefines;
  78924. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  78925. if (this._staticDefines.indexOf("DOF") != -1) {
  78926. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  78927. varyingCount--;
  78928. }
  78929. for (var i = 0; i < varyingCount; i++) {
  78930. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  78931. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  78932. }
  78933. var depCount = 0;
  78934. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  78935. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  78936. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  78937. depCount++;
  78938. }
  78939. if (this.packedFloat) {
  78940. defines += "#define PACKEDFLOAT 1";
  78941. }
  78942. this.blockCompilation = false;
  78943. _super.prototype.updateEffect.call(this, defines, null, null, {
  78944. varyingCount: varyingCount,
  78945. depCount: depCount
  78946. }, onCompiled, onError);
  78947. };
  78948. /**
  78949. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  78950. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  78951. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  78952. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  78953. * The gaps between physical kernels are compensated for in the weighting of the samples
  78954. * @param idealKernel Ideal blur kernel.
  78955. * @return Nearest best kernel.
  78956. */
  78957. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  78958. var v = Math.round(idealKernel);
  78959. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  78960. var k = _a[_i];
  78961. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  78962. return Math.max(k, 3);
  78963. }
  78964. }
  78965. return Math.max(v, 3);
  78966. };
  78967. /**
  78968. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  78969. * @param x The point on the Gaussian distribution to sample.
  78970. * @return the value of the Gaussian function at x.
  78971. */
  78972. BlurPostProcess.prototype._gaussianWeight = function (x) {
  78973. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  78974. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  78975. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  78976. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  78977. // truncated at around 1.3% of peak strength.
  78978. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  78979. var sigma = (1 / 3);
  78980. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  78981. var exponent = -((x * x) / (2.0 * sigma * sigma));
  78982. var weight = (1.0 / denominator) * Math.exp(exponent);
  78983. return weight;
  78984. };
  78985. /**
  78986. * Generates a string that can be used as a floating point number in GLSL.
  78987. * @param x Value to print.
  78988. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  78989. * @return GLSL float string.
  78990. */
  78991. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  78992. if (decimalFigures === void 0) { decimalFigures = 8; }
  78993. return x.toFixed(decimalFigures).replace(/0+$/, '');
  78994. };
  78995. return BlurPostProcess;
  78996. }(BABYLON.PostProcess));
  78997. BABYLON.BlurPostProcess = BlurPostProcess;
  78998. })(BABYLON || (BABYLON = {}));
  78999. //# sourceMappingURL=babylon.blurPostProcess.js.map
  79000. var BABYLON;
  79001. (function (BABYLON) {
  79002. /**
  79003. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  79004. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  79005. * based on samples that have a large difference in distance than the center pixel.
  79006. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  79007. */
  79008. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  79009. __extends(DepthOfFieldBlurPostProcess, _super);
  79010. /**
  79011. * Creates a new instance CircleOfConfusionPostProcess
  79012. * @param name The name of the effect.
  79013. * @param scene The scene the effect belongs to.
  79014. * @param direction The direction the blur should be applied.
  79015. * @param kernel The size of the kernel used to blur.
  79016. * @param options The required width/height ratio to downsize to before computing the render pass.
  79017. * @param camera The camera to apply the render pass to.
  79018. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  79019. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  79020. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79021. * @param engine The engine which the post process will be applied. (default: current engine)
  79022. * @param reusable If the post process can be reused on the same frame. (default: false)
  79023. * @param textureType Type of textures used when performing the post process. (default: 0)
  79024. * @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)
  79025. */
  79026. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  79027. if (imageToBlur === void 0) { imageToBlur = null; }
  79028. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79029. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79030. if (blockCompilation === void 0) { blockCompilation = false; }
  79031. 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;
  79032. _this.direction = direction;
  79033. _this.onApplyObservable.add(function (effect) {
  79034. if (imageToBlur != null) {
  79035. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  79036. }
  79037. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  79038. if (scene.activeCamera) {
  79039. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  79040. }
  79041. });
  79042. return _this;
  79043. }
  79044. return DepthOfFieldBlurPostProcess;
  79045. }(BABYLON.BlurPostProcess));
  79046. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  79047. })(BABYLON || (BABYLON = {}));
  79048. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  79049. var BABYLON;
  79050. (function (BABYLON) {
  79051. /**
  79052. * Options to be set when merging outputs from the default pipeline.
  79053. */
  79054. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  79055. function DepthOfFieldMergePostProcessOptions() {
  79056. }
  79057. return DepthOfFieldMergePostProcessOptions;
  79058. }());
  79059. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  79060. /**
  79061. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  79062. */
  79063. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  79064. __extends(DepthOfFieldMergePostProcess, _super);
  79065. /**
  79066. * Creates a new instance of DepthOfFieldMergePostProcess
  79067. * @param name The name of the effect.
  79068. * @param originalFromInput Post process which's input will be used for the merge.
  79069. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  79070. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  79071. * @param options The required width/height ratio to downsize to before computing the render pass.
  79072. * @param camera The camera to apply the render pass to.
  79073. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79074. * @param engine The engine which the post process will be applied. (default: current engine)
  79075. * @param reusable If the post process can be reused on the same frame. (default: false)
  79076. * @param textureType Type of textures used when performing the post process. (default: 0)
  79077. * @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)
  79078. */
  79079. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79080. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79081. if (blockCompilation === void 0) { blockCompilation = false; }
  79082. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  79083. _this.blurSteps = blurSteps;
  79084. _this.onApplyObservable.add(function (effect) {
  79085. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  79086. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  79087. blurSteps.forEach(function (step, index) {
  79088. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  79089. });
  79090. });
  79091. if (!blockCompilation) {
  79092. _this.updateEffect();
  79093. }
  79094. return _this;
  79095. }
  79096. /**
  79097. * Updates the effect with the current post process compile time values and recompiles the shader.
  79098. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  79099. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  79100. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  79101. * @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
  79102. * @param onCompiled Called when the shader has been compiled.
  79103. * @param onError Called if there is an error when compiling a shader.
  79104. */
  79105. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  79106. if (defines === void 0) { defines = null; }
  79107. if (uniforms === void 0) { uniforms = null; }
  79108. if (samplers === void 0) { samplers = null; }
  79109. if (!defines) {
  79110. defines = "";
  79111. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  79112. }
  79113. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  79114. };
  79115. return DepthOfFieldMergePostProcess;
  79116. }(BABYLON.PostProcess));
  79117. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  79118. })(BABYLON || (BABYLON = {}));
  79119. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  79120. var BABYLON;
  79121. (function (BABYLON) {
  79122. /**
  79123. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  79124. */
  79125. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  79126. __extends(CircleOfConfusionPostProcess, _super);
  79127. /**
  79128. * Creates a new instance CircleOfConfusionPostProcess
  79129. * @param name The name of the effect.
  79130. * @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.
  79131. * @param options The required width/height ratio to downsize to before computing the render pass.
  79132. * @param camera The camera to apply the render pass to.
  79133. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79134. * @param engine The engine which the post process will be applied. (default: current engine)
  79135. * @param reusable If the post process can be reused on the same frame. (default: false)
  79136. * @param textureType Type of textures used when performing the post process. (default: 0)
  79137. * @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)
  79138. */
  79139. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79140. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79141. if (blockCompilation === void 0) { blockCompilation = false; }
  79142. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79143. /**
  79144. * 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.
  79145. */
  79146. _this.lensSize = 50;
  79147. /**
  79148. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  79149. */
  79150. _this.fStop = 1.4;
  79151. /**
  79152. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  79153. */
  79154. _this.focusDistance = 2000;
  79155. /**
  79156. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  79157. */
  79158. _this.focalLength = 50;
  79159. _this._depthTexture = null;
  79160. _this._depthTexture = depthTexture;
  79161. _this.onApplyObservable.add(function (effect) {
  79162. if (!_this._depthTexture) {
  79163. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  79164. return;
  79165. }
  79166. effect.setTexture("depthSampler", _this._depthTexture);
  79167. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  79168. var aperture = _this.lensSize / _this.fStop;
  79169. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  79170. effect.setFloat('focusDistance', _this.focusDistance);
  79171. effect.setFloat('cocPrecalculation', cocPrecalculation);
  79172. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  79173. });
  79174. return _this;
  79175. }
  79176. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  79177. /**
  79178. * 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.
  79179. */
  79180. set: function (value) {
  79181. this._depthTexture = value;
  79182. },
  79183. enumerable: true,
  79184. configurable: true
  79185. });
  79186. return CircleOfConfusionPostProcess;
  79187. }(BABYLON.PostProcess));
  79188. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  79189. })(BABYLON || (BABYLON = {}));
  79190. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  79191. var BABYLON;
  79192. (function (BABYLON) {
  79193. /**
  79194. * Specifies the level of max blur that should be applied when using the depth of field effect
  79195. */
  79196. var DepthOfFieldEffectBlurLevel;
  79197. (function (DepthOfFieldEffectBlurLevel) {
  79198. /**
  79199. * Subtle blur
  79200. */
  79201. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  79202. /**
  79203. * Medium blur
  79204. */
  79205. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  79206. /**
  79207. * Large blur
  79208. */
  79209. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  79210. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  79211. ;
  79212. /**
  79213. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  79214. */
  79215. var DepthOfFieldEffect = /** @class */ (function (_super) {
  79216. __extends(DepthOfFieldEffect, _super);
  79217. /**
  79218. * Creates a new instance DepthOfFieldEffect
  79219. * @param scene The scene the effect belongs to.
  79220. * @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.
  79221. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  79222. * @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)
  79223. */
  79224. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  79225. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  79226. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  79227. if (blockCompilation === void 0) { blockCompilation = false; }
  79228. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  79229. return _this._effects;
  79230. }, true) || this;
  79231. /**
  79232. * @hidden Internal post processes in depth of field effect
  79233. */
  79234. _this._effects = [];
  79235. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  79236. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79237. // 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)
  79238. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  79239. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  79240. _this._depthOfFieldBlurY = [];
  79241. _this._depthOfFieldBlurX = [];
  79242. var blurCount = 1;
  79243. var kernelSize = 15;
  79244. switch (blurLevel) {
  79245. case DepthOfFieldEffectBlurLevel.High: {
  79246. blurCount = 3;
  79247. kernelSize = 51;
  79248. break;
  79249. }
  79250. case DepthOfFieldEffectBlurLevel.Medium: {
  79251. blurCount = 2;
  79252. kernelSize = 31;
  79253. break;
  79254. }
  79255. default: {
  79256. kernelSize = 15;
  79257. blurCount = 1;
  79258. break;
  79259. }
  79260. }
  79261. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  79262. var ratio = 1.0;
  79263. for (var i = 0; i < blurCount; i++) {
  79264. 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);
  79265. blurY.autoClear = false;
  79266. ratio = 0.75 / Math.pow(2, i);
  79267. 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);
  79268. blurX.autoClear = false;
  79269. _this._depthOfFieldBlurY.push(blurY);
  79270. _this._depthOfFieldBlurX.push(blurX);
  79271. }
  79272. // Set all post processes on the effect.
  79273. _this._effects = [_this._circleOfConfusion];
  79274. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  79275. _this._effects.push(_this._depthOfFieldBlurY[i]);
  79276. _this._effects.push(_this._depthOfFieldBlurX[i]);
  79277. }
  79278. // Merge blurred images with original image based on circleOfConfusion
  79279. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79280. _this._dofMerge.autoClear = false;
  79281. _this._effects.push(_this._dofMerge);
  79282. return _this;
  79283. }
  79284. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  79285. get: function () {
  79286. return this._circleOfConfusion.focalLength;
  79287. },
  79288. /**
  79289. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  79290. */
  79291. set: function (value) {
  79292. this._circleOfConfusion.focalLength = value;
  79293. },
  79294. enumerable: true,
  79295. configurable: true
  79296. });
  79297. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  79298. get: function () {
  79299. return this._circleOfConfusion.fStop;
  79300. },
  79301. /**
  79302. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  79303. */
  79304. set: function (value) {
  79305. this._circleOfConfusion.fStop = value;
  79306. },
  79307. enumerable: true,
  79308. configurable: true
  79309. });
  79310. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  79311. get: function () {
  79312. return this._circleOfConfusion.focusDistance;
  79313. },
  79314. /**
  79315. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  79316. */
  79317. set: function (value) {
  79318. this._circleOfConfusion.focusDistance = value;
  79319. },
  79320. enumerable: true,
  79321. configurable: true
  79322. });
  79323. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  79324. get: function () {
  79325. return this._circleOfConfusion.lensSize;
  79326. },
  79327. /**
  79328. * 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.
  79329. */
  79330. set: function (value) {
  79331. this._circleOfConfusion.lensSize = value;
  79332. },
  79333. enumerable: true,
  79334. configurable: true
  79335. });
  79336. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  79337. /**
  79338. * 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.
  79339. */
  79340. set: function (value) {
  79341. this._circleOfConfusion.depthTexture = value;
  79342. },
  79343. enumerable: true,
  79344. configurable: true
  79345. });
  79346. /**
  79347. * Disposes each of the internal effects for a given camera.
  79348. * @param camera The camera to dispose the effect on.
  79349. */
  79350. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  79351. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79352. this._effects[effectIndex].dispose(camera);
  79353. }
  79354. };
  79355. /**
  79356. * @hidden Internal
  79357. */
  79358. DepthOfFieldEffect.prototype._updateEffects = function () {
  79359. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79360. this._effects[effectIndex].updateEffect();
  79361. }
  79362. };
  79363. /**
  79364. * Internal
  79365. * @returns if all the contained post processes are ready.
  79366. * @hidden
  79367. */
  79368. DepthOfFieldEffect.prototype._isReady = function () {
  79369. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79370. if (!this._effects[effectIndex].isReady()) {
  79371. return false;
  79372. }
  79373. }
  79374. return true;
  79375. };
  79376. return DepthOfFieldEffect;
  79377. }(BABYLON.PostProcessRenderEffect));
  79378. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  79379. })(BABYLON || (BABYLON = {}));
  79380. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  79381. var BABYLON;
  79382. (function (BABYLON) {
  79383. /**
  79384. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  79385. */
  79386. var BloomMergePostProcess = /** @class */ (function (_super) {
  79387. __extends(BloomMergePostProcess, _super);
  79388. /**
  79389. * Creates a new instance of @see BloomMergePostProcess
  79390. * @param name The name of the effect.
  79391. * @param originalFromInput Post process which's input will be used for the merge.
  79392. * @param blurred Blurred highlights post process which's output will be used.
  79393. * @param weight Weight of the bloom to be added to the original input.
  79394. * @param options The required width/height ratio to downsize to before computing the render pass.
  79395. * @param camera The camera to apply the render pass to.
  79396. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79397. * @param engine The engine which the post process will be applied. (default: current engine)
  79398. * @param reusable If the post process can be reused on the same frame. (default: false)
  79399. * @param textureType Type of textures used when performing the post process. (default: 0)
  79400. * @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)
  79401. */
  79402. function BloomMergePostProcess(name, originalFromInput, blurred,
  79403. /** Weight of the bloom to be added to the original input. */
  79404. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79405. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79406. if (blockCompilation === void 0) { blockCompilation = false; }
  79407. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  79408. _this.weight = weight;
  79409. _this.onApplyObservable.add(function (effect) {
  79410. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  79411. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  79412. effect.setFloat("bloomWeight", _this.weight);
  79413. });
  79414. if (!blockCompilation) {
  79415. _this.updateEffect();
  79416. }
  79417. return _this;
  79418. }
  79419. return BloomMergePostProcess;
  79420. }(BABYLON.PostProcess));
  79421. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  79422. })(BABYLON || (BABYLON = {}));
  79423. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  79424. var BABYLON;
  79425. (function (BABYLON) {
  79426. /**
  79427. * 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.
  79428. */
  79429. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  79430. __extends(ExtractHighlightsPostProcess, _super);
  79431. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79432. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79433. if (blockCompilation === void 0) { blockCompilation = false; }
  79434. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79435. /**
  79436. * The luminance threshold, pixels below this value will be set to black.
  79437. */
  79438. _this.threshold = 0.9;
  79439. /** @hidden */
  79440. _this._exposure = 1;
  79441. /**
  79442. * Post process which has the input texture to be used when performing highlight extraction
  79443. * @hidden
  79444. */
  79445. _this._inputPostProcess = null;
  79446. _this.onApplyObservable.add(function (effect) {
  79447. if (_this._inputPostProcess) {
  79448. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  79449. }
  79450. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  79451. effect.setFloat('exposure', _this._exposure);
  79452. });
  79453. return _this;
  79454. }
  79455. return ExtractHighlightsPostProcess;
  79456. }(BABYLON.PostProcess));
  79457. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  79458. })(BABYLON || (BABYLON = {}));
  79459. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  79460. var BABYLON;
  79461. (function (BABYLON) {
  79462. /**
  79463. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  79464. */
  79465. var BloomEffect = /** @class */ (function (_super) {
  79466. __extends(BloomEffect, _super);
  79467. /**
  79468. * Creates a new instance of @see BloomEffect
  79469. * @param scene The scene the effect belongs to.
  79470. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  79471. * @param bloomKernel The size of the kernel to be used when applying the blur.
  79472. * @param bloomWeight The the strength of bloom.
  79473. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  79474. * @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)
  79475. */
  79476. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  79477. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  79478. if (blockCompilation === void 0) { blockCompilation = false; }
  79479. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  79480. return _this._effects;
  79481. }, true) || this;
  79482. _this.bloomScale = bloomScale;
  79483. /**
  79484. * @hidden Internal
  79485. */
  79486. _this._effects = [];
  79487. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79488. _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);
  79489. _this._blurX.alwaysForcePOT = true;
  79490. _this._blurX.autoClear = false;
  79491. _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);
  79492. _this._blurY.alwaysForcePOT = true;
  79493. _this._blurY.autoClear = false;
  79494. _this.kernel = bloomKernel;
  79495. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  79496. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79497. _this._merge.autoClear = false;
  79498. _this._effects.push(_this._merge);
  79499. return _this;
  79500. }
  79501. Object.defineProperty(BloomEffect.prototype, "threshold", {
  79502. /**
  79503. * The luminance threshold to find bright areas of the image to bloom.
  79504. */
  79505. get: function () {
  79506. return this._downscale.threshold;
  79507. },
  79508. set: function (value) {
  79509. this._downscale.threshold = value;
  79510. },
  79511. enumerable: true,
  79512. configurable: true
  79513. });
  79514. Object.defineProperty(BloomEffect.prototype, "weight", {
  79515. /**
  79516. * The strength of the bloom.
  79517. */
  79518. get: function () {
  79519. return this._merge.weight;
  79520. },
  79521. set: function (value) {
  79522. this._merge.weight = value;
  79523. },
  79524. enumerable: true,
  79525. configurable: true
  79526. });
  79527. Object.defineProperty(BloomEffect.prototype, "kernel", {
  79528. /**
  79529. * Specifies the size of the bloom blur kernel, relative to the final output size
  79530. */
  79531. get: function () {
  79532. return this._blurX.kernel / this.bloomScale;
  79533. },
  79534. set: function (value) {
  79535. this._blurX.kernel = value * this.bloomScale;
  79536. this._blurY.kernel = value * this.bloomScale;
  79537. },
  79538. enumerable: true,
  79539. configurable: true
  79540. });
  79541. /**
  79542. * Disposes each of the internal effects for a given camera.
  79543. * @param camera The camera to dispose the effect on.
  79544. */
  79545. BloomEffect.prototype.disposeEffects = function (camera) {
  79546. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79547. this._effects[effectIndex].dispose(camera);
  79548. }
  79549. };
  79550. /**
  79551. * @hidden Internal
  79552. */
  79553. BloomEffect.prototype._updateEffects = function () {
  79554. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79555. this._effects[effectIndex].updateEffect();
  79556. }
  79557. };
  79558. /**
  79559. * Internal
  79560. * @returns if all the contained post processes are ready.
  79561. * @hidden
  79562. */
  79563. BloomEffect.prototype._isReady = function () {
  79564. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79565. if (!this._effects[effectIndex].isReady()) {
  79566. return false;
  79567. }
  79568. }
  79569. return true;
  79570. };
  79571. return BloomEffect;
  79572. }(BABYLON.PostProcessRenderEffect));
  79573. BABYLON.BloomEffect = BloomEffect;
  79574. })(BABYLON || (BABYLON = {}));
  79575. //# sourceMappingURL=babylon.bloomEffect.js.map
  79576. var BABYLON;
  79577. (function (BABYLON) {
  79578. /**
  79579. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  79580. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  79581. */
  79582. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  79583. __extends(DefaultRenderingPipeline, _super);
  79584. /**
  79585. * @constructor
  79586. * @param {string} name - The rendering pipeline name (default: "")
  79587. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  79588. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  79589. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  79590. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  79591. */
  79592. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  79593. if (name === void 0) { name = ""; }
  79594. if (hdr === void 0) { hdr = true; }
  79595. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  79596. if (automaticBuild === void 0) { automaticBuild = true; }
  79597. var _this = _super.call(this, scene.getEngine(), name) || this;
  79598. _this._camerasToBeAttached = [];
  79599. /**
  79600. * ID of the sharpen post process,
  79601. */
  79602. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  79603. /**
  79604. * ID of the image processing post process;
  79605. */
  79606. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  79607. /**
  79608. * ID of the Fast Approximate Anti-Aliasing post process;
  79609. */
  79610. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  79611. /**
  79612. * ID of the chromatic aberration post process,
  79613. */
  79614. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  79615. /**
  79616. * ID of the grain post process
  79617. */
  79618. _this.GrainPostProcessId = "GrainPostProcessEffect";
  79619. /**
  79620. * Glow post process which adds a glow to emmisive areas of the image
  79621. */
  79622. _this._glowLayer = null;
  79623. /**
  79624. * Animations which can be used to tweak settings over a period of time
  79625. */
  79626. _this.animations = [];
  79627. _this._imageProcessingConfigurationObserver = null;
  79628. // Values
  79629. _this._sharpenEnabled = false;
  79630. _this._bloomEnabled = false;
  79631. _this._depthOfFieldEnabled = false;
  79632. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  79633. _this._fxaaEnabled = false;
  79634. _this._imageProcessingEnabled = true;
  79635. _this._bloomScale = 0.5;
  79636. _this._chromaticAberrationEnabled = false;
  79637. _this._grainEnabled = false;
  79638. _this._buildAllowed = true;
  79639. _this._resizeObserver = null;
  79640. _this._hardwareScaleLevel = 1.0;
  79641. _this._bloomKernel = 64;
  79642. /**
  79643. * Specifies the weight of the bloom in the final rendering
  79644. */
  79645. _this._bloomWeight = 0.15;
  79646. /**
  79647. * Specifies the luma threshold for the area that will be blurred by the bloom
  79648. */
  79649. _this._bloomThreshold = 0.9;
  79650. _this._samples = 1;
  79651. _this._hasCleared = false;
  79652. _this._prevPostProcess = null;
  79653. _this._prevPrevPostProcess = null;
  79654. _this._cameras = cameras || scene.cameras;
  79655. _this._cameras = _this._cameras.slice();
  79656. _this._camerasToBeAttached = _this._cameras.slice();
  79657. _this._buildAllowed = automaticBuild;
  79658. // Initialize
  79659. _this._scene = scene;
  79660. var caps = _this._scene.getEngine().getCaps();
  79661. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  79662. // Misc
  79663. if (_this._hdr) {
  79664. if (caps.textureHalfFloatRender) {
  79665. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79666. }
  79667. else if (caps.textureFloatRender) {
  79668. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79669. }
  79670. }
  79671. else {
  79672. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79673. }
  79674. // Attach
  79675. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79676. var engine = _this._scene.getEngine();
  79677. // Create post processes before hand so they can be modified before enabled.
  79678. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  79679. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79680. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  79681. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  79682. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  79683. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79684. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  79685. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79686. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  79687. _this._resizeObserver = engine.onResizeObservable.add(function () {
  79688. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  79689. _this.bloomKernel = _this.bloomKernel;
  79690. });
  79691. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  79692. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  79693. });
  79694. _this._buildPipeline();
  79695. return _this;
  79696. }
  79697. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  79698. get: function () {
  79699. return this._sharpenEnabled;
  79700. },
  79701. /**
  79702. * Enable or disable the sharpen process from the pipeline
  79703. */
  79704. set: function (enabled) {
  79705. if (this._sharpenEnabled === enabled) {
  79706. return;
  79707. }
  79708. this._sharpenEnabled = enabled;
  79709. this._buildPipeline();
  79710. },
  79711. enumerable: true,
  79712. configurable: true
  79713. });
  79714. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  79715. /**
  79716. * Specifies the size of the bloom blur kernel, relative to the final output size
  79717. */
  79718. get: function () {
  79719. return this._bloomKernel;
  79720. },
  79721. set: function (value) {
  79722. this._bloomKernel = value;
  79723. this.bloom.kernel = value / this._hardwareScaleLevel;
  79724. },
  79725. enumerable: true,
  79726. configurable: true
  79727. });
  79728. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  79729. get: function () {
  79730. return this._bloomWeight;
  79731. },
  79732. /**
  79733. * The strength of the bloom.
  79734. */
  79735. set: function (value) {
  79736. if (this._bloomWeight === value) {
  79737. return;
  79738. }
  79739. this.bloom.weight = value;
  79740. this._bloomWeight = value;
  79741. },
  79742. enumerable: true,
  79743. configurable: true
  79744. });
  79745. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  79746. get: function () {
  79747. return this._bloomThreshold;
  79748. },
  79749. /**
  79750. * The strength of the bloom.
  79751. */
  79752. set: function (value) {
  79753. if (this._bloomThreshold === value) {
  79754. return;
  79755. }
  79756. this.bloom.threshold = value;
  79757. this._bloomThreshold = value;
  79758. },
  79759. enumerable: true,
  79760. configurable: true
  79761. });
  79762. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  79763. get: function () {
  79764. return this._bloomScale;
  79765. },
  79766. /**
  79767. * The scale of the bloom, lower value will provide better performance.
  79768. */
  79769. set: function (value) {
  79770. if (this._bloomScale === value) {
  79771. return;
  79772. }
  79773. this._bloomScale = value;
  79774. // recreate bloom and dispose old as this setting is not dynamic
  79775. this._rebuildBloom();
  79776. this._buildPipeline();
  79777. },
  79778. enumerable: true,
  79779. configurable: true
  79780. });
  79781. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  79782. get: function () {
  79783. return this._bloomEnabled;
  79784. },
  79785. /**
  79786. * Enable or disable the bloom from the pipeline
  79787. */
  79788. set: function (enabled) {
  79789. if (this._bloomEnabled === enabled) {
  79790. return;
  79791. }
  79792. this._bloomEnabled = enabled;
  79793. this._buildPipeline();
  79794. },
  79795. enumerable: true,
  79796. configurable: true
  79797. });
  79798. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  79799. // recreate bloom and dispose old as this setting is not dynamic
  79800. var oldBloom = this.bloom;
  79801. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  79802. this.bloom.threshold = oldBloom.threshold;
  79803. for (var i = 0; i < this._cameras.length; i++) {
  79804. oldBloom.disposeEffects(this._cameras[i]);
  79805. }
  79806. };
  79807. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  79808. /**
  79809. * If the depth of field is enabled.
  79810. */
  79811. get: function () {
  79812. return this._depthOfFieldEnabled;
  79813. },
  79814. set: function (enabled) {
  79815. if (this._depthOfFieldEnabled === enabled) {
  79816. return;
  79817. }
  79818. this._depthOfFieldEnabled = enabled;
  79819. this._buildPipeline();
  79820. },
  79821. enumerable: true,
  79822. configurable: true
  79823. });
  79824. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  79825. /**
  79826. * Blur level of the depth of field effect. (Higher blur will effect performance)
  79827. */
  79828. get: function () {
  79829. return this._depthOfFieldBlurLevel;
  79830. },
  79831. set: function (value) {
  79832. if (this._depthOfFieldBlurLevel === value) {
  79833. return;
  79834. }
  79835. this._depthOfFieldBlurLevel = value;
  79836. // recreate dof and dispose old as this setting is not dynamic
  79837. var oldDof = this.depthOfField;
  79838. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  79839. this.depthOfField.focalLength = oldDof.focalLength;
  79840. this.depthOfField.focusDistance = oldDof.focusDistance;
  79841. this.depthOfField.fStop = oldDof.fStop;
  79842. this.depthOfField.lensSize = oldDof.lensSize;
  79843. for (var i = 0; i < this._cameras.length; i++) {
  79844. oldDof.disposeEffects(this._cameras[i]);
  79845. }
  79846. this._buildPipeline();
  79847. },
  79848. enumerable: true,
  79849. configurable: true
  79850. });
  79851. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  79852. get: function () {
  79853. return this._fxaaEnabled;
  79854. },
  79855. /**
  79856. * If the anti aliasing is enabled.
  79857. */
  79858. set: function (enabled) {
  79859. if (this._fxaaEnabled === enabled) {
  79860. return;
  79861. }
  79862. this._fxaaEnabled = enabled;
  79863. this._buildPipeline();
  79864. },
  79865. enumerable: true,
  79866. configurable: true
  79867. });
  79868. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  79869. get: function () {
  79870. return this._samples;
  79871. },
  79872. /**
  79873. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  79874. */
  79875. set: function (sampleCount) {
  79876. if (this._samples === sampleCount) {
  79877. return;
  79878. }
  79879. this._samples = sampleCount;
  79880. this._buildPipeline();
  79881. },
  79882. enumerable: true,
  79883. configurable: true
  79884. });
  79885. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  79886. get: function () {
  79887. return this._imageProcessingEnabled;
  79888. },
  79889. /**
  79890. * If image processing is enabled.
  79891. */
  79892. set: function (enabled) {
  79893. if (this._imageProcessingEnabled === enabled) {
  79894. return;
  79895. }
  79896. this._imageProcessingEnabled = enabled;
  79897. this._buildPipeline();
  79898. },
  79899. enumerable: true,
  79900. configurable: true
  79901. });
  79902. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  79903. get: function () {
  79904. return this._glowLayer == null;
  79905. },
  79906. /**
  79907. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  79908. */
  79909. set: function (enabled) {
  79910. if (enabled && !this._glowLayer) {
  79911. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  79912. }
  79913. else if (!enabled && this._glowLayer) {
  79914. this._glowLayer.dispose();
  79915. this._glowLayer = null;
  79916. }
  79917. },
  79918. enumerable: true,
  79919. configurable: true
  79920. });
  79921. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  79922. get: function () {
  79923. return this._chromaticAberrationEnabled;
  79924. },
  79925. /**
  79926. * Enable or disable the chromaticAberration process from the pipeline
  79927. */
  79928. set: function (enabled) {
  79929. if (this._chromaticAberrationEnabled === enabled) {
  79930. return;
  79931. }
  79932. this._chromaticAberrationEnabled = enabled;
  79933. this._buildPipeline();
  79934. },
  79935. enumerable: true,
  79936. configurable: true
  79937. });
  79938. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  79939. get: function () {
  79940. return this._grainEnabled;
  79941. },
  79942. /**
  79943. * Enable or disable the grain process from the pipeline
  79944. */
  79945. set: function (enabled) {
  79946. if (this._grainEnabled === enabled) {
  79947. return;
  79948. }
  79949. this._grainEnabled = enabled;
  79950. this._buildPipeline();
  79951. },
  79952. enumerable: true,
  79953. configurable: true
  79954. });
  79955. /**
  79956. * Force the compilation of the entire pipeline.
  79957. */
  79958. DefaultRenderingPipeline.prototype.prepare = function () {
  79959. var previousState = this._buildAllowed;
  79960. this._buildAllowed = true;
  79961. this._buildPipeline();
  79962. this._buildAllowed = previousState;
  79963. };
  79964. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  79965. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  79966. if (this._hasCleared) {
  79967. postProcess.autoClear = false;
  79968. }
  79969. else {
  79970. postProcess.autoClear = true;
  79971. this._scene.autoClear = false;
  79972. this._hasCleared = true;
  79973. }
  79974. if (!skipTextureSharing) {
  79975. if (this._prevPrevPostProcess) {
  79976. postProcess.shareOutputWith(this._prevPrevPostProcess);
  79977. }
  79978. else {
  79979. postProcess.useOwnOutput();
  79980. }
  79981. if (this._prevPostProcess) {
  79982. this._prevPrevPostProcess = this._prevPostProcess;
  79983. }
  79984. this._prevPostProcess = postProcess;
  79985. }
  79986. };
  79987. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  79988. var _this = this;
  79989. if (!this._buildAllowed) {
  79990. return;
  79991. }
  79992. this._scene.autoClear = true;
  79993. var engine = this._scene.getEngine();
  79994. this._disposePostProcesses();
  79995. if (this._cameras !== null) {
  79996. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  79997. // get back cameras to be used to reattach pipeline
  79998. this._cameras = this._camerasToBeAttached.slice();
  79999. }
  80000. this._reset();
  80001. this._prevPostProcess = null;
  80002. this._prevPrevPostProcess = null;
  80003. this._hasCleared = false;
  80004. if (this.depthOfFieldEnabled) {
  80005. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  80006. this.depthOfField.depthTexture = depthTexture;
  80007. if (!this.depthOfField._isReady()) {
  80008. this.depthOfField._updateEffects();
  80009. }
  80010. this.addEffect(this.depthOfField);
  80011. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  80012. }
  80013. if (this.bloomEnabled) {
  80014. if (!this.bloom._isReady()) {
  80015. this.bloom._updateEffects();
  80016. }
  80017. this.addEffect(this.bloom);
  80018. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  80019. }
  80020. if (this._imageProcessingEnabled) {
  80021. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  80022. if (this._hdr) {
  80023. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  80024. this._setAutoClearAndTextureSharing(this.imageProcessing);
  80025. }
  80026. else {
  80027. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  80028. }
  80029. }
  80030. if (this.sharpenEnabled) {
  80031. if (!this.sharpen.isReady()) {
  80032. this.sharpen.updateEffect();
  80033. }
  80034. this.addEffect(this._sharpenEffect);
  80035. this._setAutoClearAndTextureSharing(this.sharpen);
  80036. }
  80037. if (this.grainEnabled) {
  80038. if (!this.grain.isReady()) {
  80039. this.grain.updateEffect();
  80040. }
  80041. this.addEffect(this._grainEffect);
  80042. this._setAutoClearAndTextureSharing(this.grain);
  80043. }
  80044. if (this.chromaticAberrationEnabled) {
  80045. if (!this.chromaticAberration.isReady()) {
  80046. this.chromaticAberration.updateEffect();
  80047. }
  80048. this.addEffect(this._chromaticAberrationEffect);
  80049. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  80050. }
  80051. if (this.fxaaEnabled) {
  80052. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  80053. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  80054. this._setAutoClearAndTextureSharing(this.fxaa, true);
  80055. }
  80056. if (this._cameras !== null) {
  80057. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  80058. }
  80059. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  80060. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  80061. }
  80062. };
  80063. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  80064. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  80065. for (var i = 0; i < this._cameras.length; i++) {
  80066. var camera = this._cameras[i];
  80067. if (this.imageProcessing) {
  80068. this.imageProcessing.dispose(camera);
  80069. }
  80070. if (this.fxaa) {
  80071. this.fxaa.dispose(camera);
  80072. }
  80073. // These are created in the constructor and should not be disposed on every pipeline change
  80074. if (disposeNonRecreated) {
  80075. if (this.sharpen) {
  80076. this.sharpen.dispose(camera);
  80077. }
  80078. if (this.depthOfField) {
  80079. this.depthOfField.disposeEffects(camera);
  80080. }
  80081. if (this.bloom) {
  80082. this.bloom.disposeEffects(camera);
  80083. }
  80084. if (this.chromaticAberration) {
  80085. this.chromaticAberration.dispose(camera);
  80086. }
  80087. if (this.grain) {
  80088. this.grain.dispose(camera);
  80089. }
  80090. if (this._glowLayer) {
  80091. this._glowLayer.dispose();
  80092. }
  80093. }
  80094. }
  80095. this.imageProcessing = null;
  80096. this.fxaa = null;
  80097. if (disposeNonRecreated) {
  80098. this.sharpen = null;
  80099. this._sharpenEffect = null;
  80100. this.depthOfField = null;
  80101. this.bloom = null;
  80102. this.chromaticAberration = null;
  80103. this._chromaticAberrationEffect = null;
  80104. this.grain = null;
  80105. this._grainEffect = null;
  80106. this._glowLayer = null;
  80107. }
  80108. };
  80109. /**
  80110. * Adds a camera to the pipeline
  80111. * @param camera the camera to be added
  80112. */
  80113. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  80114. this._camerasToBeAttached.push(camera);
  80115. this._buildPipeline();
  80116. };
  80117. /**
  80118. * Removes a camera from the pipeline
  80119. * @param camera the camera to remove
  80120. */
  80121. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  80122. var index = this._camerasToBeAttached.indexOf(camera);
  80123. this._camerasToBeAttached.splice(index, 1);
  80124. this._buildPipeline();
  80125. };
  80126. /**
  80127. * Dispose of the pipeline and stop all post processes
  80128. */
  80129. DefaultRenderingPipeline.prototype.dispose = function () {
  80130. this._disposePostProcesses(true);
  80131. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80132. this._scene.autoClear = true;
  80133. if (this._resizeObserver) {
  80134. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  80135. this._resizeObserver = null;
  80136. }
  80137. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  80138. _super.prototype.dispose.call(this);
  80139. };
  80140. /**
  80141. * Serialize the rendering pipeline (Used when exporting)
  80142. * @returns the serialized object
  80143. */
  80144. DefaultRenderingPipeline.prototype.serialize = function () {
  80145. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80146. serializationObject.customType = "DefaultRenderingPipeline";
  80147. return serializationObject;
  80148. };
  80149. /**
  80150. * Parse the serialized pipeline
  80151. * @param source Source pipeline.
  80152. * @param scene The scene to load the pipeline to.
  80153. * @param rootUrl The URL of the serialized pipeline.
  80154. * @returns An instantiated pipeline from the serialized object.
  80155. */
  80156. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  80157. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  80158. };
  80159. __decorate([
  80160. BABYLON.serialize()
  80161. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  80162. __decorate([
  80163. BABYLON.serialize()
  80164. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  80165. __decorate([
  80166. BABYLON.serialize()
  80167. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  80168. __decorate([
  80169. BABYLON.serialize()
  80170. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  80171. __decorate([
  80172. BABYLON.serialize()
  80173. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  80174. __decorate([
  80175. BABYLON.serialize()
  80176. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  80177. __decorate([
  80178. BABYLON.serialize()
  80179. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  80180. __decorate([
  80181. BABYLON.serialize()
  80182. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  80183. __decorate([
  80184. BABYLON.serialize()
  80185. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  80186. __decorate([
  80187. BABYLON.serialize()
  80188. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  80189. __decorate([
  80190. BABYLON.serialize()
  80191. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  80192. __decorate([
  80193. BABYLON.serialize()
  80194. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  80195. __decorate([
  80196. BABYLON.serialize()
  80197. ], DefaultRenderingPipeline.prototype, "samples", null);
  80198. __decorate([
  80199. BABYLON.serialize()
  80200. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  80201. __decorate([
  80202. BABYLON.serialize()
  80203. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  80204. __decorate([
  80205. BABYLON.serialize()
  80206. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  80207. __decorate([
  80208. BABYLON.serialize()
  80209. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  80210. return DefaultRenderingPipeline;
  80211. }(BABYLON.PostProcessRenderPipeline));
  80212. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  80213. })(BABYLON || (BABYLON = {}));
  80214. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  80215. var BABYLON;
  80216. (function (BABYLON) {
  80217. /**
  80218. * @hidden
  80219. */
  80220. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  80221. __extends(ImageProcessingConfigurationDefines, _super);
  80222. function ImageProcessingConfigurationDefines() {
  80223. var _this = _super.call(this) || this;
  80224. _this.IMAGEPROCESSING = false;
  80225. _this.VIGNETTE = false;
  80226. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  80227. _this.VIGNETTEBLENDMODEOPAQUE = false;
  80228. _this.TONEMAPPING = false;
  80229. _this.TONEMAPPING_ACES = false;
  80230. _this.CONTRAST = false;
  80231. _this.COLORCURVES = false;
  80232. _this.COLORGRADING = false;
  80233. _this.COLORGRADING3D = false;
  80234. _this.SAMPLER3DGREENDEPTH = false;
  80235. _this.SAMPLER3DBGRMAP = false;
  80236. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  80237. _this.EXPOSURE = false;
  80238. _this.rebuild();
  80239. return _this;
  80240. }
  80241. return ImageProcessingConfigurationDefines;
  80242. }(BABYLON.MaterialDefines));
  80243. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  80244. /**
  80245. * This groups together the common properties used for image processing either in direct forward pass
  80246. * or through post processing effect depending on the use of the image processing pipeline in your scene
  80247. * or not.
  80248. */
  80249. var ImageProcessingConfiguration = /** @class */ (function () {
  80250. function ImageProcessingConfiguration() {
  80251. /**
  80252. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  80253. */
  80254. this.colorCurves = new BABYLON.ColorCurves();
  80255. this._colorCurvesEnabled = false;
  80256. this._colorGradingEnabled = false;
  80257. this._colorGradingWithGreenDepth = true;
  80258. this._colorGradingBGR = true;
  80259. /** @hidden */
  80260. this._exposure = 1.0;
  80261. this._toneMappingEnabled = false;
  80262. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  80263. this._contrast = 1.0;
  80264. /**
  80265. * Vignette stretch size.
  80266. */
  80267. this.vignetteStretch = 0;
  80268. /**
  80269. * Vignette centre X Offset.
  80270. */
  80271. this.vignetteCentreX = 0;
  80272. /**
  80273. * Vignette centre Y Offset.
  80274. */
  80275. this.vignetteCentreY = 0;
  80276. /**
  80277. * Vignette weight or intensity of the vignette effect.
  80278. */
  80279. this.vignetteWeight = 1.5;
  80280. /**
  80281. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80282. * if vignetteEnabled is set to true.
  80283. */
  80284. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  80285. /**
  80286. * Camera field of view used by the Vignette effect.
  80287. */
  80288. this.vignetteCameraFov = 0.5;
  80289. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  80290. this._vignetteEnabled = false;
  80291. this._applyByPostProcess = false;
  80292. this._isEnabled = true;
  80293. /**
  80294. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  80295. */
  80296. this.onUpdateParameters = new BABYLON.Observable();
  80297. }
  80298. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  80299. /**
  80300. * Gets wether the color curves effect is enabled.
  80301. */
  80302. get: function () {
  80303. return this._colorCurvesEnabled;
  80304. },
  80305. /**
  80306. * Sets wether the color curves effect is enabled.
  80307. */
  80308. set: function (value) {
  80309. if (this._colorCurvesEnabled === value) {
  80310. return;
  80311. }
  80312. this._colorCurvesEnabled = value;
  80313. this._updateParameters();
  80314. },
  80315. enumerable: true,
  80316. configurable: true
  80317. });
  80318. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  80319. /**
  80320. * Gets wether the color grading effect is enabled.
  80321. */
  80322. get: function () {
  80323. return this._colorGradingEnabled;
  80324. },
  80325. /**
  80326. * Sets wether the color grading effect is enabled.
  80327. */
  80328. set: function (value) {
  80329. if (this._colorGradingEnabled === value) {
  80330. return;
  80331. }
  80332. this._colorGradingEnabled = value;
  80333. this._updateParameters();
  80334. },
  80335. enumerable: true,
  80336. configurable: true
  80337. });
  80338. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  80339. /**
  80340. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  80341. */
  80342. get: function () {
  80343. return this._colorGradingWithGreenDepth;
  80344. },
  80345. /**
  80346. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  80347. */
  80348. set: function (value) {
  80349. if (this._colorGradingWithGreenDepth === value) {
  80350. return;
  80351. }
  80352. this._colorGradingWithGreenDepth = value;
  80353. this._updateParameters();
  80354. },
  80355. enumerable: true,
  80356. configurable: true
  80357. });
  80358. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  80359. /**
  80360. * Gets wether the color grading texture contains BGR values.
  80361. */
  80362. get: function () {
  80363. return this._colorGradingBGR;
  80364. },
  80365. /**
  80366. * Sets wether the color grading texture contains BGR values.
  80367. */
  80368. set: function (value) {
  80369. if (this._colorGradingBGR === value) {
  80370. return;
  80371. }
  80372. this._colorGradingBGR = value;
  80373. this._updateParameters();
  80374. },
  80375. enumerable: true,
  80376. configurable: true
  80377. });
  80378. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  80379. /**
  80380. * Gets the Exposure used in the effect.
  80381. */
  80382. get: function () {
  80383. return this._exposure;
  80384. },
  80385. /**
  80386. * Sets the Exposure used in the effect.
  80387. */
  80388. set: function (value) {
  80389. if (this._exposure === value) {
  80390. return;
  80391. }
  80392. this._exposure = value;
  80393. this._updateParameters();
  80394. },
  80395. enumerable: true,
  80396. configurable: true
  80397. });
  80398. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  80399. /**
  80400. * Gets wether the tone mapping effect is enabled.
  80401. */
  80402. get: function () {
  80403. return this._toneMappingEnabled;
  80404. },
  80405. /**
  80406. * Sets wether the tone mapping effect is enabled.
  80407. */
  80408. set: function (value) {
  80409. if (this._toneMappingEnabled === value) {
  80410. return;
  80411. }
  80412. this._toneMappingEnabled = value;
  80413. this._updateParameters();
  80414. },
  80415. enumerable: true,
  80416. configurable: true
  80417. });
  80418. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  80419. /**
  80420. * Gets the type of tone mapping effect.
  80421. */
  80422. get: function () {
  80423. return this._toneMappingType;
  80424. },
  80425. /**
  80426. * Sets the type of tone mapping effect used in BabylonJS.
  80427. */
  80428. set: function (value) {
  80429. if (this._toneMappingType === value) {
  80430. return;
  80431. }
  80432. this._toneMappingType = value;
  80433. this._updateParameters();
  80434. },
  80435. enumerable: true,
  80436. configurable: true
  80437. });
  80438. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  80439. /**
  80440. * Gets the contrast used in the effect.
  80441. */
  80442. get: function () {
  80443. return this._contrast;
  80444. },
  80445. /**
  80446. * Sets the contrast used in the effect.
  80447. */
  80448. set: function (value) {
  80449. if (this._contrast === value) {
  80450. return;
  80451. }
  80452. this._contrast = value;
  80453. this._updateParameters();
  80454. },
  80455. enumerable: true,
  80456. configurable: true
  80457. });
  80458. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  80459. /**
  80460. * Gets the vignette blend mode allowing different kind of effect.
  80461. */
  80462. get: function () {
  80463. return this._vignetteBlendMode;
  80464. },
  80465. /**
  80466. * Sets the vignette blend mode allowing different kind of effect.
  80467. */
  80468. set: function (value) {
  80469. if (this._vignetteBlendMode === value) {
  80470. return;
  80471. }
  80472. this._vignetteBlendMode = value;
  80473. this._updateParameters();
  80474. },
  80475. enumerable: true,
  80476. configurable: true
  80477. });
  80478. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  80479. /**
  80480. * Gets wether the vignette effect is enabled.
  80481. */
  80482. get: function () {
  80483. return this._vignetteEnabled;
  80484. },
  80485. /**
  80486. * Sets wether the vignette effect is enabled.
  80487. */
  80488. set: function (value) {
  80489. if (this._vignetteEnabled === value) {
  80490. return;
  80491. }
  80492. this._vignetteEnabled = value;
  80493. this._updateParameters();
  80494. },
  80495. enumerable: true,
  80496. configurable: true
  80497. });
  80498. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  80499. /**
  80500. * Gets wether the image processing is applied through a post process or not.
  80501. */
  80502. get: function () {
  80503. return this._applyByPostProcess;
  80504. },
  80505. /**
  80506. * Sets wether the image processing is applied through a post process or not.
  80507. */
  80508. set: function (value) {
  80509. if (this._applyByPostProcess === value) {
  80510. return;
  80511. }
  80512. this._applyByPostProcess = value;
  80513. this._updateParameters();
  80514. },
  80515. enumerable: true,
  80516. configurable: true
  80517. });
  80518. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  80519. /**
  80520. * Gets wether the image processing is enabled or not.
  80521. */
  80522. get: function () {
  80523. return this._isEnabled;
  80524. },
  80525. /**
  80526. * Sets wether the image processing is enabled or not.
  80527. */
  80528. set: function (value) {
  80529. if (this._isEnabled === value) {
  80530. return;
  80531. }
  80532. this._isEnabled = value;
  80533. this._updateParameters();
  80534. },
  80535. enumerable: true,
  80536. configurable: true
  80537. });
  80538. /**
  80539. * Method called each time the image processing information changes requires to recompile the effect.
  80540. */
  80541. ImageProcessingConfiguration.prototype._updateParameters = function () {
  80542. this.onUpdateParameters.notifyObservers(this);
  80543. };
  80544. ImageProcessingConfiguration.prototype.getClassName = function () {
  80545. return "ImageProcessingConfiguration";
  80546. };
  80547. /**
  80548. * Prepare the list of uniforms associated with the Image Processing effects.
  80549. * @param uniformsList The list of uniforms used in the effect
  80550. * @param defines the list of defines currently in use
  80551. */
  80552. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  80553. if (defines.EXPOSURE) {
  80554. uniforms.push("exposureLinear");
  80555. }
  80556. if (defines.CONTRAST) {
  80557. uniforms.push("contrast");
  80558. }
  80559. if (defines.COLORGRADING) {
  80560. uniforms.push("colorTransformSettings");
  80561. }
  80562. if (defines.VIGNETTE) {
  80563. uniforms.push("vInverseScreenSize");
  80564. uniforms.push("vignetteSettings1");
  80565. uniforms.push("vignetteSettings2");
  80566. }
  80567. if (defines.COLORCURVES) {
  80568. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  80569. }
  80570. };
  80571. /**
  80572. * Prepare the list of samplers associated with the Image Processing effects.
  80573. * @param uniformsList The list of uniforms used in the effect
  80574. * @param defines the list of defines currently in use
  80575. */
  80576. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  80577. if (defines.COLORGRADING) {
  80578. samplersList.push("txColorTransform");
  80579. }
  80580. };
  80581. /**
  80582. * Prepare the list of defines associated to the shader.
  80583. * @param defines the list of defines to complete
  80584. */
  80585. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  80586. if (forPostProcess === void 0) { forPostProcess = false; }
  80587. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  80588. defines.VIGNETTE = false;
  80589. defines.TONEMAPPING = false;
  80590. defines.TONEMAPPING_ACES = false;
  80591. defines.CONTRAST = false;
  80592. defines.EXPOSURE = false;
  80593. defines.COLORCURVES = false;
  80594. defines.COLORGRADING = false;
  80595. defines.COLORGRADING3D = false;
  80596. defines.IMAGEPROCESSING = false;
  80597. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  80598. return;
  80599. }
  80600. defines.VIGNETTE = this.vignetteEnabled;
  80601. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  80602. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  80603. defines.TONEMAPPING = this.toneMappingEnabled;
  80604. switch (this._toneMappingType) {
  80605. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  80606. defines.TONEMAPPING_ACES = true;
  80607. break;
  80608. }
  80609. defines.CONTRAST = (this.contrast !== 1.0);
  80610. defines.EXPOSURE = (this.exposure !== 1.0);
  80611. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  80612. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  80613. if (defines.COLORGRADING) {
  80614. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  80615. }
  80616. else {
  80617. defines.COLORGRADING3D = false;
  80618. }
  80619. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  80620. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  80621. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  80622. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  80623. };
  80624. /**
  80625. * Returns true if all the image processing information are ready.
  80626. */
  80627. ImageProcessingConfiguration.prototype.isReady = function () {
  80628. // Color Grading texure can not be none blocking.
  80629. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  80630. };
  80631. /**
  80632. * Binds the image processing to the shader.
  80633. * @param effect The effect to bind to
  80634. */
  80635. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  80636. if (aspectRatio === void 0) { aspectRatio = 1; }
  80637. // Color Curves
  80638. if (this._colorCurvesEnabled && this.colorCurves) {
  80639. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  80640. }
  80641. // Vignette
  80642. if (this._vignetteEnabled) {
  80643. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  80644. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  80645. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  80646. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  80647. var vignetteScaleX = vignetteScaleY * aspectRatio;
  80648. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  80649. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  80650. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  80651. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  80652. var vignettePower = -2.0 * this.vignetteWeight;
  80653. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  80654. }
  80655. // Exposure
  80656. effect.setFloat("exposureLinear", this.exposure);
  80657. // Contrast
  80658. effect.setFloat("contrast", this.contrast);
  80659. // Color transform settings
  80660. if (this.colorGradingTexture) {
  80661. effect.setTexture("txColorTransform", this.colorGradingTexture);
  80662. var textureSize = this.colorGradingTexture.getSize().height;
  80663. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  80664. 0.5 / textureSize, // textureOffset
  80665. textureSize, // textureSize
  80666. this.colorGradingTexture.level // weight
  80667. );
  80668. }
  80669. };
  80670. /**
  80671. * Clones the current image processing instance.
  80672. * @return The cloned image processing
  80673. */
  80674. ImageProcessingConfiguration.prototype.clone = function () {
  80675. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  80676. };
  80677. /**
  80678. * Serializes the current image processing instance to a json representation.
  80679. * @return a JSON representation
  80680. */
  80681. ImageProcessingConfiguration.prototype.serialize = function () {
  80682. return BABYLON.SerializationHelper.Serialize(this);
  80683. };
  80684. /**
  80685. * Parses the image processing from a json representation.
  80686. * @param source the JSON source to parse
  80687. * @return The parsed image processing
  80688. */
  80689. ImageProcessingConfiguration.Parse = function (source) {
  80690. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  80691. };
  80692. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  80693. /**
  80694. * Used to apply the vignette as a mix with the pixel color.
  80695. */
  80696. get: function () {
  80697. return this._VIGNETTEMODE_MULTIPLY;
  80698. },
  80699. enumerable: true,
  80700. configurable: true
  80701. });
  80702. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  80703. /**
  80704. * Used to apply the vignette as a replacement of the pixel color.
  80705. */
  80706. get: function () {
  80707. return this._VIGNETTEMODE_OPAQUE;
  80708. },
  80709. enumerable: true,
  80710. configurable: true
  80711. });
  80712. /**
  80713. * Default tone mapping applied in BabylonJS.
  80714. */
  80715. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  80716. /**
  80717. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  80718. * to other engines rendering to increase portability.
  80719. */
  80720. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  80721. // Static constants associated to the image processing.
  80722. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  80723. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  80724. __decorate([
  80725. BABYLON.serializeAsColorCurves()
  80726. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  80727. __decorate([
  80728. BABYLON.serialize()
  80729. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  80730. __decorate([
  80731. BABYLON.serializeAsTexture()
  80732. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  80733. __decorate([
  80734. BABYLON.serialize()
  80735. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  80736. __decorate([
  80737. BABYLON.serialize()
  80738. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  80739. __decorate([
  80740. BABYLON.serialize()
  80741. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  80742. __decorate([
  80743. BABYLON.serialize()
  80744. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  80745. __decorate([
  80746. BABYLON.serialize()
  80747. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  80748. __decorate([
  80749. BABYLON.serialize()
  80750. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  80751. __decorate([
  80752. BABYLON.serialize()
  80753. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  80754. __decorate([
  80755. BABYLON.serialize()
  80756. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  80757. __decorate([
  80758. BABYLON.serialize()
  80759. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  80760. __decorate([
  80761. BABYLON.serialize()
  80762. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  80763. __decorate([
  80764. BABYLON.serialize()
  80765. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  80766. __decorate([
  80767. BABYLON.serializeAsColor4()
  80768. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  80769. __decorate([
  80770. BABYLON.serialize()
  80771. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  80772. __decorate([
  80773. BABYLON.serialize()
  80774. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  80775. __decorate([
  80776. BABYLON.serialize()
  80777. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  80778. __decorate([
  80779. BABYLON.serialize()
  80780. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  80781. __decorate([
  80782. BABYLON.serialize()
  80783. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  80784. return ImageProcessingConfiguration;
  80785. }());
  80786. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  80787. })(BABYLON || (BABYLON = {}));
  80788. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  80789. var BABYLON;
  80790. (function (BABYLON) {
  80791. /**
  80792. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  80793. * It can help converting any input color in a desired output one. This can then be used to create effects
  80794. * from sepia, black and white to sixties or futuristic rendering...
  80795. *
  80796. * The only supported format is currently 3dl.
  80797. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  80798. */
  80799. var ColorGradingTexture = /** @class */ (function (_super) {
  80800. __extends(ColorGradingTexture, _super);
  80801. /**
  80802. * Instantiates a ColorGradingTexture from the following parameters.
  80803. *
  80804. * @param url The location of the color gradind data (currently only supporting 3dl)
  80805. * @param scene The scene the texture will be used in
  80806. */
  80807. function ColorGradingTexture(url, scene) {
  80808. var _this = _super.call(this, scene) || this;
  80809. if (!url) {
  80810. return _this;
  80811. }
  80812. _this._engine = scene.getEngine();
  80813. _this._textureMatrix = BABYLON.Matrix.Identity();
  80814. _this.name = url;
  80815. _this.url = url;
  80816. _this.hasAlpha = false;
  80817. _this.isCube = false;
  80818. _this.is3D = _this._engine.webGLVersion > 1;
  80819. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80820. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80821. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80822. _this.anisotropicFilteringLevel = 1;
  80823. _this._texture = _this._getFromCache(url, true);
  80824. if (!_this._texture) {
  80825. if (!scene.useDelayedTextureLoading) {
  80826. _this.loadTexture();
  80827. }
  80828. else {
  80829. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80830. }
  80831. }
  80832. return _this;
  80833. }
  80834. /**
  80835. * Returns the texture matrix used in most of the material.
  80836. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  80837. */
  80838. ColorGradingTexture.prototype.getTextureMatrix = function () {
  80839. return this._textureMatrix;
  80840. };
  80841. /**
  80842. * Occurs when the file being loaded is a .3dl LUT file.
  80843. */
  80844. ColorGradingTexture.prototype.load3dlTexture = function () {
  80845. var engine = this._engine;
  80846. var texture;
  80847. if (engine.webGLVersion === 1) {
  80848. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80849. }
  80850. else {
  80851. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80852. }
  80853. this._texture = texture;
  80854. var callback = function (text) {
  80855. if (typeof text !== "string") {
  80856. return;
  80857. }
  80858. var data = null;
  80859. var tempData = null;
  80860. var line;
  80861. var lines = text.split('\n');
  80862. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  80863. var maxColor = 0;
  80864. for (var i = 0; i < lines.length; i++) {
  80865. line = lines[i];
  80866. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  80867. continue;
  80868. if (line.indexOf('#') === 0)
  80869. continue;
  80870. var words = line.split(" ");
  80871. if (size === 0) {
  80872. // Number of space + one
  80873. size = words.length;
  80874. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  80875. tempData = new Float32Array(size * size * size * 4);
  80876. continue;
  80877. }
  80878. if (size != 0) {
  80879. var r = Math.max(parseInt(words[0]), 0);
  80880. var g = Math.max(parseInt(words[1]), 0);
  80881. var b = Math.max(parseInt(words[2]), 0);
  80882. maxColor = Math.max(r, maxColor);
  80883. maxColor = Math.max(g, maxColor);
  80884. maxColor = Math.max(b, maxColor);
  80885. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  80886. if (tempData) {
  80887. tempData[pixelStorageIndex + 0] = r;
  80888. tempData[pixelStorageIndex + 1] = g;
  80889. tempData[pixelStorageIndex + 2] = b;
  80890. }
  80891. pixelIndexSlice++;
  80892. if (pixelIndexSlice % size == 0) {
  80893. pixelIndexH++;
  80894. pixelIndexSlice = 0;
  80895. if (pixelIndexH % size == 0) {
  80896. pixelIndexW++;
  80897. pixelIndexH = 0;
  80898. }
  80899. }
  80900. }
  80901. }
  80902. if (tempData && data) {
  80903. for (var i = 0; i < tempData.length; i++) {
  80904. if (i > 0 && (i + 1) % 4 === 0) {
  80905. data[i] = 255;
  80906. }
  80907. else {
  80908. var value = tempData[i];
  80909. data[i] = (value / maxColor * 255);
  80910. }
  80911. }
  80912. }
  80913. if (texture.is3D) {
  80914. texture.updateSize(size, size, size);
  80915. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  80916. }
  80917. else {
  80918. texture.updateSize(size * size, size);
  80919. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  80920. }
  80921. };
  80922. var scene = this.getScene();
  80923. if (scene) {
  80924. scene._loadFile(this.url, callback);
  80925. }
  80926. else {
  80927. this._engine._loadFile(this.url, callback);
  80928. }
  80929. return this._texture;
  80930. };
  80931. /**
  80932. * Starts the loading process of the texture.
  80933. */
  80934. ColorGradingTexture.prototype.loadTexture = function () {
  80935. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  80936. this.load3dlTexture();
  80937. }
  80938. };
  80939. /**
  80940. * Clones the color gradind texture.
  80941. */
  80942. ColorGradingTexture.prototype.clone = function () {
  80943. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  80944. // Base texture
  80945. newTexture.level = this.level;
  80946. return newTexture;
  80947. };
  80948. /**
  80949. * Called during delayed load for textures.
  80950. */
  80951. ColorGradingTexture.prototype.delayLoad = function () {
  80952. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80953. return;
  80954. }
  80955. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80956. this._texture = this._getFromCache(this.url, true);
  80957. if (!this._texture) {
  80958. this.loadTexture();
  80959. }
  80960. };
  80961. /**
  80962. * Parses a color grading texture serialized by Babylon.
  80963. * @param parsedTexture The texture information being parsedTexture
  80964. * @param scene The scene to load the texture in
  80965. * @param rootUrl The root url of the data assets to load
  80966. * @return A color gradind texture
  80967. */
  80968. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80969. var texture = null;
  80970. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80971. texture = new ColorGradingTexture(parsedTexture.name, scene);
  80972. texture.name = parsedTexture.name;
  80973. texture.level = parsedTexture.level;
  80974. }
  80975. return texture;
  80976. };
  80977. /**
  80978. * Serializes the LUT texture to json format.
  80979. */
  80980. ColorGradingTexture.prototype.serialize = function () {
  80981. if (!this.name) {
  80982. return null;
  80983. }
  80984. var serializationObject = {};
  80985. serializationObject.name = this.name;
  80986. serializationObject.level = this.level;
  80987. serializationObject.customType = "BABYLON.ColorGradingTexture";
  80988. return serializationObject;
  80989. };
  80990. /**
  80991. * Empty line regex stored for GC.
  80992. */
  80993. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  80994. return ColorGradingTexture;
  80995. }(BABYLON.BaseTexture));
  80996. BABYLON.ColorGradingTexture = ColorGradingTexture;
  80997. })(BABYLON || (BABYLON = {}));
  80998. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  80999. var BABYLON;
  81000. (function (BABYLON) {
  81001. /**
  81002. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  81003. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  81004. * 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;
  81005. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  81006. */
  81007. var ColorCurves = /** @class */ (function () {
  81008. function ColorCurves() {
  81009. this._dirty = true;
  81010. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  81011. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  81012. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  81013. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  81014. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  81015. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  81016. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  81017. this._globalHue = 30;
  81018. this._globalDensity = 0;
  81019. this._globalSaturation = 0;
  81020. this._globalExposure = 0;
  81021. this._highlightsHue = 30;
  81022. this._highlightsDensity = 0;
  81023. this._highlightsSaturation = 0;
  81024. this._highlightsExposure = 0;
  81025. this._midtonesHue = 30;
  81026. this._midtonesDensity = 0;
  81027. this._midtonesSaturation = 0;
  81028. this._midtonesExposure = 0;
  81029. this._shadowsHue = 30;
  81030. this._shadowsDensity = 0;
  81031. this._shadowsSaturation = 0;
  81032. this._shadowsExposure = 0;
  81033. }
  81034. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  81035. /**
  81036. * Gets the global Hue value.
  81037. * 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).
  81038. */
  81039. get: function () {
  81040. return this._globalHue;
  81041. },
  81042. /**
  81043. * Sets the global Hue value.
  81044. * 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).
  81045. */
  81046. set: function (value) {
  81047. this._globalHue = value;
  81048. this._dirty = true;
  81049. },
  81050. enumerable: true,
  81051. configurable: true
  81052. });
  81053. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  81054. /**
  81055. * Gets the global Density value.
  81056. * 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.
  81057. * Values less than zero provide a filter of opposite hue.
  81058. */
  81059. get: function () {
  81060. return this._globalDensity;
  81061. },
  81062. /**
  81063. * Sets the global Density value.
  81064. * 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.
  81065. * Values less than zero provide a filter of opposite hue.
  81066. */
  81067. set: function (value) {
  81068. this._globalDensity = value;
  81069. this._dirty = true;
  81070. },
  81071. enumerable: true,
  81072. configurable: true
  81073. });
  81074. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  81075. /**
  81076. * Gets the global Saturation value.
  81077. * 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.
  81078. */
  81079. get: function () {
  81080. return this._globalSaturation;
  81081. },
  81082. /**
  81083. * Sets the global Saturation value.
  81084. * 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.
  81085. */
  81086. set: function (value) {
  81087. this._globalSaturation = value;
  81088. this._dirty = true;
  81089. },
  81090. enumerable: true,
  81091. configurable: true
  81092. });
  81093. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  81094. /**
  81095. * Gets the global Exposure value.
  81096. * 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.
  81097. */
  81098. get: function () {
  81099. return this._globalExposure;
  81100. },
  81101. /**
  81102. * Sets the global Exposure value.
  81103. * 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.
  81104. */
  81105. set: function (value) {
  81106. this._globalExposure = value;
  81107. this._dirty = true;
  81108. },
  81109. enumerable: true,
  81110. configurable: true
  81111. });
  81112. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  81113. /**
  81114. * Gets the highlights Hue value.
  81115. * 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).
  81116. */
  81117. get: function () {
  81118. return this._highlightsHue;
  81119. },
  81120. /**
  81121. * Sets the highlights Hue value.
  81122. * 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).
  81123. */
  81124. set: function (value) {
  81125. this._highlightsHue = value;
  81126. this._dirty = true;
  81127. },
  81128. enumerable: true,
  81129. configurable: true
  81130. });
  81131. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  81132. /**
  81133. * Gets the highlights Density value.
  81134. * 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.
  81135. * Values less than zero provide a filter of opposite hue.
  81136. */
  81137. get: function () {
  81138. return this._highlightsDensity;
  81139. },
  81140. /**
  81141. * Sets the highlights Density value.
  81142. * 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.
  81143. * Values less than zero provide a filter of opposite hue.
  81144. */
  81145. set: function (value) {
  81146. this._highlightsDensity = value;
  81147. this._dirty = true;
  81148. },
  81149. enumerable: true,
  81150. configurable: true
  81151. });
  81152. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  81153. /**
  81154. * Gets the highlights Saturation value.
  81155. * 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.
  81156. */
  81157. get: function () {
  81158. return this._highlightsSaturation;
  81159. },
  81160. /**
  81161. * Sets the highlights Saturation value.
  81162. * 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.
  81163. */
  81164. set: function (value) {
  81165. this._highlightsSaturation = value;
  81166. this._dirty = true;
  81167. },
  81168. enumerable: true,
  81169. configurable: true
  81170. });
  81171. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  81172. /**
  81173. * Gets the highlights Exposure value.
  81174. * 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.
  81175. */
  81176. get: function () {
  81177. return this._highlightsExposure;
  81178. },
  81179. /**
  81180. * Sets the highlights Exposure value.
  81181. * 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.
  81182. */
  81183. set: function (value) {
  81184. this._highlightsExposure = value;
  81185. this._dirty = true;
  81186. },
  81187. enumerable: true,
  81188. configurable: true
  81189. });
  81190. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  81191. /**
  81192. * Gets the midtones Hue value.
  81193. * 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).
  81194. */
  81195. get: function () {
  81196. return this._midtonesHue;
  81197. },
  81198. /**
  81199. * Sets the midtones Hue value.
  81200. * 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).
  81201. */
  81202. set: function (value) {
  81203. this._midtonesHue = value;
  81204. this._dirty = true;
  81205. },
  81206. enumerable: true,
  81207. configurable: true
  81208. });
  81209. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  81210. /**
  81211. * Gets the midtones Density value.
  81212. * 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.
  81213. * Values less than zero provide a filter of opposite hue.
  81214. */
  81215. get: function () {
  81216. return this._midtonesDensity;
  81217. },
  81218. /**
  81219. * Sets the midtones Density value.
  81220. * 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.
  81221. * Values less than zero provide a filter of opposite hue.
  81222. */
  81223. set: function (value) {
  81224. this._midtonesDensity = value;
  81225. this._dirty = true;
  81226. },
  81227. enumerable: true,
  81228. configurable: true
  81229. });
  81230. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  81231. /**
  81232. * Gets the midtones Saturation value.
  81233. * 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.
  81234. */
  81235. get: function () {
  81236. return this._midtonesSaturation;
  81237. },
  81238. /**
  81239. * Sets the midtones Saturation value.
  81240. * 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.
  81241. */
  81242. set: function (value) {
  81243. this._midtonesSaturation = value;
  81244. this._dirty = true;
  81245. },
  81246. enumerable: true,
  81247. configurable: true
  81248. });
  81249. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  81250. /**
  81251. * Gets the midtones Exposure value.
  81252. * 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.
  81253. */
  81254. get: function () {
  81255. return this._midtonesExposure;
  81256. },
  81257. /**
  81258. * Sets the midtones Exposure value.
  81259. * 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.
  81260. */
  81261. set: function (value) {
  81262. this._midtonesExposure = value;
  81263. this._dirty = true;
  81264. },
  81265. enumerable: true,
  81266. configurable: true
  81267. });
  81268. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  81269. /**
  81270. * Gets the shadows Hue value.
  81271. * 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).
  81272. */
  81273. get: function () {
  81274. return this._shadowsHue;
  81275. },
  81276. /**
  81277. * Sets the shadows Hue value.
  81278. * 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).
  81279. */
  81280. set: function (value) {
  81281. this._shadowsHue = value;
  81282. this._dirty = true;
  81283. },
  81284. enumerable: true,
  81285. configurable: true
  81286. });
  81287. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  81288. /**
  81289. * Gets the shadows Density value.
  81290. * 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.
  81291. * Values less than zero provide a filter of opposite hue.
  81292. */
  81293. get: function () {
  81294. return this._shadowsDensity;
  81295. },
  81296. /**
  81297. * Sets the shadows Density value.
  81298. * 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.
  81299. * Values less than zero provide a filter of opposite hue.
  81300. */
  81301. set: function (value) {
  81302. this._shadowsDensity = value;
  81303. this._dirty = true;
  81304. },
  81305. enumerable: true,
  81306. configurable: true
  81307. });
  81308. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  81309. /**
  81310. * Gets the shadows Saturation value.
  81311. * 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.
  81312. */
  81313. get: function () {
  81314. return this._shadowsSaturation;
  81315. },
  81316. /**
  81317. * Sets the shadows Saturation value.
  81318. * 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.
  81319. */
  81320. set: function (value) {
  81321. this._shadowsSaturation = value;
  81322. this._dirty = true;
  81323. },
  81324. enumerable: true,
  81325. configurable: true
  81326. });
  81327. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  81328. /**
  81329. * Gets the shadows Exposure value.
  81330. * 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.
  81331. */
  81332. get: function () {
  81333. return this._shadowsExposure;
  81334. },
  81335. /**
  81336. * Sets the shadows Exposure value.
  81337. * 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.
  81338. */
  81339. set: function (value) {
  81340. this._shadowsExposure = value;
  81341. this._dirty = true;
  81342. },
  81343. enumerable: true,
  81344. configurable: true
  81345. });
  81346. ColorCurves.prototype.getClassName = function () {
  81347. return "ColorCurves";
  81348. };
  81349. /**
  81350. * Binds the color curves to the shader.
  81351. * @param colorCurves The color curve to bind
  81352. * @param effect The effect to bind to
  81353. */
  81354. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  81355. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  81356. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  81357. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  81358. if (colorCurves._dirty) {
  81359. colorCurves._dirty = false;
  81360. // Fill in global info.
  81361. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  81362. // Compute highlights info.
  81363. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  81364. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  81365. // Compute midtones info.
  81366. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  81367. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  81368. // Compute shadows info.
  81369. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  81370. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  81371. // Compute deltas (neutral is midtones).
  81372. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  81373. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  81374. }
  81375. if (effect) {
  81376. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  81377. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  81378. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  81379. }
  81380. };
  81381. /**
  81382. * Prepare the list of uniforms associated with the ColorCurves effects.
  81383. * @param uniformsList The list of uniforms used in the effect
  81384. */
  81385. ColorCurves.PrepareUniforms = function (uniformsList) {
  81386. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  81387. };
  81388. /**
  81389. * Returns color grading data based on a hue, density, saturation and exposure value.
  81390. * @param filterHue The hue of the color filter.
  81391. * @param filterDensity The density of the color filter.
  81392. * @param saturation The saturation.
  81393. * @param exposure The exposure.
  81394. * @param result The result data container.
  81395. */
  81396. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  81397. if (hue == null) {
  81398. return;
  81399. }
  81400. hue = ColorCurves.clamp(hue, 0, 360);
  81401. density = ColorCurves.clamp(density, -100, 100);
  81402. saturation = ColorCurves.clamp(saturation, -100, 100);
  81403. exposure = ColorCurves.clamp(exposure, -100, 100);
  81404. // Remap the slider/config filter density with non-linear mapping and also scale by half
  81405. // so that the maximum filter density is only 50% control. This provides fine control
  81406. // for small values and reasonable range.
  81407. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  81408. density *= 0.5;
  81409. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  81410. if (density < 0) {
  81411. density *= -1;
  81412. hue = (hue + 180) % 360;
  81413. }
  81414. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  81415. result.scaleToRef(2, result);
  81416. result.a = 1 + 0.01 * saturation;
  81417. };
  81418. /**
  81419. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  81420. * @param value The input slider value in range [-100,100].
  81421. * @returns Adjusted value.
  81422. */
  81423. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  81424. value /= 100;
  81425. var x = Math.abs(value);
  81426. x = Math.pow(x, 2);
  81427. if (value < 0) {
  81428. x *= -1;
  81429. }
  81430. x *= 100;
  81431. return x;
  81432. };
  81433. /**
  81434. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  81435. * @param hue The hue (H) input.
  81436. * @param saturation The saturation (S) input.
  81437. * @param brightness The brightness (B) input.
  81438. * @result An RGBA color represented as Vector4.
  81439. */
  81440. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  81441. var h = ColorCurves.clamp(hue, 0, 360);
  81442. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  81443. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  81444. if (s === 0) {
  81445. result.r = v;
  81446. result.g = v;
  81447. result.b = v;
  81448. }
  81449. else {
  81450. // sector 0 to 5
  81451. h /= 60;
  81452. var i = Math.floor(h);
  81453. // fractional part of h
  81454. var f = h - i;
  81455. var p = v * (1 - s);
  81456. var q = v * (1 - s * f);
  81457. var t = v * (1 - s * (1 - f));
  81458. switch (i) {
  81459. case 0:
  81460. result.r = v;
  81461. result.g = t;
  81462. result.b = p;
  81463. break;
  81464. case 1:
  81465. result.r = q;
  81466. result.g = v;
  81467. result.b = p;
  81468. break;
  81469. case 2:
  81470. result.r = p;
  81471. result.g = v;
  81472. result.b = t;
  81473. break;
  81474. case 3:
  81475. result.r = p;
  81476. result.g = q;
  81477. result.b = v;
  81478. break;
  81479. case 4:
  81480. result.r = t;
  81481. result.g = p;
  81482. result.b = v;
  81483. break;
  81484. default: // case 5:
  81485. result.r = v;
  81486. result.g = p;
  81487. result.b = q;
  81488. break;
  81489. }
  81490. }
  81491. result.a = 1;
  81492. };
  81493. /**
  81494. * Returns a value clamped between min and max
  81495. * @param value The value to clamp
  81496. * @param min The minimum of value
  81497. * @param max The maximum of value
  81498. * @returns The clamped value.
  81499. */
  81500. ColorCurves.clamp = function (value, min, max) {
  81501. return Math.min(Math.max(value, min), max);
  81502. };
  81503. /**
  81504. * Clones the current color curve instance.
  81505. * @return The cloned curves
  81506. */
  81507. ColorCurves.prototype.clone = function () {
  81508. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  81509. };
  81510. /**
  81511. * Serializes the current color curve instance to a json representation.
  81512. * @return a JSON representation
  81513. */
  81514. ColorCurves.prototype.serialize = function () {
  81515. return BABYLON.SerializationHelper.Serialize(this);
  81516. };
  81517. /**
  81518. * Parses the color curve from a json representation.
  81519. * @param source the JSON source to parse
  81520. * @return The parsed curves
  81521. */
  81522. ColorCurves.Parse = function (source) {
  81523. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  81524. };
  81525. __decorate([
  81526. BABYLON.serialize()
  81527. ], ColorCurves.prototype, "_globalHue", void 0);
  81528. __decorate([
  81529. BABYLON.serialize()
  81530. ], ColorCurves.prototype, "_globalDensity", void 0);
  81531. __decorate([
  81532. BABYLON.serialize()
  81533. ], ColorCurves.prototype, "_globalSaturation", void 0);
  81534. __decorate([
  81535. BABYLON.serialize()
  81536. ], ColorCurves.prototype, "_globalExposure", void 0);
  81537. __decorate([
  81538. BABYLON.serialize()
  81539. ], ColorCurves.prototype, "_highlightsHue", void 0);
  81540. __decorate([
  81541. BABYLON.serialize()
  81542. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  81543. __decorate([
  81544. BABYLON.serialize()
  81545. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  81546. __decorate([
  81547. BABYLON.serialize()
  81548. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  81549. __decorate([
  81550. BABYLON.serialize()
  81551. ], ColorCurves.prototype, "_midtonesHue", void 0);
  81552. __decorate([
  81553. BABYLON.serialize()
  81554. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  81555. __decorate([
  81556. BABYLON.serialize()
  81557. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  81558. __decorate([
  81559. BABYLON.serialize()
  81560. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  81561. return ColorCurves;
  81562. }());
  81563. BABYLON.ColorCurves = ColorCurves;
  81564. })(BABYLON || (BABYLON = {}));
  81565. //# sourceMappingURL=babylon.colorCurves.js.map
  81566. var BABYLON;
  81567. (function (BABYLON) {
  81568. var RefractionPostProcess = /** @class */ (function (_super) {
  81569. __extends(RefractionPostProcess, _super);
  81570. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  81571. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  81572. _this.color = color;
  81573. _this.depth = depth;
  81574. _this.colorLevel = colorLevel;
  81575. _this._ownRefractionTexture = true;
  81576. _this.onActivateObservable.add(function (cam) {
  81577. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  81578. });
  81579. _this.onApplyObservable.add(function (effect) {
  81580. effect.setColor3("baseColor", _this.color);
  81581. effect.setFloat("depth", _this.depth);
  81582. effect.setFloat("colorLevel", _this.colorLevel);
  81583. effect.setTexture("refractionSampler", _this._refTexture);
  81584. });
  81585. return _this;
  81586. }
  81587. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  81588. /**
  81589. * Gets or sets the refraction texture
  81590. * Please note that you are responsible for disposing the texture if you set it manually
  81591. */
  81592. get: function () {
  81593. return this._refTexture;
  81594. },
  81595. set: function (value) {
  81596. if (this._refTexture && this._ownRefractionTexture) {
  81597. this._refTexture.dispose();
  81598. }
  81599. this._refTexture = value;
  81600. this._ownRefractionTexture = false;
  81601. },
  81602. enumerable: true,
  81603. configurable: true
  81604. });
  81605. // Methods
  81606. RefractionPostProcess.prototype.dispose = function (camera) {
  81607. if (this._refTexture && this._ownRefractionTexture) {
  81608. this._refTexture.dispose();
  81609. this._refTexture = null;
  81610. }
  81611. _super.prototype.dispose.call(this, camera);
  81612. };
  81613. return RefractionPostProcess;
  81614. }(BABYLON.PostProcess));
  81615. BABYLON.RefractionPostProcess = RefractionPostProcess;
  81616. })(BABYLON || (BABYLON = {}));
  81617. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  81618. var BABYLON;
  81619. (function (BABYLON) {
  81620. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  81621. __extends(BlackAndWhitePostProcess, _super);
  81622. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  81623. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  81624. _this.degree = 1;
  81625. _this.onApplyObservable.add(function (effect) {
  81626. effect.setFloat("degree", _this.degree);
  81627. });
  81628. return _this;
  81629. }
  81630. return BlackAndWhitePostProcess;
  81631. }(BABYLON.PostProcess));
  81632. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  81633. })(BABYLON || (BABYLON = {}));
  81634. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  81635. var BABYLON;
  81636. (function (BABYLON) {
  81637. /**
  81638. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  81639. * input texture to perform effects such as edge detection or sharpening
  81640. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  81641. */
  81642. var ConvolutionPostProcess = /** @class */ (function (_super) {
  81643. __extends(ConvolutionPostProcess, _super);
  81644. /**
  81645. * Creates a new instance ConvolutionPostProcess
  81646. * @param name The name of the effect.
  81647. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  81648. * @param options The required width/height ratio to downsize to before computing the render pass.
  81649. * @param camera The camera to apply the render pass to.
  81650. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81651. * @param engine The engine which the post process will be applied. (default: current engine)
  81652. * @param reusable If the post process can be reused on the same frame. (default: false)
  81653. * @param textureType Type of textures used when performing the post process. (default: 0)
  81654. */
  81655. function ConvolutionPostProcess(name,
  81656. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  81657. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  81658. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81659. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  81660. _this.kernel = kernel;
  81661. _this.onApply = function (effect) {
  81662. effect.setFloat2("screenSize", _this.width, _this.height);
  81663. effect.setArray("kernel", _this.kernel);
  81664. };
  81665. return _this;
  81666. }
  81667. // Statics
  81668. /**
  81669. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81670. */
  81671. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  81672. /**
  81673. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81674. */
  81675. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  81676. /**
  81677. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81678. */
  81679. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  81680. /**
  81681. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81682. */
  81683. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  81684. /**
  81685. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81686. */
  81687. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  81688. /**
  81689. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81690. */
  81691. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  81692. return ConvolutionPostProcess;
  81693. }(BABYLON.PostProcess));
  81694. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  81695. })(BABYLON || (BABYLON = {}));
  81696. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  81697. var BABYLON;
  81698. (function (BABYLON) {
  81699. var FilterPostProcess = /** @class */ (function (_super) {
  81700. __extends(FilterPostProcess, _super);
  81701. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  81702. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  81703. _this.kernelMatrix = kernelMatrix;
  81704. _this.onApply = function (effect) {
  81705. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  81706. };
  81707. return _this;
  81708. }
  81709. return FilterPostProcess;
  81710. }(BABYLON.PostProcess));
  81711. BABYLON.FilterPostProcess = FilterPostProcess;
  81712. })(BABYLON || (BABYLON = {}));
  81713. //# sourceMappingURL=babylon.filterPostProcess.js.map
  81714. var BABYLON;
  81715. (function (BABYLON) {
  81716. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  81717. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  81718. __extends(VolumetricLightScatteringPostProcess, _super);
  81719. /**
  81720. * @constructor
  81721. * @param {string} name - The post-process name
  81722. * @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)
  81723. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  81724. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  81725. * @param {number} samples - The post-process quality, default 100
  81726. * @param {number} samplingMode - The post-process filtering mode
  81727. * @param {BABYLON.Engine} engine - The babylon engine
  81728. * @param {boolean} reusable - If the post-process is reusable
  81729. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  81730. */
  81731. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  81732. if (samples === void 0) { samples = 100; }
  81733. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81734. 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;
  81735. _this._screenCoordinates = BABYLON.Vector2.Zero();
  81736. /**
  81737. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  81738. */
  81739. _this.customMeshPosition = BABYLON.Vector3.Zero();
  81740. /**
  81741. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  81742. */
  81743. _this.useCustomMeshPosition = false;
  81744. /**
  81745. * If the post-process should inverse the light scattering direction
  81746. */
  81747. _this.invert = true;
  81748. /**
  81749. * Array containing the excluded meshes not rendered in the internal pass
  81750. */
  81751. _this.excludedMeshes = new Array();
  81752. /**
  81753. * Controls the overall intensity of the post-process
  81754. */
  81755. _this.exposure = 0.3;
  81756. /**
  81757. * Dissipates each sample's contribution in range [0, 1]
  81758. */
  81759. _this.decay = 0.96815;
  81760. /**
  81761. * Controls the overall intensity of each sample
  81762. */
  81763. _this.weight = 0.58767;
  81764. /**
  81765. * Controls the density of each sample
  81766. */
  81767. _this.density = 0.926;
  81768. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  81769. engine = scene.getEngine();
  81770. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  81771. // Configure mesh
  81772. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  81773. // Configure
  81774. _this._createPass(scene, ratio.passRatio || ratio);
  81775. _this.onActivate = function (camera) {
  81776. if (!_this.isSupported) {
  81777. _this.dispose(camera);
  81778. }
  81779. _this.onActivate = null;
  81780. };
  81781. _this.onApplyObservable.add(function (effect) {
  81782. _this._updateMeshScreenCoordinates(scene);
  81783. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  81784. effect.setFloat("exposure", _this.exposure);
  81785. effect.setFloat("decay", _this.decay);
  81786. effect.setFloat("weight", _this.weight);
  81787. effect.setFloat("density", _this.density);
  81788. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  81789. });
  81790. return _this;
  81791. }
  81792. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  81793. get: function () {
  81794. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  81795. return false;
  81796. },
  81797. set: function (useDiffuseColor) {
  81798. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  81799. },
  81800. enumerable: true,
  81801. configurable: true
  81802. });
  81803. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  81804. return "VolumetricLightScatteringPostProcess";
  81805. };
  81806. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  81807. var mesh = subMesh.getMesh();
  81808. // Render this.mesh as default
  81809. if (mesh === this.mesh && mesh.material) {
  81810. return mesh.material.isReady(mesh);
  81811. }
  81812. var defines = [];
  81813. var attribs = [BABYLON.VertexBuffer.PositionKind];
  81814. var material = subMesh.getMaterial();
  81815. // Alpha test
  81816. if (material) {
  81817. if (material.needAlphaTesting()) {
  81818. defines.push("#define ALPHATEST");
  81819. }
  81820. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81821. attribs.push(BABYLON.VertexBuffer.UVKind);
  81822. defines.push("#define UV1");
  81823. }
  81824. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81825. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81826. defines.push("#define UV2");
  81827. }
  81828. }
  81829. // Bones
  81830. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81831. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81832. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81833. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81834. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  81835. }
  81836. else {
  81837. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81838. }
  81839. // Instances
  81840. if (useInstances) {
  81841. defines.push("#define INSTANCES");
  81842. attribs.push("world0");
  81843. attribs.push("world1");
  81844. attribs.push("world2");
  81845. attribs.push("world3");
  81846. }
  81847. // Get correct effect
  81848. var join = defines.join("\n");
  81849. if (this._cachedDefines !== join) {
  81850. this._cachedDefines = join;
  81851. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  81852. }
  81853. return this._volumetricLightScatteringPass.isReady();
  81854. };
  81855. /**
  81856. * Sets the new light position for light scattering effect
  81857. * @param {BABYLON.Vector3} The new custom light position
  81858. */
  81859. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  81860. this.customMeshPosition = position;
  81861. };
  81862. /**
  81863. * Returns the light position for light scattering effect
  81864. * @return {BABYLON.Vector3} The custom light position
  81865. */
  81866. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  81867. return this.customMeshPosition;
  81868. };
  81869. /**
  81870. * Disposes the internal assets and detaches the post-process from the camera
  81871. */
  81872. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  81873. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  81874. if (rttIndex !== -1) {
  81875. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  81876. }
  81877. this._volumetricLightScatteringRTT.dispose();
  81878. _super.prototype.dispose.call(this, camera);
  81879. };
  81880. /**
  81881. * Returns the render target texture used by the post-process
  81882. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  81883. */
  81884. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  81885. return this._volumetricLightScatteringRTT;
  81886. };
  81887. // Private methods
  81888. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  81889. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  81890. return true;
  81891. }
  81892. return false;
  81893. };
  81894. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  81895. var _this = this;
  81896. var engine = scene.getEngine();
  81897. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81898. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81899. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81900. this._volumetricLightScatteringRTT.renderList = null;
  81901. this._volumetricLightScatteringRTT.renderParticles = false;
  81902. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  81903. var camera = this.getCamera();
  81904. if (camera) {
  81905. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  81906. }
  81907. else {
  81908. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  81909. }
  81910. // Custom render function for submeshes
  81911. var renderSubMesh = function (subMesh) {
  81912. var mesh = subMesh.getRenderingMesh();
  81913. if (_this._meshExcluded(mesh)) {
  81914. return;
  81915. }
  81916. var material = subMesh.getMaterial();
  81917. if (!material) {
  81918. return;
  81919. }
  81920. var scene = mesh.getScene();
  81921. var engine = scene.getEngine();
  81922. // Culling
  81923. engine.setState(material.backFaceCulling);
  81924. // Managing instances
  81925. var batch = mesh._getInstancesRenderList(subMesh._id);
  81926. if (batch.mustReturn) {
  81927. return;
  81928. }
  81929. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  81930. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  81931. var effect = _this._volumetricLightScatteringPass;
  81932. if (mesh === _this.mesh) {
  81933. if (subMesh.effect) {
  81934. effect = subMesh.effect;
  81935. }
  81936. else {
  81937. effect = material.getEffect();
  81938. }
  81939. }
  81940. engine.enableEffect(effect);
  81941. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  81942. if (mesh === _this.mesh) {
  81943. material.bind(mesh.getWorldMatrix(), mesh);
  81944. }
  81945. else {
  81946. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  81947. // Alpha test
  81948. if (material && material.needAlphaTesting()) {
  81949. var alphaTexture = material.getAlphaTestTexture();
  81950. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  81951. if (alphaTexture) {
  81952. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81953. }
  81954. }
  81955. // Bones
  81956. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81957. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81958. }
  81959. }
  81960. // Draw
  81961. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  81962. }
  81963. };
  81964. // Render target texture callbacks
  81965. var savedSceneClearColor;
  81966. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  81967. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  81968. savedSceneClearColor = scene.clearColor;
  81969. scene.clearColor = sceneClearColor;
  81970. });
  81971. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  81972. scene.clearColor = savedSceneClearColor;
  81973. });
  81974. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  81975. var engine = scene.getEngine();
  81976. var index;
  81977. if (depthOnlySubMeshes.length) {
  81978. engine.setColorWrite(false);
  81979. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  81980. renderSubMesh(depthOnlySubMeshes.data[index]);
  81981. }
  81982. engine.setColorWrite(true);
  81983. }
  81984. for (index = 0; index < opaqueSubMeshes.length; index++) {
  81985. renderSubMesh(opaqueSubMeshes.data[index]);
  81986. }
  81987. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  81988. renderSubMesh(alphaTestSubMeshes.data[index]);
  81989. }
  81990. if (transparentSubMeshes.length) {
  81991. // Sort sub meshes
  81992. for (index = 0; index < transparentSubMeshes.length; index++) {
  81993. var submesh = transparentSubMeshes.data[index];
  81994. var boundingInfo = submesh.getBoundingInfo();
  81995. if (boundingInfo && scene.activeCamera) {
  81996. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  81997. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  81998. }
  81999. }
  82000. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  82001. sortedArray.sort(function (a, b) {
  82002. // Alpha index first
  82003. if (a._alphaIndex > b._alphaIndex) {
  82004. return 1;
  82005. }
  82006. if (a._alphaIndex < b._alphaIndex) {
  82007. return -1;
  82008. }
  82009. // Then distance to camera
  82010. if (a._distanceToCamera < b._distanceToCamera) {
  82011. return 1;
  82012. }
  82013. if (a._distanceToCamera > b._distanceToCamera) {
  82014. return -1;
  82015. }
  82016. return 0;
  82017. });
  82018. // Render sub meshes
  82019. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  82020. for (index = 0; index < sortedArray.length; index++) {
  82021. renderSubMesh(sortedArray[index]);
  82022. }
  82023. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82024. }
  82025. };
  82026. };
  82027. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  82028. var transform = scene.getTransformMatrix();
  82029. var meshPosition;
  82030. if (this.useCustomMeshPosition) {
  82031. meshPosition = this.customMeshPosition;
  82032. }
  82033. else if (this.attachedNode) {
  82034. meshPosition = this.attachedNode.position;
  82035. }
  82036. else {
  82037. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  82038. }
  82039. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  82040. this._screenCoordinates.x = pos.x / this._viewPort.width;
  82041. this._screenCoordinates.y = pos.y / this._viewPort.height;
  82042. if (this.invert)
  82043. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  82044. };
  82045. // Static methods
  82046. /**
  82047. * Creates a default mesh for the Volumeric Light Scattering post-process
  82048. * @param {string} The mesh name
  82049. * @param {BABYLON.Scene} The scene where to create the mesh
  82050. * @return {BABYLON.Mesh} the default mesh
  82051. */
  82052. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  82053. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  82054. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  82055. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  82056. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  82057. mesh.material = material;
  82058. return mesh;
  82059. };
  82060. __decorate([
  82061. BABYLON.serializeAsVector3()
  82062. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  82063. __decorate([
  82064. BABYLON.serialize()
  82065. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  82066. __decorate([
  82067. BABYLON.serialize()
  82068. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  82069. __decorate([
  82070. BABYLON.serializeAsMeshReference()
  82071. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  82072. __decorate([
  82073. BABYLON.serialize()
  82074. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  82075. __decorate([
  82076. BABYLON.serialize()
  82077. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  82078. __decorate([
  82079. BABYLON.serialize()
  82080. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  82081. __decorate([
  82082. BABYLON.serialize()
  82083. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  82084. __decorate([
  82085. BABYLON.serialize()
  82086. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  82087. return VolumetricLightScatteringPostProcess;
  82088. }(BABYLON.PostProcess));
  82089. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  82090. })(BABYLON || (BABYLON = {}));
  82091. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  82092. //
  82093. // This post-process allows the modification of rendered colors by using
  82094. // a 'look-up table' (LUT). This effect is also called Color Grading.
  82095. //
  82096. // The object needs to be provided an url to a texture containing the color
  82097. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  82098. // Use an image editing software to tweak the LUT to match your needs.
  82099. //
  82100. // For an example of a color LUT, see here:
  82101. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  82102. // For explanations on color grading, see here:
  82103. // http://udn.epicgames.com/Three/ColorGrading.html
  82104. //
  82105. var BABYLON;
  82106. (function (BABYLON) {
  82107. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  82108. __extends(ColorCorrectionPostProcess, _super);
  82109. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  82110. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  82111. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82112. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  82113. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82114. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82115. _this.onApply = function (effect) {
  82116. effect.setTexture("colorTable", _this._colorTableTexture);
  82117. };
  82118. return _this;
  82119. }
  82120. return ColorCorrectionPostProcess;
  82121. }(BABYLON.PostProcess));
  82122. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  82123. })(BABYLON || (BABYLON = {}));
  82124. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  82125. var BABYLON;
  82126. (function (BABYLON) {
  82127. /** Defines operator used for tonemapping */
  82128. var TonemappingOperator;
  82129. (function (TonemappingOperator) {
  82130. /** Hable */
  82131. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  82132. /** Reinhard */
  82133. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  82134. /** HejiDawson */
  82135. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  82136. /** Photographic */
  82137. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  82138. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  82139. ;
  82140. /**
  82141. * Defines a post process to apply tone mapping
  82142. */
  82143. var TonemapPostProcess = /** @class */ (function (_super) {
  82144. __extends(TonemapPostProcess, _super);
  82145. /**
  82146. * Creates a new TonemapPostProcess
  82147. * @param name defines the name of the postprocess
  82148. * @param _operator defines the operator to use
  82149. * @param exposureAdjustment defines the required exposure adjustement
  82150. * @param camera defines the camera to use (can be null)
  82151. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  82152. * @param engine defines the hosting engine (can be ignore if camera is set)
  82153. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  82154. */
  82155. function TonemapPostProcess(name, _operator,
  82156. /** Defines the required exposure adjustement */
  82157. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  82158. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82159. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82160. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  82161. _this._operator = _operator;
  82162. _this.exposureAdjustment = exposureAdjustment;
  82163. var defines = "#define ";
  82164. if (_this._operator === TonemappingOperator.Hable)
  82165. defines += "HABLE_TONEMAPPING";
  82166. else if (_this._operator === TonemappingOperator.Reinhard)
  82167. defines += "REINHARD_TONEMAPPING";
  82168. else if (_this._operator === TonemappingOperator.HejiDawson)
  82169. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  82170. else if (_this._operator === TonemappingOperator.Photographic)
  82171. defines += "PHOTOGRAPHIC_TONEMAPPING";
  82172. //sadly a second call to create the effect.
  82173. _this.updateEffect(defines);
  82174. _this.onApply = function (effect) {
  82175. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  82176. };
  82177. return _this;
  82178. }
  82179. return TonemapPostProcess;
  82180. }(BABYLON.PostProcess));
  82181. BABYLON.TonemapPostProcess = TonemapPostProcess;
  82182. })(BABYLON || (BABYLON = {}));
  82183. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  82184. var BABYLON;
  82185. (function (BABYLON) {
  82186. var DisplayPassPostProcess = /** @class */ (function (_super) {
  82187. __extends(DisplayPassPostProcess, _super);
  82188. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  82189. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  82190. }
  82191. return DisplayPassPostProcess;
  82192. }(BABYLON.PostProcess));
  82193. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  82194. })(BABYLON || (BABYLON = {}));
  82195. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  82196. var BABYLON;
  82197. (function (BABYLON) {
  82198. var HighlightsPostProcess = /** @class */ (function (_super) {
  82199. __extends(HighlightsPostProcess, _super);
  82200. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  82201. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82202. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  82203. }
  82204. return HighlightsPostProcess;
  82205. }(BABYLON.PostProcess));
  82206. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  82207. })(BABYLON || (BABYLON = {}));
  82208. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  82209. var BABYLON;
  82210. (function (BABYLON) {
  82211. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  82212. __extends(ImageProcessingPostProcess, _super);
  82213. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  82214. if (camera === void 0) { camera = null; }
  82215. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82216. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  82217. _this._fromLinearSpace = true;
  82218. /**
  82219. * Defines cache preventing GC.
  82220. */
  82221. _this._defines = {
  82222. IMAGEPROCESSING: false,
  82223. VIGNETTE: false,
  82224. VIGNETTEBLENDMODEMULTIPLY: false,
  82225. VIGNETTEBLENDMODEOPAQUE: false,
  82226. TONEMAPPING: false,
  82227. TONEMAPPING_ACES: false,
  82228. CONTRAST: false,
  82229. COLORCURVES: false,
  82230. COLORGRADING: false,
  82231. COLORGRADING3D: false,
  82232. FROMLINEARSPACE: false,
  82233. SAMPLER3DGREENDEPTH: false,
  82234. SAMPLER3DBGRMAP: false,
  82235. IMAGEPROCESSINGPOSTPROCESS: false,
  82236. EXPOSURE: false,
  82237. };
  82238. // Setup the configuration as forced by the constructor. This would then not force the
  82239. // scene materials output in linear space and let untouched the default forward pass.
  82240. if (imageProcessingConfiguration) {
  82241. imageProcessingConfiguration.applyByPostProcess = true;
  82242. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  82243. // This will cause the shader to be compiled
  82244. _this.fromLinearSpace = false;
  82245. }
  82246. // Setup the default processing configuration to the scene.
  82247. else {
  82248. _this._attachImageProcessingConfiguration(null, true);
  82249. _this.imageProcessingConfiguration.applyByPostProcess = true;
  82250. }
  82251. _this.onApply = function (effect) {
  82252. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  82253. };
  82254. return _this;
  82255. }
  82256. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  82257. /**
  82258. * Gets the image processing configuration used either in this material.
  82259. */
  82260. get: function () {
  82261. return this._imageProcessingConfiguration;
  82262. },
  82263. /**
  82264. * Sets the Default image processing configuration used either in the this material.
  82265. *
  82266. * If sets to null, the scene one is in use.
  82267. */
  82268. set: function (value) {
  82269. this._attachImageProcessingConfiguration(value);
  82270. },
  82271. enumerable: true,
  82272. configurable: true
  82273. });
  82274. /**
  82275. * Attaches a new image processing configuration to the PBR Material.
  82276. * @param configuration
  82277. */
  82278. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  82279. var _this = this;
  82280. if (doNotBuild === void 0) { doNotBuild = false; }
  82281. if (configuration === this._imageProcessingConfiguration) {
  82282. return;
  82283. }
  82284. // Detaches observer.
  82285. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82286. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82287. }
  82288. // Pick the scene configuration if needed.
  82289. if (!configuration) {
  82290. var scene = null;
  82291. var engine = this.getEngine();
  82292. var camera = this.getCamera();
  82293. if (camera) {
  82294. scene = camera.getScene();
  82295. }
  82296. else if (engine && engine.scenes) {
  82297. var scenes = engine.scenes;
  82298. scene = scenes[scenes.length - 1];
  82299. }
  82300. else {
  82301. scene = BABYLON.Engine.LastCreatedScene;
  82302. }
  82303. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  82304. }
  82305. else {
  82306. this._imageProcessingConfiguration = configuration;
  82307. }
  82308. // Attaches observer.
  82309. if (this._imageProcessingConfiguration) {
  82310. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  82311. _this._updateParameters();
  82312. });
  82313. }
  82314. // Ensure the effect will be rebuilt.
  82315. if (!doNotBuild) {
  82316. this._updateParameters();
  82317. }
  82318. };
  82319. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  82320. /**
  82321. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  82322. */
  82323. get: function () {
  82324. return this.imageProcessingConfiguration.colorCurves;
  82325. },
  82326. /**
  82327. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  82328. */
  82329. set: function (value) {
  82330. this.imageProcessingConfiguration.colorCurves = value;
  82331. },
  82332. enumerable: true,
  82333. configurable: true
  82334. });
  82335. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  82336. /**
  82337. * Gets wether the color curves effect is enabled.
  82338. */
  82339. get: function () {
  82340. return this.imageProcessingConfiguration.colorCurvesEnabled;
  82341. },
  82342. /**
  82343. * Sets wether the color curves effect is enabled.
  82344. */
  82345. set: function (value) {
  82346. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  82347. },
  82348. enumerable: true,
  82349. configurable: true
  82350. });
  82351. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  82352. /**
  82353. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  82354. */
  82355. get: function () {
  82356. return this.imageProcessingConfiguration.colorGradingTexture;
  82357. },
  82358. /**
  82359. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  82360. */
  82361. set: function (value) {
  82362. this.imageProcessingConfiguration.colorGradingTexture = value;
  82363. },
  82364. enumerable: true,
  82365. configurable: true
  82366. });
  82367. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  82368. /**
  82369. * Gets wether the color grading effect is enabled.
  82370. */
  82371. get: function () {
  82372. return this.imageProcessingConfiguration.colorGradingEnabled;
  82373. },
  82374. /**
  82375. * Gets wether the color grading effect is enabled.
  82376. */
  82377. set: function (value) {
  82378. this.imageProcessingConfiguration.colorGradingEnabled = value;
  82379. },
  82380. enumerable: true,
  82381. configurable: true
  82382. });
  82383. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  82384. /**
  82385. * Gets exposure used in the effect.
  82386. */
  82387. get: function () {
  82388. return this.imageProcessingConfiguration.exposure;
  82389. },
  82390. /**
  82391. * Sets exposure used in the effect.
  82392. */
  82393. set: function (value) {
  82394. this.imageProcessingConfiguration.exposure = value;
  82395. },
  82396. enumerable: true,
  82397. configurable: true
  82398. });
  82399. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  82400. /**
  82401. * Gets wether tonemapping is enabled or not.
  82402. */
  82403. get: function () {
  82404. return this._imageProcessingConfiguration.toneMappingEnabled;
  82405. },
  82406. /**
  82407. * Sets wether tonemapping is enabled or not
  82408. */
  82409. set: function (value) {
  82410. this._imageProcessingConfiguration.toneMappingEnabled = value;
  82411. },
  82412. enumerable: true,
  82413. configurable: true
  82414. });
  82415. ;
  82416. ;
  82417. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  82418. /**
  82419. * Gets contrast used in the effect.
  82420. */
  82421. get: function () {
  82422. return this.imageProcessingConfiguration.contrast;
  82423. },
  82424. /**
  82425. * Sets contrast used in the effect.
  82426. */
  82427. set: function (value) {
  82428. this.imageProcessingConfiguration.contrast = value;
  82429. },
  82430. enumerable: true,
  82431. configurable: true
  82432. });
  82433. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  82434. /**
  82435. * Gets Vignette stretch size.
  82436. */
  82437. get: function () {
  82438. return this.imageProcessingConfiguration.vignetteStretch;
  82439. },
  82440. /**
  82441. * Sets Vignette stretch size.
  82442. */
  82443. set: function (value) {
  82444. this.imageProcessingConfiguration.vignetteStretch = value;
  82445. },
  82446. enumerable: true,
  82447. configurable: true
  82448. });
  82449. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  82450. /**
  82451. * Gets Vignette centre X Offset.
  82452. */
  82453. get: function () {
  82454. return this.imageProcessingConfiguration.vignetteCentreX;
  82455. },
  82456. /**
  82457. * Sets Vignette centre X Offset.
  82458. */
  82459. set: function (value) {
  82460. this.imageProcessingConfiguration.vignetteCentreX = value;
  82461. },
  82462. enumerable: true,
  82463. configurable: true
  82464. });
  82465. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  82466. /**
  82467. * Gets Vignette centre Y Offset.
  82468. */
  82469. get: function () {
  82470. return this.imageProcessingConfiguration.vignetteCentreY;
  82471. },
  82472. /**
  82473. * Sets Vignette centre Y Offset.
  82474. */
  82475. set: function (value) {
  82476. this.imageProcessingConfiguration.vignetteCentreY = value;
  82477. },
  82478. enumerable: true,
  82479. configurable: true
  82480. });
  82481. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  82482. /**
  82483. * Gets Vignette weight or intensity of the vignette effect.
  82484. */
  82485. get: function () {
  82486. return this.imageProcessingConfiguration.vignetteWeight;
  82487. },
  82488. /**
  82489. * Sets Vignette weight or intensity of the vignette effect.
  82490. */
  82491. set: function (value) {
  82492. this.imageProcessingConfiguration.vignetteWeight = value;
  82493. },
  82494. enumerable: true,
  82495. configurable: true
  82496. });
  82497. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  82498. /**
  82499. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82500. * if vignetteEnabled is set to true.
  82501. */
  82502. get: function () {
  82503. return this.imageProcessingConfiguration.vignetteColor;
  82504. },
  82505. /**
  82506. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82507. * if vignetteEnabled is set to true.
  82508. */
  82509. set: function (value) {
  82510. this.imageProcessingConfiguration.vignetteColor = value;
  82511. },
  82512. enumerable: true,
  82513. configurable: true
  82514. });
  82515. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  82516. /**
  82517. * Gets Camera field of view used by the Vignette effect.
  82518. */
  82519. get: function () {
  82520. return this.imageProcessingConfiguration.vignetteCameraFov;
  82521. },
  82522. /**
  82523. * Sets Camera field of view used by the Vignette effect.
  82524. */
  82525. set: function (value) {
  82526. this.imageProcessingConfiguration.vignetteCameraFov = value;
  82527. },
  82528. enumerable: true,
  82529. configurable: true
  82530. });
  82531. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  82532. /**
  82533. * Gets the vignette blend mode allowing different kind of effect.
  82534. */
  82535. get: function () {
  82536. return this.imageProcessingConfiguration.vignetteBlendMode;
  82537. },
  82538. /**
  82539. * Sets the vignette blend mode allowing different kind of effect.
  82540. */
  82541. set: function (value) {
  82542. this.imageProcessingConfiguration.vignetteBlendMode = value;
  82543. },
  82544. enumerable: true,
  82545. configurable: true
  82546. });
  82547. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  82548. /**
  82549. * Gets wether the vignette effect is enabled.
  82550. */
  82551. get: function () {
  82552. return this.imageProcessingConfiguration.vignetteEnabled;
  82553. },
  82554. /**
  82555. * Sets wether the vignette effect is enabled.
  82556. */
  82557. set: function (value) {
  82558. this.imageProcessingConfiguration.vignetteEnabled = value;
  82559. },
  82560. enumerable: true,
  82561. configurable: true
  82562. });
  82563. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  82564. /**
  82565. * Gets wether the input of the processing is in Gamma or Linear Space.
  82566. */
  82567. get: function () {
  82568. return this._fromLinearSpace;
  82569. },
  82570. /**
  82571. * Sets wether the input of the processing is in Gamma or Linear Space.
  82572. */
  82573. set: function (value) {
  82574. if (this._fromLinearSpace === value) {
  82575. return;
  82576. }
  82577. this._fromLinearSpace = value;
  82578. this._updateParameters();
  82579. },
  82580. enumerable: true,
  82581. configurable: true
  82582. });
  82583. ImageProcessingPostProcess.prototype.getClassName = function () {
  82584. return "ImageProcessingPostProcess";
  82585. };
  82586. ImageProcessingPostProcess.prototype._updateParameters = function () {
  82587. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  82588. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  82589. var defines = "";
  82590. for (var define in this._defines) {
  82591. if (this._defines[define]) {
  82592. defines += "#define " + define + ";\r\n";
  82593. }
  82594. }
  82595. var samplers = ["textureSampler"];
  82596. var uniforms = ["scale"];
  82597. if (BABYLON.ImageProcessingConfiguration) {
  82598. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  82599. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  82600. }
  82601. this.updateEffect(defines, uniforms, samplers);
  82602. };
  82603. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  82604. _super.prototype.dispose.call(this, camera);
  82605. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82606. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82607. }
  82608. if (this._imageProcessingConfiguration) {
  82609. this.imageProcessingConfiguration.applyByPostProcess = false;
  82610. }
  82611. };
  82612. __decorate([
  82613. BABYLON.serialize()
  82614. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  82615. return ImageProcessingPostProcess;
  82616. }(BABYLON.PostProcess));
  82617. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  82618. })(BABYLON || (BABYLON = {}));
  82619. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  82620. var BABYLON;
  82621. (function (BABYLON) {
  82622. /**
  82623. * Class used to store bone information
  82624. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82625. */
  82626. var Bone = /** @class */ (function (_super) {
  82627. __extends(Bone, _super);
  82628. /**
  82629. * Create a new bone
  82630. * @param name defines the bone name
  82631. * @param skeleton defines the parent skeleton
  82632. * @param parentBone defines the parent (can be null if the bone is the root)
  82633. * @param localMatrix defines the local matrix
  82634. * @param restPose defines the rest pose matrix
  82635. * @param baseMatrix defines the base matrix
  82636. * @param index defines index of the bone in the hiearchy
  82637. */
  82638. function Bone(
  82639. /**
  82640. * defines the bone name
  82641. */
  82642. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  82643. if (parentBone === void 0) { parentBone = null; }
  82644. if (localMatrix === void 0) { localMatrix = null; }
  82645. if (restPose === void 0) { restPose = null; }
  82646. if (baseMatrix === void 0) { baseMatrix = null; }
  82647. if (index === void 0) { index = null; }
  82648. var _this = _super.call(this, name, skeleton.getScene()) || this;
  82649. _this.name = name;
  82650. /**
  82651. * Gets the list of child bones
  82652. */
  82653. _this.children = new Array();
  82654. /** Gets the animations associated with this bone */
  82655. _this.animations = new Array();
  82656. /**
  82657. * @hidden Internal only
  82658. * Set this value to map this bone to a different index in the transform matrices
  82659. * Set this value to -1 to exclude the bone from the transform matrices
  82660. */
  82661. _this._index = null;
  82662. _this._absoluteTransform = new BABYLON.Matrix();
  82663. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  82664. _this._scalingDeterminant = 1;
  82665. _this._worldTransform = new BABYLON.Matrix();
  82666. _this._needToDecompose = true;
  82667. _this._needToCompose = false;
  82668. _this._skeleton = skeleton;
  82669. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  82670. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  82671. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  82672. _this._index = index;
  82673. skeleton.bones.push(_this);
  82674. _this.setParent(parentBone, false);
  82675. if (baseMatrix || localMatrix) {
  82676. _this._updateDifferenceMatrix();
  82677. }
  82678. return _this;
  82679. }
  82680. Object.defineProperty(Bone.prototype, "_matrix", {
  82681. /** @hidden */
  82682. get: function () {
  82683. this._compose();
  82684. return this._localMatrix;
  82685. },
  82686. /** @hidden */
  82687. set: function (value) {
  82688. this._localMatrix.copyFrom(value);
  82689. this._needToDecompose = true;
  82690. },
  82691. enumerable: true,
  82692. configurable: true
  82693. });
  82694. // Members
  82695. /**
  82696. * Gets the parent skeleton
  82697. * @returns a skeleton
  82698. */
  82699. Bone.prototype.getSkeleton = function () {
  82700. return this._skeleton;
  82701. };
  82702. /**
  82703. * Gets parent bone
  82704. * @returns a bone or null if the bone is the root of the bone hierarchy
  82705. */
  82706. Bone.prototype.getParent = function () {
  82707. return this._parent;
  82708. };
  82709. /**
  82710. * Sets the parent bone
  82711. * @param parent defines the parent (can be null if the bone is the root)
  82712. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  82713. */
  82714. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  82715. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  82716. if (this._parent === parent) {
  82717. return;
  82718. }
  82719. if (this._parent) {
  82720. var index = this._parent.children.indexOf(this);
  82721. if (index !== -1) {
  82722. this._parent.children.splice(index, 1);
  82723. }
  82724. }
  82725. this._parent = parent;
  82726. if (this._parent) {
  82727. this._parent.children.push(this);
  82728. }
  82729. if (updateDifferenceMatrix) {
  82730. this._updateDifferenceMatrix();
  82731. }
  82732. this.markAsDirty();
  82733. };
  82734. /**
  82735. * Gets the local matrix
  82736. * @returns a matrix
  82737. */
  82738. Bone.prototype.getLocalMatrix = function () {
  82739. this._compose();
  82740. return this._localMatrix;
  82741. };
  82742. /**
  82743. * Gets the base matrix (initial matrix which remains unchanged)
  82744. * @returns a matrix
  82745. */
  82746. Bone.prototype.getBaseMatrix = function () {
  82747. return this._baseMatrix;
  82748. };
  82749. /**
  82750. * Gets the rest pose matrix
  82751. * @returns a matrix
  82752. */
  82753. Bone.prototype.getRestPose = function () {
  82754. return this._restPose;
  82755. };
  82756. /**
  82757. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  82758. */
  82759. Bone.prototype.getWorldMatrix = function () {
  82760. return this._worldTransform;
  82761. };
  82762. /**
  82763. * Sets the local matrix to rest pose matrix
  82764. */
  82765. Bone.prototype.returnToRest = function () {
  82766. this.updateMatrix(this._restPose.clone());
  82767. };
  82768. /**
  82769. * Gets the inverse of the absolute transform matrix.
  82770. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  82771. * @returns a matrix
  82772. */
  82773. Bone.prototype.getInvertedAbsoluteTransform = function () {
  82774. return this._invertedAbsoluteTransform;
  82775. };
  82776. /**
  82777. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  82778. * @returns a matrix
  82779. */
  82780. Bone.prototype.getAbsoluteTransform = function () {
  82781. return this._absoluteTransform;
  82782. };
  82783. Object.defineProperty(Bone.prototype, "position", {
  82784. // Properties (matches AbstractMesh properties)
  82785. /** Gets or sets current position (in local space) */
  82786. get: function () {
  82787. this._decompose();
  82788. return this._localPosition;
  82789. },
  82790. set: function (newPosition) {
  82791. this._decompose();
  82792. this._localPosition.copyFrom(newPosition);
  82793. this._markAsDirtyAndCompose();
  82794. },
  82795. enumerable: true,
  82796. configurable: true
  82797. });
  82798. Object.defineProperty(Bone.prototype, "rotation", {
  82799. /** Gets or sets current rotation (in local space) */
  82800. get: function () {
  82801. return this.getRotation();
  82802. },
  82803. set: function (newRotation) {
  82804. this.setRotation(newRotation);
  82805. },
  82806. enumerable: true,
  82807. configurable: true
  82808. });
  82809. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  82810. /** Gets or sets current rotation quaternion (in local space) */
  82811. get: function () {
  82812. this._decompose();
  82813. return this._localRotation;
  82814. },
  82815. set: function (newRotation) {
  82816. this.setRotationQuaternion(newRotation);
  82817. },
  82818. enumerable: true,
  82819. configurable: true
  82820. });
  82821. Object.defineProperty(Bone.prototype, "scaling", {
  82822. /** Gets or sets current scaling (in local space) */
  82823. get: function () {
  82824. return this.getScale();
  82825. },
  82826. set: function (newScaling) {
  82827. this.setScale(newScaling);
  82828. },
  82829. enumerable: true,
  82830. configurable: true
  82831. });
  82832. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  82833. /**
  82834. * Gets the animation properties override
  82835. */
  82836. get: function () {
  82837. return this._skeleton.animationPropertiesOverride;
  82838. },
  82839. enumerable: true,
  82840. configurable: true
  82841. });
  82842. // Methods
  82843. Bone.prototype._decompose = function () {
  82844. if (!this._needToDecompose) {
  82845. return;
  82846. }
  82847. this._needToDecompose = false;
  82848. if (!this._localScaling) {
  82849. this._localScaling = BABYLON.Vector3.Zero();
  82850. this._localRotation = BABYLON.Quaternion.Zero();
  82851. this._localPosition = BABYLON.Vector3.Zero();
  82852. }
  82853. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  82854. };
  82855. Bone.prototype._compose = function () {
  82856. if (!this._needToCompose) {
  82857. return;
  82858. }
  82859. this._needToCompose = false;
  82860. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  82861. };
  82862. /**
  82863. * Update the base and local matrices
  82864. * @param matrix defines the new base or local matrix
  82865. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  82866. * @param updateLocalMatrix defines if the local matrix should be updated
  82867. */
  82868. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  82869. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  82870. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  82871. this._baseMatrix.copyFrom(matrix);
  82872. if (updateDifferenceMatrix) {
  82873. this._updateDifferenceMatrix();
  82874. }
  82875. if (updateLocalMatrix) {
  82876. this._localMatrix.copyFrom(matrix);
  82877. this._markAsDirtyAndDecompose();
  82878. }
  82879. else {
  82880. this.markAsDirty();
  82881. }
  82882. };
  82883. /** @hidden */
  82884. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  82885. if (updateChildren === void 0) { updateChildren = true; }
  82886. if (!rootMatrix) {
  82887. rootMatrix = this._baseMatrix;
  82888. }
  82889. if (this._parent) {
  82890. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  82891. }
  82892. else {
  82893. this._absoluteTransform.copyFrom(rootMatrix);
  82894. }
  82895. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  82896. if (updateChildren) {
  82897. for (var index = 0; index < this.children.length; index++) {
  82898. this.children[index]._updateDifferenceMatrix();
  82899. }
  82900. }
  82901. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  82902. };
  82903. /**
  82904. * Flag the bone as dirty (Forcing it to update everything)
  82905. */
  82906. Bone.prototype.markAsDirty = function () {
  82907. this._currentRenderId++;
  82908. this._childRenderId++;
  82909. this._skeleton._markAsDirty();
  82910. };
  82911. Bone.prototype._markAsDirtyAndCompose = function () {
  82912. this.markAsDirty();
  82913. this._needToCompose = true;
  82914. };
  82915. Bone.prototype._markAsDirtyAndDecompose = function () {
  82916. this.markAsDirty();
  82917. this._needToDecompose = true;
  82918. };
  82919. /**
  82920. * Copy an animation range from another bone
  82921. * @param source defines the source bone
  82922. * @param rangeName defines the range name to copy
  82923. * @param frameOffset defines the frame offset
  82924. * @param rescaleAsRequired defines if rescaling must be applied if required
  82925. * @param skelDimensionsRatio defines the scaling ratio
  82926. * @returns true if operation was successful
  82927. */
  82928. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  82929. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  82930. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  82931. // all animation may be coming from a library skeleton, so may need to create animation
  82932. if (this.animations.length === 0) {
  82933. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  82934. this.animations[0].setKeys([]);
  82935. }
  82936. // get animation info / verify there is such a range from the source bone
  82937. var sourceRange = source.animations[0].getRange(rangeName);
  82938. if (!sourceRange) {
  82939. return false;
  82940. }
  82941. var from = sourceRange.from;
  82942. var to = sourceRange.to;
  82943. var sourceKeys = source.animations[0].getKeys();
  82944. // rescaling prep
  82945. var sourceBoneLength = source.length;
  82946. var sourceParent = source.getParent();
  82947. var parent = this.getParent();
  82948. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  82949. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  82950. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  82951. var destKeys = this.animations[0].getKeys();
  82952. // loop vars declaration
  82953. var orig;
  82954. var origTranslation;
  82955. var mat;
  82956. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  82957. orig = sourceKeys[key];
  82958. if (orig.frame >= from && orig.frame <= to) {
  82959. if (rescaleAsRequired) {
  82960. mat = orig.value.clone();
  82961. // scale based on parent ratio, when bone has parent
  82962. if (parentScalingReqd) {
  82963. origTranslation = mat.getTranslation();
  82964. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  82965. // scale based on skeleton dimension ratio when root bone, and value is passed
  82966. }
  82967. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  82968. origTranslation = mat.getTranslation();
  82969. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  82970. // use original when root bone, and no data for skelDimensionsRatio
  82971. }
  82972. else {
  82973. mat = orig.value;
  82974. }
  82975. }
  82976. else {
  82977. mat = orig.value;
  82978. }
  82979. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  82980. }
  82981. }
  82982. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  82983. return true;
  82984. };
  82985. /**
  82986. * Translate the bone in local or world space
  82987. * @param vec The amount to translate the bone
  82988. * @param space The space that the translation is in
  82989. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82990. */
  82991. Bone.prototype.translate = function (vec, space, mesh) {
  82992. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82993. var lm = this.getLocalMatrix();
  82994. if (space == BABYLON.Space.LOCAL) {
  82995. lm.m[12] += vec.x;
  82996. lm.m[13] += vec.y;
  82997. lm.m[14] += vec.z;
  82998. }
  82999. else {
  83000. var wm = null;
  83001. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83002. if (mesh) {
  83003. wm = mesh.getWorldMatrix();
  83004. }
  83005. this._skeleton.computeAbsoluteTransforms();
  83006. var tmat = Bone._tmpMats[0];
  83007. var tvec = Bone._tmpVecs[0];
  83008. if (this._parent) {
  83009. if (mesh && wm) {
  83010. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83011. tmat.multiplyToRef(wm, tmat);
  83012. }
  83013. else {
  83014. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83015. }
  83016. }
  83017. tmat.m[12] = 0;
  83018. tmat.m[13] = 0;
  83019. tmat.m[14] = 0;
  83020. tmat.invert();
  83021. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  83022. lm.m[12] += tvec.x;
  83023. lm.m[13] += tvec.y;
  83024. lm.m[14] += tvec.z;
  83025. }
  83026. this._markAsDirtyAndDecompose();
  83027. };
  83028. /**
  83029. * Set the postion of the bone in local or world space
  83030. * @param position The position to set the bone
  83031. * @param space The space that the position is in
  83032. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83033. */
  83034. Bone.prototype.setPosition = function (position, space, mesh) {
  83035. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83036. var lm = this.getLocalMatrix();
  83037. if (space == BABYLON.Space.LOCAL) {
  83038. lm.m[12] = position.x;
  83039. lm.m[13] = position.y;
  83040. lm.m[14] = position.z;
  83041. }
  83042. else {
  83043. var wm = null;
  83044. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83045. if (mesh) {
  83046. wm = mesh.getWorldMatrix();
  83047. }
  83048. this._skeleton.computeAbsoluteTransforms();
  83049. var tmat = Bone._tmpMats[0];
  83050. var vec = Bone._tmpVecs[0];
  83051. if (this._parent) {
  83052. if (mesh && wm) {
  83053. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83054. tmat.multiplyToRef(wm, tmat);
  83055. }
  83056. else {
  83057. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83058. }
  83059. }
  83060. tmat.invert();
  83061. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  83062. lm.m[12] = vec.x;
  83063. lm.m[13] = vec.y;
  83064. lm.m[14] = vec.z;
  83065. }
  83066. this._markAsDirtyAndDecompose();
  83067. };
  83068. /**
  83069. * Set the absolute position of the bone (world space)
  83070. * @param position The position to set the bone
  83071. * @param mesh The mesh that this bone is attached to
  83072. */
  83073. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  83074. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  83075. };
  83076. /**
  83077. * Scale the bone on the x, y and z axes (in local space)
  83078. * @param x The amount to scale the bone on the x axis
  83079. * @param y The amount to scale the bone on the y axis
  83080. * @param z The amount to scale the bone on the z axis
  83081. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  83082. */
  83083. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  83084. if (scaleChildren === void 0) { scaleChildren = false; }
  83085. var locMat = this.getLocalMatrix();
  83086. // Apply new scaling on top of current local matrix
  83087. var scaleMat = Bone._tmpMats[0];
  83088. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  83089. scaleMat.multiplyToRef(locMat, locMat);
  83090. // Invert scaling matrix and apply the inverse to all children
  83091. scaleMat.invert();
  83092. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  83093. var child = _a[_i];
  83094. var cm = child.getLocalMatrix();
  83095. cm.multiplyToRef(scaleMat, cm);
  83096. cm.m[12] *= x;
  83097. cm.m[13] *= y;
  83098. cm.m[14] *= z;
  83099. child._markAsDirtyAndDecompose();
  83100. }
  83101. this._markAsDirtyAndDecompose();
  83102. if (scaleChildren) {
  83103. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  83104. var child = _c[_b];
  83105. child.scale(x, y, z, scaleChildren);
  83106. }
  83107. }
  83108. };
  83109. /**
  83110. * Set the bone scaling in local space
  83111. * @param scale defines the scaling vector
  83112. */
  83113. Bone.prototype.setScale = function (scale) {
  83114. this._decompose();
  83115. this._localScaling.copyFrom(scale);
  83116. this._markAsDirtyAndCompose();
  83117. };
  83118. /**
  83119. * Gets the current scaling in local space
  83120. * @returns the current scaling vector
  83121. */
  83122. Bone.prototype.getScale = function () {
  83123. this._decompose();
  83124. return this._localScaling;
  83125. };
  83126. /**
  83127. * Gets the current scaling in local space and stores it in a target vector
  83128. * @param result defines the target vector
  83129. */
  83130. Bone.prototype.getScaleToRef = function (result) {
  83131. this._decompose();
  83132. result.copyFrom(this._localScaling);
  83133. };
  83134. /**
  83135. * Set the yaw, pitch, and roll of the bone in local or world space
  83136. * @param yaw The rotation of the bone on the y axis
  83137. * @param pitch The rotation of the bone on the x axis
  83138. * @param roll The rotation of the bone on the z axis
  83139. * @param space The space that the axes of rotation are in
  83140. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83141. */
  83142. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  83143. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83144. if (space === BABYLON.Space.LOCAL) {
  83145. var quat = Bone._tmpQuat;
  83146. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  83147. this.setRotationQuaternion(quat, space, mesh);
  83148. return;
  83149. }
  83150. var rotMatInv = Bone._tmpMats[0];
  83151. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83152. return;
  83153. }
  83154. var rotMat = Bone._tmpMats[1];
  83155. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  83156. rotMatInv.multiplyToRef(rotMat, rotMat);
  83157. this._rotateWithMatrix(rotMat, space, mesh);
  83158. };
  83159. /**
  83160. * Add a rotation to the bone on an axis in local or world space
  83161. * @param axis The axis to rotate the bone on
  83162. * @param amount The amount to rotate the bone
  83163. * @param space The space that the axis is in
  83164. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83165. */
  83166. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  83167. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83168. var rmat = Bone._tmpMats[0];
  83169. rmat.m[12] = 0;
  83170. rmat.m[13] = 0;
  83171. rmat.m[14] = 0;
  83172. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  83173. this._rotateWithMatrix(rmat, space, mesh);
  83174. };
  83175. /**
  83176. * Set the rotation of the bone to a particular axis angle in local or world space
  83177. * @param axis The axis to rotate the bone on
  83178. * @param angle The angle that the bone should be rotated to
  83179. * @param space The space that the axis is in
  83180. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83181. */
  83182. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  83183. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83184. if (space === BABYLON.Space.LOCAL) {
  83185. var quat = Bone._tmpQuat;
  83186. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  83187. this.setRotationQuaternion(quat, space, mesh);
  83188. return;
  83189. }
  83190. var rotMatInv = Bone._tmpMats[0];
  83191. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83192. return;
  83193. }
  83194. var rotMat = Bone._tmpMats[1];
  83195. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  83196. rotMatInv.multiplyToRef(rotMat, rotMat);
  83197. this._rotateWithMatrix(rotMat, space, mesh);
  83198. };
  83199. /**
  83200. * Set the euler rotation of the bone in local of world space
  83201. * @param rotation The euler rotation that the bone should be set to
  83202. * @param space The space that the rotation is in
  83203. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83204. */
  83205. Bone.prototype.setRotation = function (rotation, space, mesh) {
  83206. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83207. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  83208. };
  83209. /**
  83210. * Set the quaternion rotation of the bone in local of world space
  83211. * @param quat The quaternion rotation that the bone should be set to
  83212. * @param space The space that the rotation is in
  83213. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83214. */
  83215. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  83216. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83217. if (space === BABYLON.Space.LOCAL) {
  83218. this._decompose();
  83219. this._localRotation.copyFrom(quat);
  83220. this._markAsDirtyAndCompose();
  83221. return;
  83222. }
  83223. var rotMatInv = Bone._tmpMats[0];
  83224. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83225. return;
  83226. }
  83227. var rotMat = Bone._tmpMats[1];
  83228. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  83229. rotMatInv.multiplyToRef(rotMat, rotMat);
  83230. this._rotateWithMatrix(rotMat, space, mesh);
  83231. };
  83232. /**
  83233. * Set the rotation matrix of the bone in local of world space
  83234. * @param rotMat The rotation matrix that the bone should be set to
  83235. * @param space The space that the rotation is in
  83236. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83237. */
  83238. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  83239. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83240. if (space === BABYLON.Space.LOCAL) {
  83241. var quat = Bone._tmpQuat;
  83242. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  83243. this.setRotationQuaternion(quat, space, mesh);
  83244. return;
  83245. }
  83246. var rotMatInv = Bone._tmpMats[0];
  83247. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83248. return;
  83249. }
  83250. var rotMat2 = Bone._tmpMats[1];
  83251. rotMat2.copyFrom(rotMat);
  83252. rotMatInv.multiplyToRef(rotMat, rotMat2);
  83253. this._rotateWithMatrix(rotMat2, space, mesh);
  83254. };
  83255. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  83256. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83257. var lmat = this.getLocalMatrix();
  83258. var lx = lmat.m[12];
  83259. var ly = lmat.m[13];
  83260. var lz = lmat.m[14];
  83261. var parent = this.getParent();
  83262. var parentScale = Bone._tmpMats[3];
  83263. var parentScaleInv = Bone._tmpMats[4];
  83264. if (parent && space == BABYLON.Space.WORLD) {
  83265. if (mesh) {
  83266. parentScale.copyFrom(mesh.getWorldMatrix());
  83267. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  83268. }
  83269. else {
  83270. parentScale.copyFrom(parent.getAbsoluteTransform());
  83271. }
  83272. parentScaleInv.copyFrom(parentScale);
  83273. parentScaleInv.invert();
  83274. lmat.multiplyToRef(parentScale, lmat);
  83275. lmat.multiplyToRef(rmat, lmat);
  83276. lmat.multiplyToRef(parentScaleInv, lmat);
  83277. }
  83278. else {
  83279. if (space == BABYLON.Space.WORLD && mesh) {
  83280. parentScale.copyFrom(mesh.getWorldMatrix());
  83281. parentScaleInv.copyFrom(parentScale);
  83282. parentScaleInv.invert();
  83283. lmat.multiplyToRef(parentScale, lmat);
  83284. lmat.multiplyToRef(rmat, lmat);
  83285. lmat.multiplyToRef(parentScaleInv, lmat);
  83286. }
  83287. else {
  83288. lmat.multiplyToRef(rmat, lmat);
  83289. }
  83290. }
  83291. lmat.m[12] = lx;
  83292. lmat.m[13] = ly;
  83293. lmat.m[14] = lz;
  83294. this.computeAbsoluteTransforms();
  83295. this._markAsDirtyAndDecompose();
  83296. };
  83297. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  83298. var scaleMatrix = Bone._tmpMats[2];
  83299. rotMatInv.copyFrom(this.getAbsoluteTransform());
  83300. if (mesh) {
  83301. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  83302. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  83303. }
  83304. rotMatInv.invert();
  83305. if (isNaN(rotMatInv.m[0])) {
  83306. // Matrix failed to invert.
  83307. // This can happen if scale is zero for example.
  83308. return false;
  83309. }
  83310. scaleMatrix.m[0] *= this._scalingDeterminant;
  83311. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  83312. return true;
  83313. };
  83314. /**
  83315. * Get the position of the bone in local or world space
  83316. * @param space The space that the returned position is in
  83317. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83318. * @returns The position of the bone
  83319. */
  83320. Bone.prototype.getPosition = function (space, mesh) {
  83321. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83322. if (mesh === void 0) { mesh = null; }
  83323. var pos = BABYLON.Vector3.Zero();
  83324. this.getPositionToRef(space, mesh, pos);
  83325. return pos;
  83326. };
  83327. /**
  83328. * Copy the position of the bone to a vector3 in local or world space
  83329. * @param space The space that the returned position is in
  83330. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83331. * @param result The vector3 to copy the position to
  83332. */
  83333. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  83334. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83335. if (space == BABYLON.Space.LOCAL) {
  83336. var lm = this.getLocalMatrix();
  83337. result.x = lm.m[12];
  83338. result.y = lm.m[13];
  83339. result.z = lm.m[14];
  83340. }
  83341. else {
  83342. var wm = null;
  83343. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83344. if (mesh) {
  83345. wm = mesh.getWorldMatrix();
  83346. }
  83347. this._skeleton.computeAbsoluteTransforms();
  83348. var tmat = Bone._tmpMats[0];
  83349. if (mesh && wm) {
  83350. tmat.copyFrom(this.getAbsoluteTransform());
  83351. tmat.multiplyToRef(wm, tmat);
  83352. }
  83353. else {
  83354. tmat = this.getAbsoluteTransform();
  83355. }
  83356. result.x = tmat.m[12];
  83357. result.y = tmat.m[13];
  83358. result.z = tmat.m[14];
  83359. }
  83360. };
  83361. /**
  83362. * Get the absolute position of the bone (world space)
  83363. * @param mesh The mesh that this bone is attached to
  83364. * @returns The absolute position of the bone
  83365. */
  83366. Bone.prototype.getAbsolutePosition = function (mesh) {
  83367. if (mesh === void 0) { mesh = null; }
  83368. var pos = BABYLON.Vector3.Zero();
  83369. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  83370. return pos;
  83371. };
  83372. /**
  83373. * Copy the absolute position of the bone (world space) to the result param
  83374. * @param mesh The mesh that this bone is attached to
  83375. * @param result The vector3 to copy the absolute position to
  83376. */
  83377. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  83378. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  83379. };
  83380. /**
  83381. * Compute the absolute transforms of this bone and its children
  83382. */
  83383. Bone.prototype.computeAbsoluteTransforms = function () {
  83384. this._compose();
  83385. if (this._parent) {
  83386. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  83387. }
  83388. else {
  83389. this._absoluteTransform.copyFrom(this._localMatrix);
  83390. var poseMatrix = this._skeleton.getPoseMatrix();
  83391. if (poseMatrix) {
  83392. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  83393. }
  83394. }
  83395. var children = this.children;
  83396. var len = children.length;
  83397. for (var i = 0; i < len; i++) {
  83398. children[i].computeAbsoluteTransforms();
  83399. }
  83400. };
  83401. /**
  83402. * Get the world direction from an axis that is in the local space of the bone
  83403. * @param localAxis The local direction that is used to compute the world direction
  83404. * @param mesh The mesh that this bone is attached to
  83405. * @returns The world direction
  83406. */
  83407. Bone.prototype.getDirection = function (localAxis, mesh) {
  83408. if (mesh === void 0) { mesh = null; }
  83409. var result = BABYLON.Vector3.Zero();
  83410. this.getDirectionToRef(localAxis, mesh, result);
  83411. return result;
  83412. };
  83413. /**
  83414. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  83415. * @param localAxis The local direction that is used to compute the world direction
  83416. * @param mesh The mesh that this bone is attached to
  83417. * @param result The vector3 that the world direction will be copied to
  83418. */
  83419. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  83420. if (mesh === void 0) { mesh = null; }
  83421. var wm = null;
  83422. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83423. if (mesh) {
  83424. wm = mesh.getWorldMatrix();
  83425. }
  83426. this._skeleton.computeAbsoluteTransforms();
  83427. var mat = Bone._tmpMats[0];
  83428. mat.copyFrom(this.getAbsoluteTransform());
  83429. if (mesh && wm) {
  83430. mat.multiplyToRef(wm, mat);
  83431. }
  83432. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  83433. result.normalize();
  83434. };
  83435. /**
  83436. * Get the euler rotation of the bone in local or world space
  83437. * @param space The space that the rotation should be in
  83438. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83439. * @returns The euler rotation
  83440. */
  83441. Bone.prototype.getRotation = function (space, mesh) {
  83442. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83443. if (mesh === void 0) { mesh = null; }
  83444. var result = BABYLON.Vector3.Zero();
  83445. this.getRotationToRef(space, mesh, result);
  83446. return result;
  83447. };
  83448. /**
  83449. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  83450. * @param space The space that the rotation should be in
  83451. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83452. * @param result The vector3 that the rotation should be copied to
  83453. */
  83454. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  83455. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83456. if (mesh === void 0) { mesh = null; }
  83457. var quat = Bone._tmpQuat;
  83458. this.getRotationQuaternionToRef(space, mesh, quat);
  83459. quat.toEulerAnglesToRef(result);
  83460. };
  83461. /**
  83462. * Get the quaternion rotation of the bone in either local or world space
  83463. * @param space The space that the rotation should be in
  83464. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83465. * @returns The quaternion rotation
  83466. */
  83467. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  83468. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83469. if (mesh === void 0) { mesh = null; }
  83470. var result = BABYLON.Quaternion.Identity();
  83471. this.getRotationQuaternionToRef(space, mesh, result);
  83472. return result;
  83473. };
  83474. /**
  83475. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  83476. * @param space The space that the rotation should be in
  83477. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83478. * @param result The quaternion that the rotation should be copied to
  83479. */
  83480. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  83481. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83482. if (mesh === void 0) { mesh = null; }
  83483. if (space == BABYLON.Space.LOCAL) {
  83484. this._decompose();
  83485. result.copyFrom(this._localRotation);
  83486. }
  83487. else {
  83488. var mat = Bone._tmpMats[0];
  83489. var amat = this.getAbsoluteTransform();
  83490. if (mesh) {
  83491. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  83492. }
  83493. else {
  83494. mat.copyFrom(amat);
  83495. }
  83496. mat.m[0] *= this._scalingDeterminant;
  83497. mat.m[1] *= this._scalingDeterminant;
  83498. mat.m[2] *= this._scalingDeterminant;
  83499. mat.decompose(undefined, result, undefined);
  83500. }
  83501. };
  83502. /**
  83503. * Get the rotation matrix of the bone in local or world space
  83504. * @param space The space that the rotation should be in
  83505. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83506. * @returns The rotation matrix
  83507. */
  83508. Bone.prototype.getRotationMatrix = function (space, mesh) {
  83509. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83510. var result = BABYLON.Matrix.Identity();
  83511. this.getRotationMatrixToRef(space, mesh, result);
  83512. return result;
  83513. };
  83514. /**
  83515. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  83516. * @param space The space that the rotation should be in
  83517. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83518. * @param result The quaternion that the rotation should be copied to
  83519. */
  83520. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  83521. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83522. if (space == BABYLON.Space.LOCAL) {
  83523. this.getLocalMatrix().getRotationMatrixToRef(result);
  83524. }
  83525. else {
  83526. var mat = Bone._tmpMats[0];
  83527. var amat = this.getAbsoluteTransform();
  83528. if (mesh) {
  83529. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  83530. }
  83531. else {
  83532. mat.copyFrom(amat);
  83533. }
  83534. mat.m[0] *= this._scalingDeterminant;
  83535. mat.m[1] *= this._scalingDeterminant;
  83536. mat.m[2] *= this._scalingDeterminant;
  83537. mat.getRotationMatrixToRef(result);
  83538. }
  83539. };
  83540. /**
  83541. * Get the world position of a point that is in the local space of the bone
  83542. * @param position The local position
  83543. * @param mesh The mesh that this bone is attached to
  83544. * @returns The world position
  83545. */
  83546. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  83547. if (mesh === void 0) { mesh = null; }
  83548. var result = BABYLON.Vector3.Zero();
  83549. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  83550. return result;
  83551. };
  83552. /**
  83553. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  83554. * @param position The local position
  83555. * @param mesh The mesh that this bone is attached to
  83556. * @param result The vector3 that the world position should be copied to
  83557. */
  83558. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  83559. if (mesh === void 0) { mesh = null; }
  83560. var wm = null;
  83561. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83562. if (mesh) {
  83563. wm = mesh.getWorldMatrix();
  83564. }
  83565. this._skeleton.computeAbsoluteTransforms();
  83566. var tmat = Bone._tmpMats[0];
  83567. if (mesh && wm) {
  83568. tmat.copyFrom(this.getAbsoluteTransform());
  83569. tmat.multiplyToRef(wm, tmat);
  83570. }
  83571. else {
  83572. tmat = this.getAbsoluteTransform();
  83573. }
  83574. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  83575. };
  83576. /**
  83577. * Get the local position of a point that is in world space
  83578. * @param position The world position
  83579. * @param mesh The mesh that this bone is attached to
  83580. * @returns The local position
  83581. */
  83582. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  83583. if (mesh === void 0) { mesh = null; }
  83584. var result = BABYLON.Vector3.Zero();
  83585. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  83586. return result;
  83587. };
  83588. /**
  83589. * Get the local position of a point that is in world space and copy it to the result param
  83590. * @param position The world position
  83591. * @param mesh The mesh that this bone is attached to
  83592. * @param result The vector3 that the local position should be copied to
  83593. */
  83594. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  83595. if (mesh === void 0) { mesh = null; }
  83596. var wm = null;
  83597. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83598. if (mesh) {
  83599. wm = mesh.getWorldMatrix();
  83600. }
  83601. this._skeleton.computeAbsoluteTransforms();
  83602. var tmat = Bone._tmpMats[0];
  83603. tmat.copyFrom(this.getAbsoluteTransform());
  83604. if (mesh && wm) {
  83605. tmat.multiplyToRef(wm, tmat);
  83606. }
  83607. tmat.invert();
  83608. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  83609. };
  83610. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83611. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  83612. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83613. return Bone;
  83614. }(BABYLON.Node));
  83615. BABYLON.Bone = Bone;
  83616. })(BABYLON || (BABYLON = {}));
  83617. //# sourceMappingURL=babylon.bone.js.map
  83618. var BABYLON;
  83619. (function (BABYLON) {
  83620. /**
  83621. * Class used to apply inverse kinematics to bones
  83622. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  83623. */
  83624. var BoneIKController = /** @class */ (function () {
  83625. /**
  83626. * Creates a new BoneIKController
  83627. * @param mesh defines the mesh to control
  83628. * @param bone defines the bone to control
  83629. * @param options defines options to set up the controller
  83630. */
  83631. function BoneIKController(mesh, bone, options) {
  83632. /**
  83633. * Gets or sets the target position
  83634. */
  83635. this.targetPosition = BABYLON.Vector3.Zero();
  83636. /**
  83637. * Gets or sets the pole target position
  83638. */
  83639. this.poleTargetPosition = BABYLON.Vector3.Zero();
  83640. /**
  83641. * Gets or sets the pole target local offset
  83642. */
  83643. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  83644. /**
  83645. * Gets or sets the pole angle
  83646. */
  83647. this.poleAngle = 0;
  83648. /**
  83649. * 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)
  83650. */
  83651. this.slerpAmount = 1;
  83652. this._bone1Quat = BABYLON.Quaternion.Identity();
  83653. this._bone1Mat = BABYLON.Matrix.Identity();
  83654. this._bone2Ang = Math.PI;
  83655. this._maxAngle = Math.PI;
  83656. this._rightHandedSystem = false;
  83657. this._bendAxis = BABYLON.Vector3.Right();
  83658. this._slerping = false;
  83659. this._adjustRoll = 0;
  83660. this._bone2 = bone;
  83661. this._bone1 = bone.getParent();
  83662. if (!this._bone1) {
  83663. return;
  83664. }
  83665. this.mesh = mesh;
  83666. var bonePos = bone.getPosition();
  83667. if (bone.getAbsoluteTransform().determinant() > 0) {
  83668. this._rightHandedSystem = true;
  83669. this._bendAxis.x = 0;
  83670. this._bendAxis.y = 0;
  83671. this._bendAxis.z = -1;
  83672. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  83673. this._adjustRoll = Math.PI * .5;
  83674. this._bendAxis.z = 1;
  83675. }
  83676. }
  83677. if (this._bone1.length) {
  83678. var boneScale1 = this._bone1.getScale();
  83679. var boneScale2 = this._bone2.getScale();
  83680. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  83681. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  83682. }
  83683. else if (this._bone1.children[0]) {
  83684. mesh.computeWorldMatrix(true);
  83685. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  83686. var pos2 = this._bone2.getAbsolutePosition(mesh);
  83687. var pos3 = this._bone1.getAbsolutePosition(mesh);
  83688. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  83689. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  83690. }
  83691. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  83692. this.maxAngle = Math.PI;
  83693. if (options) {
  83694. if (options.targetMesh) {
  83695. this.targetMesh = options.targetMesh;
  83696. this.targetMesh.computeWorldMatrix(true);
  83697. }
  83698. if (options.poleTargetMesh) {
  83699. this.poleTargetMesh = options.poleTargetMesh;
  83700. this.poleTargetMesh.computeWorldMatrix(true);
  83701. }
  83702. else if (options.poleTargetBone) {
  83703. this.poleTargetBone = options.poleTargetBone;
  83704. }
  83705. else if (this._bone1.getParent()) {
  83706. this.poleTargetBone = this._bone1.getParent();
  83707. }
  83708. if (options.poleTargetLocalOffset) {
  83709. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  83710. }
  83711. if (options.poleAngle) {
  83712. this.poleAngle = options.poleAngle;
  83713. }
  83714. if (options.bendAxis) {
  83715. this._bendAxis.copyFrom(options.bendAxis);
  83716. }
  83717. if (options.maxAngle) {
  83718. this.maxAngle = options.maxAngle;
  83719. }
  83720. if (options.slerpAmount) {
  83721. this.slerpAmount = options.slerpAmount;
  83722. }
  83723. }
  83724. }
  83725. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  83726. /**
  83727. * Gets or sets maximum allowed angle
  83728. */
  83729. get: function () {
  83730. return this._maxAngle;
  83731. },
  83732. set: function (value) {
  83733. this._setMaxAngle(value);
  83734. },
  83735. enumerable: true,
  83736. configurable: true
  83737. });
  83738. BoneIKController.prototype._setMaxAngle = function (ang) {
  83739. if (ang < 0) {
  83740. ang = 0;
  83741. }
  83742. if (ang > Math.PI || ang == undefined) {
  83743. ang = Math.PI;
  83744. }
  83745. this._maxAngle = ang;
  83746. var a = this._bone1Length;
  83747. var b = this._bone2Length;
  83748. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  83749. };
  83750. /**
  83751. * Force the controller to update the bones
  83752. */
  83753. BoneIKController.prototype.update = function () {
  83754. var bone1 = this._bone1;
  83755. if (!bone1) {
  83756. return;
  83757. }
  83758. var target = this.targetPosition;
  83759. var poleTarget = this.poleTargetPosition;
  83760. var mat1 = BoneIKController._tmpMats[0];
  83761. var mat2 = BoneIKController._tmpMats[1];
  83762. if (this.targetMesh) {
  83763. target.copyFrom(this.targetMesh.getAbsolutePosition());
  83764. }
  83765. if (this.poleTargetBone) {
  83766. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  83767. }
  83768. else if (this.poleTargetMesh) {
  83769. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  83770. }
  83771. var bonePos = BoneIKController._tmpVecs[0];
  83772. var zaxis = BoneIKController._tmpVecs[1];
  83773. var xaxis = BoneIKController._tmpVecs[2];
  83774. var yaxis = BoneIKController._tmpVecs[3];
  83775. var upAxis = BoneIKController._tmpVecs[4];
  83776. var _tmpQuat = BoneIKController._tmpQuat;
  83777. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  83778. poleTarget.subtractToRef(bonePos, upAxis);
  83779. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  83780. upAxis.y = 1;
  83781. }
  83782. else {
  83783. upAxis.normalize();
  83784. }
  83785. target.subtractToRef(bonePos, yaxis);
  83786. yaxis.normalize();
  83787. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  83788. zaxis.normalize();
  83789. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  83790. xaxis.normalize();
  83791. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  83792. var a = this._bone1Length;
  83793. var b = this._bone2Length;
  83794. var c = BABYLON.Vector3.Distance(bonePos, target);
  83795. if (this._maxReach > 0) {
  83796. c = Math.min(this._maxReach, c);
  83797. }
  83798. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  83799. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  83800. if (acosa > 1) {
  83801. acosa = 1;
  83802. }
  83803. if (acosb > 1) {
  83804. acosb = 1;
  83805. }
  83806. if (acosa < -1) {
  83807. acosa = -1;
  83808. }
  83809. if (acosb < -1) {
  83810. acosb = -1;
  83811. }
  83812. var angA = Math.acos(acosa);
  83813. var angB = Math.acos(acosb);
  83814. var angC = -angA - angB;
  83815. if (this._rightHandedSystem) {
  83816. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  83817. mat2.multiplyToRef(mat1, mat1);
  83818. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  83819. mat2.multiplyToRef(mat1, mat1);
  83820. }
  83821. else {
  83822. var _tmpVec = BoneIKController._tmpVecs[5];
  83823. _tmpVec.copyFrom(this._bendAxis);
  83824. _tmpVec.x *= -1;
  83825. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  83826. mat2.multiplyToRef(mat1, mat1);
  83827. }
  83828. if (this.poleAngle) {
  83829. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  83830. mat1.multiplyToRef(mat2, mat1);
  83831. }
  83832. if (this._bone1) {
  83833. if (this.slerpAmount < 1) {
  83834. if (!this._slerping) {
  83835. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  83836. }
  83837. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  83838. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  83839. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  83840. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  83841. this._slerping = true;
  83842. }
  83843. else {
  83844. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  83845. this._bone1Mat.copyFrom(mat1);
  83846. this._slerping = false;
  83847. }
  83848. }
  83849. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  83850. this._bone2Ang = angC;
  83851. };
  83852. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83853. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  83854. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83855. return BoneIKController;
  83856. }());
  83857. BABYLON.BoneIKController = BoneIKController;
  83858. })(BABYLON || (BABYLON = {}));
  83859. //# sourceMappingURL=babylon.boneIKController.js.map
  83860. var BABYLON;
  83861. (function (BABYLON) {
  83862. /**
  83863. * Class used to make a bone look toward a point in space
  83864. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  83865. */
  83866. var BoneLookController = /** @class */ (function () {
  83867. /**
  83868. * Create a BoneLookController
  83869. * @param mesh the mesh that the bone belongs to
  83870. * @param bone the bone that will be looking to the target
  83871. * @param target the target Vector3 to look at
  83872. * @param settings optional settings:
  83873. * * maxYaw: the maximum angle the bone will yaw to
  83874. * * minYaw: the minimum angle the bone will yaw to
  83875. * * maxPitch: the maximum angle the bone will pitch to
  83876. * * minPitch: the minimum angle the bone will yaw to
  83877. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  83878. * * upAxis: the up axis of the coordinate system
  83879. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  83880. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  83881. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  83882. * * adjustYaw: used to make an adjustment to the yaw of the bone
  83883. * * adjustPitch: used to make an adjustment to the pitch of the bone
  83884. * * adjustRoll: used to make an adjustment to the roll of the bone
  83885. **/
  83886. function BoneLookController(mesh, bone, target, options) {
  83887. /**
  83888. * The up axis of the coordinate system that is used when the bone is rotated
  83889. */
  83890. this.upAxis = BABYLON.Vector3.Up();
  83891. /**
  83892. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  83893. */
  83894. this.upAxisSpace = BABYLON.Space.LOCAL;
  83895. /**
  83896. * Used to make an adjustment to the yaw of the bone
  83897. */
  83898. this.adjustYaw = 0;
  83899. /**
  83900. * Used to make an adjustment to the pitch of the bone
  83901. */
  83902. this.adjustPitch = 0;
  83903. /**
  83904. * Used to make an adjustment to the roll of the bone
  83905. */
  83906. this.adjustRoll = 0;
  83907. /**
  83908. * 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)
  83909. */
  83910. this.slerpAmount = 1;
  83911. this._boneQuat = BABYLON.Quaternion.Identity();
  83912. this._slerping = false;
  83913. this._firstFrameSkipped = false;
  83914. this._fowardAxis = BABYLON.Vector3.Forward();
  83915. this.mesh = mesh;
  83916. this.bone = bone;
  83917. this.target = target;
  83918. if (options) {
  83919. if (options.adjustYaw) {
  83920. this.adjustYaw = options.adjustYaw;
  83921. }
  83922. if (options.adjustPitch) {
  83923. this.adjustPitch = options.adjustPitch;
  83924. }
  83925. if (options.adjustRoll) {
  83926. this.adjustRoll = options.adjustRoll;
  83927. }
  83928. if (options.maxYaw != null) {
  83929. this.maxYaw = options.maxYaw;
  83930. }
  83931. else {
  83932. this.maxYaw = Math.PI;
  83933. }
  83934. if (options.minYaw != null) {
  83935. this.minYaw = options.minYaw;
  83936. }
  83937. else {
  83938. this.minYaw = -Math.PI;
  83939. }
  83940. if (options.maxPitch != null) {
  83941. this.maxPitch = options.maxPitch;
  83942. }
  83943. else {
  83944. this.maxPitch = Math.PI;
  83945. }
  83946. if (options.minPitch != null) {
  83947. this.minPitch = options.minPitch;
  83948. }
  83949. else {
  83950. this.minPitch = -Math.PI;
  83951. }
  83952. if (options.slerpAmount != null) {
  83953. this.slerpAmount = options.slerpAmount;
  83954. }
  83955. if (options.upAxis != null) {
  83956. this.upAxis = options.upAxis;
  83957. }
  83958. if (options.upAxisSpace != null) {
  83959. this.upAxisSpace = options.upAxisSpace;
  83960. }
  83961. if (options.yawAxis != null || options.pitchAxis != null) {
  83962. var newYawAxis = BABYLON.Axis.Y;
  83963. var newPitchAxis = BABYLON.Axis.X;
  83964. if (options.yawAxis != null) {
  83965. newYawAxis = options.yawAxis.clone();
  83966. newYawAxis.normalize();
  83967. }
  83968. if (options.pitchAxis != null) {
  83969. newPitchAxis = options.pitchAxis.clone();
  83970. newPitchAxis.normalize();
  83971. }
  83972. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  83973. this._transformYawPitch = BABYLON.Matrix.Identity();
  83974. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  83975. this._transformYawPitchInv = this._transformYawPitch.clone();
  83976. this._transformYawPitch.invert();
  83977. }
  83978. }
  83979. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  83980. this.upAxisSpace = BABYLON.Space.LOCAL;
  83981. }
  83982. }
  83983. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  83984. /**
  83985. * Gets or sets the minimum yaw angle that the bone can look to
  83986. */
  83987. get: function () {
  83988. return this._minYaw;
  83989. },
  83990. set: function (value) {
  83991. this._minYaw = value;
  83992. this._minYawSin = Math.sin(value);
  83993. this._minYawCos = Math.cos(value);
  83994. if (this._maxYaw != null) {
  83995. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  83996. this._yawRange = this._maxYaw - this._minYaw;
  83997. }
  83998. },
  83999. enumerable: true,
  84000. configurable: true
  84001. });
  84002. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  84003. /**
  84004. * Gets or sets the maximum yaw angle that the bone can look to
  84005. */
  84006. get: function () {
  84007. return this._maxYaw;
  84008. },
  84009. set: function (value) {
  84010. this._maxYaw = value;
  84011. this._maxYawSin = Math.sin(value);
  84012. this._maxYawCos = Math.cos(value);
  84013. if (this._minYaw != null) {
  84014. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  84015. this._yawRange = this._maxYaw - this._minYaw;
  84016. }
  84017. },
  84018. enumerable: true,
  84019. configurable: true
  84020. });
  84021. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  84022. /**
  84023. * Gets or sets the minimum pitch angle that the bone can look to
  84024. */
  84025. get: function () {
  84026. return this._minPitch;
  84027. },
  84028. set: function (value) {
  84029. this._minPitch = value;
  84030. this._minPitchTan = Math.tan(value);
  84031. },
  84032. enumerable: true,
  84033. configurable: true
  84034. });
  84035. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  84036. /**
  84037. * Gets or sets the maximum pitch angle that the bone can look to
  84038. */
  84039. get: function () {
  84040. return this._maxPitch;
  84041. },
  84042. set: function (value) {
  84043. this._maxPitch = value;
  84044. this._maxPitchTan = Math.tan(value);
  84045. },
  84046. enumerable: true,
  84047. configurable: true
  84048. });
  84049. /**
  84050. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  84051. */
  84052. BoneLookController.prototype.update = function () {
  84053. //skip the first frame when slerping so that the mesh rotation is correct
  84054. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  84055. this._firstFrameSkipped = true;
  84056. return;
  84057. }
  84058. var bone = this.bone;
  84059. var bonePos = BoneLookController._tmpVecs[0];
  84060. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  84061. var target = this.target;
  84062. var _tmpMat1 = BoneLookController._tmpMats[0];
  84063. var _tmpMat2 = BoneLookController._tmpMats[1];
  84064. var mesh = this.mesh;
  84065. var parentBone = bone.getParent();
  84066. var upAxis = BoneLookController._tmpVecs[1];
  84067. upAxis.copyFrom(this.upAxis);
  84068. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  84069. if (this._transformYawPitch) {
  84070. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  84071. }
  84072. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  84073. }
  84074. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  84075. mesh.getDirectionToRef(upAxis, upAxis);
  84076. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  84077. upAxis.normalize();
  84078. }
  84079. }
  84080. var checkYaw = false;
  84081. var checkPitch = false;
  84082. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  84083. checkYaw = true;
  84084. }
  84085. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  84086. checkPitch = true;
  84087. }
  84088. if (checkYaw || checkPitch) {
  84089. var spaceMat = BoneLookController._tmpMats[2];
  84090. var spaceMatInv = BoneLookController._tmpMats[3];
  84091. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  84092. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  84093. }
  84094. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  84095. spaceMat.copyFrom(mesh.getWorldMatrix());
  84096. }
  84097. else {
  84098. var forwardAxis = BoneLookController._tmpVecs[2];
  84099. forwardAxis.copyFrom(this._fowardAxis);
  84100. if (this._transformYawPitch) {
  84101. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  84102. }
  84103. if (parentBone) {
  84104. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  84105. }
  84106. else {
  84107. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  84108. }
  84109. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  84110. rightAxis.normalize();
  84111. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  84112. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  84113. }
  84114. spaceMat.invertToRef(spaceMatInv);
  84115. var xzlen = null;
  84116. if (checkPitch) {
  84117. var localTarget = BoneLookController._tmpVecs[3];
  84118. target.subtractToRef(bonePos, localTarget);
  84119. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  84120. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84121. var pitch = Math.atan2(localTarget.y, xzlen);
  84122. var newPitch = pitch;
  84123. if (pitch > this._maxPitch) {
  84124. localTarget.y = this._maxPitchTan * xzlen;
  84125. newPitch = this._maxPitch;
  84126. }
  84127. else if (pitch < this._minPitch) {
  84128. localTarget.y = this._minPitchTan * xzlen;
  84129. newPitch = this._minPitch;
  84130. }
  84131. if (pitch != newPitch) {
  84132. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  84133. localTarget.addInPlace(bonePos);
  84134. target = localTarget;
  84135. }
  84136. }
  84137. if (checkYaw) {
  84138. var localTarget = BoneLookController._tmpVecs[4];
  84139. target.subtractToRef(bonePos, localTarget);
  84140. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  84141. var yaw = Math.atan2(localTarget.x, localTarget.z);
  84142. var newYaw = yaw;
  84143. if (yaw > this._maxYaw || yaw < this._minYaw) {
  84144. if (xzlen == null) {
  84145. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84146. }
  84147. if (this._yawRange > Math.PI) {
  84148. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  84149. localTarget.z = this._maxYawCos * xzlen;
  84150. localTarget.x = this._maxYawSin * xzlen;
  84151. newYaw = this._maxYaw;
  84152. }
  84153. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  84154. localTarget.z = this._minYawCos * xzlen;
  84155. localTarget.x = this._minYawSin * xzlen;
  84156. newYaw = this._minYaw;
  84157. }
  84158. }
  84159. else {
  84160. if (yaw > this._maxYaw) {
  84161. localTarget.z = this._maxYawCos * xzlen;
  84162. localTarget.x = this._maxYawSin * xzlen;
  84163. newYaw = this._maxYaw;
  84164. }
  84165. else if (yaw < this._minYaw) {
  84166. localTarget.z = this._minYawCos * xzlen;
  84167. localTarget.x = this._minYawSin * xzlen;
  84168. newYaw = this._minYaw;
  84169. }
  84170. }
  84171. }
  84172. if (this._slerping && this._yawRange > Math.PI) {
  84173. //are we going to be crossing into the min/max region?
  84174. var boneFwd = BoneLookController._tmpVecs[8];
  84175. boneFwd.copyFrom(BABYLON.Axis.Z);
  84176. if (this._transformYawPitch) {
  84177. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  84178. }
  84179. var boneRotMat = BoneLookController._tmpMats[4];
  84180. this._boneQuat.toRotationMatrix(boneRotMat);
  84181. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  84182. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  84183. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  84184. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  84185. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  84186. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  84187. if (angBtwTar > angBtwMidYaw) {
  84188. if (xzlen == null) {
  84189. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84190. }
  84191. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  84192. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  84193. if (angBtwMin < angBtwMax) {
  84194. newYaw = boneYaw + Math.PI * .75;
  84195. localTarget.z = Math.cos(newYaw) * xzlen;
  84196. localTarget.x = Math.sin(newYaw) * xzlen;
  84197. }
  84198. else {
  84199. newYaw = boneYaw - Math.PI * .75;
  84200. localTarget.z = Math.cos(newYaw) * xzlen;
  84201. localTarget.x = Math.sin(newYaw) * xzlen;
  84202. }
  84203. }
  84204. }
  84205. if (yaw != newYaw) {
  84206. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  84207. localTarget.addInPlace(bonePos);
  84208. target = localTarget;
  84209. }
  84210. }
  84211. }
  84212. var zaxis = BoneLookController._tmpVecs[5];
  84213. var xaxis = BoneLookController._tmpVecs[6];
  84214. var yaxis = BoneLookController._tmpVecs[7];
  84215. var _tmpQuat = BoneLookController._tmpQuat;
  84216. target.subtractToRef(bonePos, zaxis);
  84217. zaxis.normalize();
  84218. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  84219. xaxis.normalize();
  84220. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  84221. yaxis.normalize();
  84222. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  84223. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  84224. return;
  84225. }
  84226. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  84227. return;
  84228. }
  84229. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  84230. return;
  84231. }
  84232. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  84233. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  84234. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  84235. }
  84236. if (this.slerpAmount < 1) {
  84237. if (!this._slerping) {
  84238. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  84239. }
  84240. if (this._transformYawPitch) {
  84241. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  84242. }
  84243. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  84244. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  84245. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  84246. this._slerping = true;
  84247. }
  84248. else {
  84249. if (this._transformYawPitch) {
  84250. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  84251. }
  84252. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  84253. this._slerping = false;
  84254. }
  84255. };
  84256. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  84257. var angDiff = ang2 - ang1;
  84258. angDiff %= Math.PI * 2;
  84259. if (angDiff > Math.PI) {
  84260. angDiff -= Math.PI * 2;
  84261. }
  84262. else if (angDiff < -Math.PI) {
  84263. angDiff += Math.PI * 2;
  84264. }
  84265. return angDiff;
  84266. };
  84267. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  84268. ang1 %= (2 * Math.PI);
  84269. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  84270. ang2 %= (2 * Math.PI);
  84271. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  84272. var ab = 0;
  84273. if (ang1 < ang2) {
  84274. ab = ang2 - ang1;
  84275. }
  84276. else {
  84277. ab = ang1 - ang2;
  84278. }
  84279. if (ab > Math.PI) {
  84280. ab = Math.PI * 2 - ab;
  84281. }
  84282. return ab;
  84283. };
  84284. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  84285. ang %= (2 * Math.PI);
  84286. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  84287. ang1 %= (2 * Math.PI);
  84288. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  84289. ang2 %= (2 * Math.PI);
  84290. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  84291. if (ang1 < ang2) {
  84292. if (ang > ang1 && ang < ang2) {
  84293. return true;
  84294. }
  84295. }
  84296. else {
  84297. if (ang > ang2 && ang < ang1) {
  84298. return true;
  84299. }
  84300. }
  84301. return false;
  84302. };
  84303. 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()];
  84304. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  84305. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  84306. return BoneLookController;
  84307. }());
  84308. BABYLON.BoneLookController = BoneLookController;
  84309. })(BABYLON || (BABYLON = {}));
  84310. //# sourceMappingURL=babylon.boneLookController.js.map
  84311. var BABYLON;
  84312. (function (BABYLON) {
  84313. /**
  84314. * Class used to handle skinning animations
  84315. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  84316. */
  84317. var Skeleton = /** @class */ (function () {
  84318. /**
  84319. * Creates a new skeleton
  84320. * @param name defines the skeleton name
  84321. * @param id defines the skeleton Id
  84322. * @param scene defines the hosting scene
  84323. */
  84324. function Skeleton(
  84325. /** defines the skeleton name */
  84326. name,
  84327. /** defines the skeleton Id */
  84328. id, scene) {
  84329. this.name = name;
  84330. this.id = id;
  84331. /**
  84332. * Gets the list of child bones
  84333. */
  84334. this.bones = new Array();
  84335. /**
  84336. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  84337. */
  84338. this.needInitialSkinMatrix = false;
  84339. this._isDirty = true;
  84340. this._meshesWithPoseMatrix = new Array();
  84341. this._identity = BABYLON.Matrix.Identity();
  84342. this._ranges = {};
  84343. this._lastAbsoluteTransformsUpdateId = -1;
  84344. /**
  84345. * Specifies if the skeleton should be serialized
  84346. */
  84347. this.doNotSerialize = false;
  84348. this._animationPropertiesOverride = null;
  84349. // Events
  84350. /**
  84351. * An observable triggered before computing the skeleton's matrices
  84352. */
  84353. this.onBeforeComputeObservable = new BABYLON.Observable();
  84354. this.bones = [];
  84355. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84356. scene.skeletons.push(this);
  84357. //make sure it will recalculate the matrix next time prepare is called.
  84358. this._isDirty = true;
  84359. }
  84360. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  84361. /**
  84362. * Gets or sets the animation properties override
  84363. */
  84364. get: function () {
  84365. if (!this._animationPropertiesOverride) {
  84366. return this._scene.animationPropertiesOverride;
  84367. }
  84368. return this._animationPropertiesOverride;
  84369. },
  84370. set: function (value) {
  84371. this._animationPropertiesOverride = value;
  84372. },
  84373. enumerable: true,
  84374. configurable: true
  84375. });
  84376. // Members
  84377. /**
  84378. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  84379. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  84380. * @returns a Float32Array containing matrices data
  84381. */
  84382. Skeleton.prototype.getTransformMatrices = function (mesh) {
  84383. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  84384. return mesh._bonesTransformMatrices;
  84385. }
  84386. if (!this._transformMatrices) {
  84387. this.prepare();
  84388. }
  84389. return this._transformMatrices;
  84390. };
  84391. /**
  84392. * Gets the current hosting scene
  84393. * @returns a scene object
  84394. */
  84395. Skeleton.prototype.getScene = function () {
  84396. return this._scene;
  84397. };
  84398. // Methods
  84399. /**
  84400. * Gets a string representing the current skeleton data
  84401. * @param fullDetails defines a boolean indicating if we want a verbose version
  84402. * @returns a string representing the current skeleton data
  84403. */
  84404. Skeleton.prototype.toString = function (fullDetails) {
  84405. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  84406. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  84407. if (fullDetails) {
  84408. ret += ", Ranges: {";
  84409. var first = true;
  84410. for (var name_1 in this._ranges) {
  84411. if (first) {
  84412. ret += ", ";
  84413. first = false;
  84414. }
  84415. ret += name_1;
  84416. }
  84417. ret += "}";
  84418. }
  84419. return ret;
  84420. };
  84421. /**
  84422. * Get bone's index searching by name
  84423. * @param name defines bone's name to search for
  84424. * @return the indice of the bone. Returns -1 if not found
  84425. */
  84426. Skeleton.prototype.getBoneIndexByName = function (name) {
  84427. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  84428. if (this.bones[boneIndex].name === name) {
  84429. return boneIndex;
  84430. }
  84431. }
  84432. return -1;
  84433. };
  84434. /**
  84435. * Creater a new animation range
  84436. * @param name defines the name of the range
  84437. * @param from defines the start key
  84438. * @param to defines the end key
  84439. */
  84440. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  84441. // check name not already in use
  84442. if (!this._ranges[name]) {
  84443. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  84444. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84445. if (this.bones[i].animations[0]) {
  84446. this.bones[i].animations[0].createRange(name, from, to);
  84447. }
  84448. }
  84449. }
  84450. };
  84451. /**
  84452. * Delete a specific animation range
  84453. * @param name defines the name of the range
  84454. * @param deleteFrames defines if frames must be removed as well
  84455. */
  84456. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  84457. if (deleteFrames === void 0) { deleteFrames = true; }
  84458. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84459. if (this.bones[i].animations[0]) {
  84460. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  84461. }
  84462. }
  84463. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  84464. };
  84465. /**
  84466. * Gets a specific animation range
  84467. * @param name defines the name of the range to look for
  84468. * @returns the requested animation range or null if not found
  84469. */
  84470. Skeleton.prototype.getAnimationRange = function (name) {
  84471. return this._ranges[name];
  84472. };
  84473. /**
  84474. * Gets the list of all animation ranges defined on this skeleton
  84475. * @returns an array
  84476. */
  84477. Skeleton.prototype.getAnimationRanges = function () {
  84478. var animationRanges = [];
  84479. var name;
  84480. var i = 0;
  84481. for (name in this._ranges) {
  84482. animationRanges[i] = this._ranges[name];
  84483. i++;
  84484. }
  84485. return animationRanges;
  84486. };
  84487. /**
  84488. * Copy animation range from a source skeleton.
  84489. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  84490. * @param source defines the source skeleton
  84491. * @param name defines the name of the range to copy
  84492. * @param rescaleAsRequired defines if rescaling must be applied if required
  84493. * @returns true if operation was successful
  84494. */
  84495. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  84496. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84497. if (this._ranges[name] || !source.getAnimationRange(name)) {
  84498. return false;
  84499. }
  84500. var ret = true;
  84501. var frameOffset = this._getHighestAnimationFrame() + 1;
  84502. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  84503. var boneDict = {};
  84504. var sourceBones = source.bones;
  84505. var nBones;
  84506. var i;
  84507. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  84508. boneDict[sourceBones[i].name] = sourceBones[i];
  84509. }
  84510. if (this.bones.length !== sourceBones.length) {
  84511. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  84512. ret = false;
  84513. }
  84514. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  84515. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  84516. var boneName = this.bones[i].name;
  84517. var sourceBone = boneDict[boneName];
  84518. if (sourceBone) {
  84519. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  84520. }
  84521. else {
  84522. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  84523. ret = false;
  84524. }
  84525. }
  84526. // do not call createAnimationRange(), since it also is done to bones, which was already done
  84527. var range = source.getAnimationRange(name);
  84528. if (range) {
  84529. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  84530. }
  84531. return ret;
  84532. };
  84533. /**
  84534. * Forces the skeleton to go to rest pose
  84535. */
  84536. Skeleton.prototype.returnToRest = function () {
  84537. for (var index = 0; index < this.bones.length; index++) {
  84538. this.bones[index].returnToRest();
  84539. }
  84540. };
  84541. Skeleton.prototype._getHighestAnimationFrame = function () {
  84542. var ret = 0;
  84543. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84544. if (this.bones[i].animations[0]) {
  84545. var highest = this.bones[i].animations[0].getHighestFrame();
  84546. if (ret < highest) {
  84547. ret = highest;
  84548. }
  84549. }
  84550. }
  84551. return ret;
  84552. };
  84553. /**
  84554. * Begin a specific animation range
  84555. * @param name defines the name of the range to start
  84556. * @param loop defines if looping must be turned on (false by default)
  84557. * @param speedRatio defines the speed ratio to apply (1 by default)
  84558. * @param onAnimationEnd defines a callback which will be called when animation will end
  84559. * @returns a new animatable
  84560. */
  84561. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  84562. var range = this.getAnimationRange(name);
  84563. if (!range) {
  84564. return null;
  84565. }
  84566. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  84567. };
  84568. /** @hidden */
  84569. Skeleton.prototype._markAsDirty = function () {
  84570. this._isDirty = true;
  84571. };
  84572. /** @hidden */
  84573. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  84574. this._meshesWithPoseMatrix.push(mesh);
  84575. };
  84576. /** @hidden */
  84577. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  84578. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  84579. if (index > -1) {
  84580. this._meshesWithPoseMatrix.splice(index, 1);
  84581. }
  84582. };
  84583. /** @hidden */
  84584. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  84585. this.onBeforeComputeObservable.notifyObservers(this);
  84586. for (var index = 0; index < this.bones.length; index++) {
  84587. var bone = this.bones[index];
  84588. var parentBone = bone.getParent();
  84589. if (parentBone) {
  84590. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  84591. }
  84592. else {
  84593. if (initialSkinMatrix) {
  84594. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  84595. }
  84596. else {
  84597. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  84598. }
  84599. }
  84600. if (bone._index !== -1) {
  84601. var mappedIndex = bone._index === null ? index : bone._index;
  84602. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  84603. }
  84604. }
  84605. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  84606. };
  84607. /**
  84608. * Build all resources required to render a skeleton
  84609. */
  84610. Skeleton.prototype.prepare = function () {
  84611. if (!this._isDirty) {
  84612. return;
  84613. }
  84614. if (this.needInitialSkinMatrix) {
  84615. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  84616. var mesh = this._meshesWithPoseMatrix[index];
  84617. var poseMatrix = mesh.getPoseMatrix();
  84618. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  84619. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  84620. }
  84621. if (this._synchronizedWithMesh !== mesh) {
  84622. this._synchronizedWithMesh = mesh;
  84623. // Prepare bones
  84624. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  84625. var bone = this.bones[boneIndex];
  84626. if (!bone.getParent()) {
  84627. var matrix = bone.getBaseMatrix();
  84628. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  84629. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  84630. }
  84631. }
  84632. }
  84633. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  84634. }
  84635. }
  84636. else {
  84637. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  84638. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  84639. }
  84640. this._computeTransformMatrices(this._transformMatrices, null);
  84641. }
  84642. this._isDirty = false;
  84643. this._scene._activeBones.addCount(this.bones.length, false);
  84644. };
  84645. /**
  84646. * Gets the list of animatables currently running for this skeleton
  84647. * @returns an array of animatables
  84648. */
  84649. Skeleton.prototype.getAnimatables = function () {
  84650. if (!this._animatables || this._animatables.length !== this.bones.length) {
  84651. this._animatables = [];
  84652. for (var index = 0; index < this.bones.length; index++) {
  84653. this._animatables.push(this.bones[index]);
  84654. }
  84655. }
  84656. return this._animatables;
  84657. };
  84658. /**
  84659. * Clone the current skeleton
  84660. * @param name defines the name of the new skeleton
  84661. * @param id defines the id of the enw skeleton
  84662. * @returns the new skeleton
  84663. */
  84664. Skeleton.prototype.clone = function (name, id) {
  84665. var result = new Skeleton(name, id || name, this._scene);
  84666. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  84667. for (var index = 0; index < this.bones.length; index++) {
  84668. var source = this.bones[index];
  84669. var parentBone = null;
  84670. var parent_1 = source.getParent();
  84671. if (parent_1) {
  84672. var parentIndex = this.bones.indexOf(parent_1);
  84673. parentBone = result.bones[parentIndex];
  84674. }
  84675. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  84676. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  84677. }
  84678. if (this._ranges) {
  84679. result._ranges = {};
  84680. for (var rangeName in this._ranges) {
  84681. var range = this._ranges[rangeName];
  84682. if (range) {
  84683. result._ranges[rangeName] = range.clone();
  84684. }
  84685. }
  84686. }
  84687. this._isDirty = true;
  84688. return result;
  84689. };
  84690. /**
  84691. * Enable animation blending for this skeleton
  84692. * @param blendingSpeed defines the blending speed to apply
  84693. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  84694. */
  84695. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  84696. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  84697. this.bones.forEach(function (bone) {
  84698. bone.animations.forEach(function (animation) {
  84699. animation.enableBlending = true;
  84700. animation.blendingSpeed = blendingSpeed;
  84701. });
  84702. });
  84703. };
  84704. /**
  84705. * Releases all resources associated with the current skeleton
  84706. */
  84707. Skeleton.prototype.dispose = function () {
  84708. this._meshesWithPoseMatrix = [];
  84709. // Animations
  84710. this.getScene().stopAnimation(this);
  84711. // Remove from scene
  84712. this.getScene().removeSkeleton(this);
  84713. };
  84714. /**
  84715. * Serialize the skeleton in a JSON object
  84716. * @returns a JSON object
  84717. */
  84718. Skeleton.prototype.serialize = function () {
  84719. var serializationObject = {};
  84720. serializationObject.name = this.name;
  84721. serializationObject.id = this.id;
  84722. if (this.dimensionsAtRest) {
  84723. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  84724. }
  84725. serializationObject.bones = [];
  84726. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  84727. for (var index = 0; index < this.bones.length; index++) {
  84728. var bone = this.bones[index];
  84729. var parent_2 = bone.getParent();
  84730. var serializedBone = {
  84731. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  84732. name: bone.name,
  84733. matrix: bone.getBaseMatrix().toArray(),
  84734. rest: bone.getRestPose().toArray()
  84735. };
  84736. serializationObject.bones.push(serializedBone);
  84737. if (bone.length) {
  84738. serializedBone.length = bone.length;
  84739. }
  84740. if (bone.metadata) {
  84741. serializedBone.metadata = bone.metadata;
  84742. }
  84743. if (bone.animations && bone.animations.length > 0) {
  84744. serializedBone.animation = bone.animations[0].serialize();
  84745. }
  84746. serializationObject.ranges = [];
  84747. for (var name in this._ranges) {
  84748. var source = this._ranges[name];
  84749. if (!source) {
  84750. continue;
  84751. }
  84752. var range = {};
  84753. range.name = name;
  84754. range.from = source.from;
  84755. range.to = source.to;
  84756. serializationObject.ranges.push(range);
  84757. }
  84758. }
  84759. return serializationObject;
  84760. };
  84761. /**
  84762. * Creates a new skeleton from serialized data
  84763. * @param parsedSkeleton defines the serialized data
  84764. * @param scene defines the hosting scene
  84765. * @returns a new skeleton
  84766. */
  84767. Skeleton.Parse = function (parsedSkeleton, scene) {
  84768. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  84769. if (parsedSkeleton.dimensionsAtRest) {
  84770. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  84771. }
  84772. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  84773. var index;
  84774. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  84775. var parsedBone = parsedSkeleton.bones[index];
  84776. var parentBone = null;
  84777. if (parsedBone.parentBoneIndex > -1) {
  84778. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  84779. }
  84780. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  84781. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  84782. if (parsedBone.length) {
  84783. bone.length = parsedBone.length;
  84784. }
  84785. if (parsedBone.metadata) {
  84786. bone.metadata = parsedBone.metadata;
  84787. }
  84788. if (parsedBone.animation) {
  84789. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  84790. }
  84791. }
  84792. // placed after bones, so createAnimationRange can cascade down
  84793. if (parsedSkeleton.ranges) {
  84794. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  84795. var data = parsedSkeleton.ranges[index];
  84796. skeleton.createAnimationRange(data.name, data.from, data.to);
  84797. }
  84798. }
  84799. return skeleton;
  84800. };
  84801. /**
  84802. * Compute all node absolute transforms
  84803. * @param forceUpdate defines if computation must be done even if cache is up to date
  84804. */
  84805. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  84806. if (forceUpdate === void 0) { forceUpdate = false; }
  84807. var renderId = this._scene.getRenderId();
  84808. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  84809. this.bones[0].computeAbsoluteTransforms();
  84810. this._lastAbsoluteTransformsUpdateId = renderId;
  84811. }
  84812. };
  84813. /**
  84814. * Gets the root pose matrix
  84815. * @returns a matrix
  84816. */
  84817. Skeleton.prototype.getPoseMatrix = function () {
  84818. var poseMatrix = null;
  84819. if (this._meshesWithPoseMatrix.length > 0) {
  84820. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  84821. }
  84822. return poseMatrix;
  84823. };
  84824. /**
  84825. * Sorts bones per internal index
  84826. */
  84827. Skeleton.prototype.sortBones = function () {
  84828. var bones = new Array();
  84829. var visited = new Array(this.bones.length);
  84830. for (var index = 0; index < this.bones.length; index++) {
  84831. this._sortBones(index, bones, visited);
  84832. }
  84833. this.bones = bones;
  84834. };
  84835. Skeleton.prototype._sortBones = function (index, bones, visited) {
  84836. if (visited[index]) {
  84837. return;
  84838. }
  84839. visited[index] = true;
  84840. var bone = this.bones[index];
  84841. if (bone._index === undefined) {
  84842. bone._index = index;
  84843. }
  84844. var parentBone = bone.getParent();
  84845. if (parentBone) {
  84846. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  84847. }
  84848. bones.push(bone);
  84849. };
  84850. return Skeleton;
  84851. }());
  84852. BABYLON.Skeleton = Skeleton;
  84853. })(BABYLON || (BABYLON = {}));
  84854. //# sourceMappingURL=babylon.skeleton.js.map
  84855. var BABYLON;
  84856. (function (BABYLON) {
  84857. ;
  84858. /**
  84859. * This groups tools to convert HDR texture to native colors array.
  84860. */
  84861. var HDRTools = /** @class */ (function () {
  84862. function HDRTools() {
  84863. }
  84864. HDRTools.Ldexp = function (mantissa, exponent) {
  84865. if (exponent > 1023) {
  84866. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  84867. }
  84868. if (exponent < -1074) {
  84869. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  84870. }
  84871. return mantissa * Math.pow(2, exponent);
  84872. };
  84873. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  84874. if (exponent > 0) { /*nonzero pixel*/
  84875. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  84876. float32array[index + 0] = red * exponent;
  84877. float32array[index + 1] = green * exponent;
  84878. float32array[index + 2] = blue * exponent;
  84879. }
  84880. else {
  84881. float32array[index + 0] = 0;
  84882. float32array[index + 1] = 0;
  84883. float32array[index + 2] = 0;
  84884. }
  84885. };
  84886. HDRTools.readStringLine = function (uint8array, startIndex) {
  84887. var line = "";
  84888. var character = "";
  84889. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  84890. character = String.fromCharCode(uint8array[i]);
  84891. if (character == "\n") {
  84892. break;
  84893. }
  84894. line += character;
  84895. }
  84896. return line;
  84897. };
  84898. /**
  84899. * Reads header information from an RGBE texture stored in a native array.
  84900. * More information on this format are available here:
  84901. * https://en.wikipedia.org/wiki/RGBE_image_format
  84902. *
  84903. * @param uint8array The binary file stored in native array.
  84904. * @return The header information.
  84905. */
  84906. HDRTools.RGBE_ReadHeader = function (uint8array) {
  84907. var height = 0;
  84908. var width = 0;
  84909. var line = this.readStringLine(uint8array, 0);
  84910. if (line[0] != '#' || line[1] != '?') {
  84911. throw "Bad HDR Format.";
  84912. }
  84913. var endOfHeader = false;
  84914. var findFormat = false;
  84915. var lineIndex = 0;
  84916. do {
  84917. lineIndex += (line.length + 1);
  84918. line = this.readStringLine(uint8array, lineIndex);
  84919. if (line == "FORMAT=32-bit_rle_rgbe") {
  84920. findFormat = true;
  84921. }
  84922. else if (line.length == 0) {
  84923. endOfHeader = true;
  84924. }
  84925. } while (!endOfHeader);
  84926. if (!findFormat) {
  84927. throw "HDR Bad header format, unsupported FORMAT";
  84928. }
  84929. lineIndex += (line.length + 1);
  84930. line = this.readStringLine(uint8array, lineIndex);
  84931. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  84932. var match = sizeRegexp.exec(line);
  84933. // TODO. Support +Y and -X if needed.
  84934. if (!match || match.length < 3) {
  84935. throw "HDR Bad header format, no size";
  84936. }
  84937. width = parseInt(match[2]);
  84938. height = parseInt(match[1]);
  84939. if (width < 8 || width > 0x7fff) {
  84940. throw "HDR Bad header format, unsupported size";
  84941. }
  84942. lineIndex += (line.length + 1);
  84943. return {
  84944. height: height,
  84945. width: width,
  84946. dataPosition: lineIndex
  84947. };
  84948. };
  84949. /**
  84950. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  84951. * This RGBE texture needs to store the information as a panorama.
  84952. *
  84953. * More information on this format are available here:
  84954. * https://en.wikipedia.org/wiki/RGBE_image_format
  84955. *
  84956. * @param buffer The binary file stored in an array buffer.
  84957. * @param size The expected size of the extracted cubemap.
  84958. * @return The Cube Map information.
  84959. */
  84960. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  84961. var uint8array = new Uint8Array(buffer);
  84962. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  84963. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  84964. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  84965. return cubeMapData;
  84966. };
  84967. /**
  84968. * Returns the pixels data extracted from an RGBE texture.
  84969. * This pixels will be stored left to right up to down in the R G B order in one array.
  84970. *
  84971. * More information on this format are available here:
  84972. * https://en.wikipedia.org/wiki/RGBE_image_format
  84973. *
  84974. * @param uint8array The binary file stored in an array buffer.
  84975. * @param hdrInfo The header information of the file.
  84976. * @return The pixels data in RGB right to left up to down order.
  84977. */
  84978. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  84979. // Keep for multi format supports.
  84980. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  84981. };
  84982. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  84983. var num_scanlines = hdrInfo.height;
  84984. var scanline_width = hdrInfo.width;
  84985. var a, b, c, d, count;
  84986. var dataIndex = hdrInfo.dataPosition;
  84987. var index = 0, endIndex = 0, i = 0;
  84988. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  84989. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  84990. // 3 channels of 4 bytes per pixel in float.
  84991. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  84992. var resultArray = new Float32Array(resultBuffer);
  84993. // read in each successive scanline
  84994. while (num_scanlines > 0) {
  84995. a = uint8array[dataIndex++];
  84996. b = uint8array[dataIndex++];
  84997. c = uint8array[dataIndex++];
  84998. d = uint8array[dataIndex++];
  84999. if (a != 2 || b != 2 || (c & 0x80)) {
  85000. // this file is not run length encoded
  85001. throw "HDR Bad header format, not RLE";
  85002. }
  85003. if (((c << 8) | d) != scanline_width) {
  85004. throw "HDR Bad header format, wrong scan line width";
  85005. }
  85006. index = 0;
  85007. // read each of the four channels for the scanline into the buffer
  85008. for (i = 0; i < 4; i++) {
  85009. endIndex = (i + 1) * scanline_width;
  85010. while (index < endIndex) {
  85011. a = uint8array[dataIndex++];
  85012. b = uint8array[dataIndex++];
  85013. if (a > 128) {
  85014. // a run of the same value
  85015. count = a - 128;
  85016. if ((count == 0) || (count > endIndex - index)) {
  85017. throw "HDR Bad Format, bad scanline data (run)";
  85018. }
  85019. while (count-- > 0) {
  85020. scanLineArray[index++] = b;
  85021. }
  85022. }
  85023. else {
  85024. // a non-run
  85025. count = a;
  85026. if ((count == 0) || (count > endIndex - index)) {
  85027. throw "HDR Bad Format, bad scanline data (non-run)";
  85028. }
  85029. scanLineArray[index++] = b;
  85030. if (--count > 0) {
  85031. for (var j = 0; j < count; j++) {
  85032. scanLineArray[index++] = uint8array[dataIndex++];
  85033. }
  85034. }
  85035. }
  85036. }
  85037. }
  85038. // now convert data from buffer into floats
  85039. for (i = 0; i < scanline_width; i++) {
  85040. a = scanLineArray[i];
  85041. b = scanLineArray[i + scanline_width];
  85042. c = scanLineArray[i + 2 * scanline_width];
  85043. d = scanLineArray[i + 3 * scanline_width];
  85044. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  85045. }
  85046. num_scanlines--;
  85047. }
  85048. return resultArray;
  85049. };
  85050. return HDRTools;
  85051. }());
  85052. BABYLON.HDRTools = HDRTools;
  85053. })(BABYLON || (BABYLON = {}));
  85054. //# sourceMappingURL=babylon.hdr.js.map
  85055. var BABYLON;
  85056. (function (BABYLON) {
  85057. /**
  85058. * This represents a texture coming from an HDR input.
  85059. *
  85060. * The only supported format is currently panorama picture stored in RGBE format.
  85061. * Example of such files can be found on HDRLib: http://hdrlib.com/
  85062. */
  85063. var HDRCubeTexture = /** @class */ (function (_super) {
  85064. __extends(HDRCubeTexture, _super);
  85065. /**
  85066. * Instantiates an HDRTexture from the following parameters.
  85067. *
  85068. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  85069. * @param scene The scene the texture will be used in
  85070. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  85071. * @param noMipmap Forces to not generate the mipmap if true
  85072. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  85073. * @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)
  85074. * @param reserved Reserved flag for internal use.
  85075. */
  85076. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  85077. if (noMipmap === void 0) { noMipmap = false; }
  85078. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85079. if (gammaSpace === void 0) { gammaSpace = false; }
  85080. if (reserved === void 0) { reserved = false; }
  85081. if (onLoad === void 0) { onLoad = null; }
  85082. if (onError === void 0) { onError = null; }
  85083. var _this = _super.call(this, scene) || this;
  85084. _this._generateHarmonics = true;
  85085. _this._onLoad = null;
  85086. _this._onError = null;
  85087. /**
  85088. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  85089. */
  85090. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  85091. _this._isBlocking = true;
  85092. _this._rotationY = 0;
  85093. /**
  85094. * Gets or sets the center of the bounding box associated with the cube texture
  85095. * It must define where the camera used to render the texture was set
  85096. */
  85097. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  85098. if (!url) {
  85099. return _this;
  85100. }
  85101. _this.name = url;
  85102. _this.url = url;
  85103. _this.hasAlpha = false;
  85104. _this.isCube = true;
  85105. _this._textureMatrix = BABYLON.Matrix.Identity();
  85106. _this._onLoad = onLoad;
  85107. _this._onError = onError;
  85108. _this.gammaSpace = gammaSpace;
  85109. _this._noMipmap = noMipmap;
  85110. _this._size = size;
  85111. _this._texture = _this._getFromCache(url, _this._noMipmap);
  85112. if (!_this._texture) {
  85113. if (!scene.useDelayedTextureLoading) {
  85114. _this.loadTexture();
  85115. }
  85116. else {
  85117. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  85118. }
  85119. }
  85120. return _this;
  85121. }
  85122. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  85123. /**
  85124. * Gets wether or not the texture is blocking during loading.
  85125. */
  85126. get: function () {
  85127. return this._isBlocking;
  85128. },
  85129. /**
  85130. * Sets wether or not the texture is blocking during loading.
  85131. */
  85132. set: function (value) {
  85133. this._isBlocking = value;
  85134. },
  85135. enumerable: true,
  85136. configurable: true
  85137. });
  85138. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  85139. /**
  85140. * Gets texture matrix rotation angle around Y axis radians.
  85141. */
  85142. get: function () {
  85143. return this._rotationY;
  85144. },
  85145. /**
  85146. * Sets texture matrix rotation angle around Y axis in radians.
  85147. */
  85148. set: function (value) {
  85149. this._rotationY = value;
  85150. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  85151. },
  85152. enumerable: true,
  85153. configurable: true
  85154. });
  85155. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  85156. get: function () {
  85157. return this._boundingBoxSize;
  85158. },
  85159. /**
  85160. * Gets or sets the size of the bounding box associated with the cube texture
  85161. * When defined, the cubemap will switch to local mode
  85162. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  85163. * @example https://www.babylonjs-playground.com/#RNASML
  85164. */
  85165. set: function (value) {
  85166. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  85167. return;
  85168. }
  85169. this._boundingBoxSize = value;
  85170. var scene = this.getScene();
  85171. if (scene) {
  85172. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  85173. }
  85174. },
  85175. enumerable: true,
  85176. configurable: true
  85177. });
  85178. /**
  85179. * Occurs when the file is raw .hdr file.
  85180. */
  85181. HDRCubeTexture.prototype.loadTexture = function () {
  85182. var _this = this;
  85183. var callback = function (buffer) {
  85184. _this.lodGenerationOffset = 0.0;
  85185. _this.lodGenerationScale = 0.8;
  85186. var scene = _this.getScene();
  85187. if (!scene) {
  85188. return null;
  85189. }
  85190. // Extract the raw linear data.
  85191. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  85192. // Generate harmonics if needed.
  85193. if (_this._generateHarmonics) {
  85194. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  85195. _this.sphericalPolynomial = sphericalPolynomial;
  85196. }
  85197. var results = [];
  85198. var byteArray = null;
  85199. // Push each faces.
  85200. for (var j = 0; j < 6; j++) {
  85201. // Create uintarray fallback.
  85202. if (!scene.getEngine().getCaps().textureFloat) {
  85203. // 3 channels of 1 bytes per pixel in bytes.
  85204. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  85205. byteArray = new Uint8Array(byteBuffer);
  85206. }
  85207. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  85208. // If special cases.
  85209. if (_this.gammaSpace || byteArray) {
  85210. for (var i = 0; i < _this._size * _this._size; i++) {
  85211. // Put in gamma space if requested.
  85212. if (_this.gammaSpace) {
  85213. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  85214. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  85215. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  85216. }
  85217. // Convert to int texture for fallback.
  85218. if (byteArray) {
  85219. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  85220. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  85221. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  85222. // May use luminance instead if the result is not accurate.
  85223. var max = Math.max(Math.max(r, g), b);
  85224. if (max > 255) {
  85225. var scale = 255 / max;
  85226. r *= scale;
  85227. g *= scale;
  85228. b *= scale;
  85229. }
  85230. byteArray[(i * 3) + 0] = r;
  85231. byteArray[(i * 3) + 1] = g;
  85232. byteArray[(i * 3) + 2] = b;
  85233. }
  85234. }
  85235. }
  85236. if (byteArray) {
  85237. results.push(byteArray);
  85238. }
  85239. else {
  85240. results.push(dataFace);
  85241. }
  85242. }
  85243. return results;
  85244. };
  85245. var scene = this.getScene();
  85246. if (scene) {
  85247. 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);
  85248. }
  85249. };
  85250. HDRCubeTexture.prototype.clone = function () {
  85251. var scene = this.getScene();
  85252. if (!scene) {
  85253. return this;
  85254. }
  85255. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  85256. // Base texture
  85257. newTexture.level = this.level;
  85258. newTexture.wrapU = this.wrapU;
  85259. newTexture.wrapV = this.wrapV;
  85260. newTexture.coordinatesIndex = this.coordinatesIndex;
  85261. newTexture.coordinatesMode = this.coordinatesMode;
  85262. return newTexture;
  85263. };
  85264. // Methods
  85265. HDRCubeTexture.prototype.delayLoad = function () {
  85266. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  85267. return;
  85268. }
  85269. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  85270. this._texture = this._getFromCache(this.url, this._noMipmap);
  85271. if (!this._texture) {
  85272. this.loadTexture();
  85273. }
  85274. };
  85275. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  85276. return this._textureMatrix;
  85277. };
  85278. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  85279. this._textureMatrix = value;
  85280. };
  85281. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  85282. var texture = null;
  85283. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  85284. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  85285. texture.name = parsedTexture.name;
  85286. texture.hasAlpha = parsedTexture.hasAlpha;
  85287. texture.level = parsedTexture.level;
  85288. texture.coordinatesMode = parsedTexture.coordinatesMode;
  85289. texture.isBlocking = parsedTexture.isBlocking;
  85290. }
  85291. if (texture) {
  85292. if (parsedTexture.boundingBoxPosition) {
  85293. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  85294. }
  85295. if (parsedTexture.boundingBoxSize) {
  85296. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  85297. }
  85298. if (parsedTexture.rotationY) {
  85299. texture.rotationY = parsedTexture.rotationY;
  85300. }
  85301. }
  85302. return texture;
  85303. };
  85304. HDRCubeTexture.prototype.serialize = function () {
  85305. if (!this.name) {
  85306. return null;
  85307. }
  85308. var serializationObject = {};
  85309. serializationObject.name = this.name;
  85310. serializationObject.hasAlpha = this.hasAlpha;
  85311. serializationObject.isCube = true;
  85312. serializationObject.level = this.level;
  85313. serializationObject.size = this._size;
  85314. serializationObject.coordinatesMode = this.coordinatesMode;
  85315. serializationObject.useInGammaSpace = this.gammaSpace;
  85316. serializationObject.generateHarmonics = this._generateHarmonics;
  85317. serializationObject.customType = "BABYLON.HDRCubeTexture";
  85318. serializationObject.noMipmap = this._noMipmap;
  85319. serializationObject.isBlocking = this._isBlocking;
  85320. serializationObject.rotationY = this._rotationY;
  85321. return serializationObject;
  85322. };
  85323. HDRCubeTexture._facesMapping = [
  85324. "right",
  85325. "left",
  85326. "up",
  85327. "down",
  85328. "front",
  85329. "back"
  85330. ];
  85331. return HDRCubeTexture;
  85332. }(BABYLON.BaseTexture));
  85333. BABYLON.HDRCubeTexture = HDRCubeTexture;
  85334. })(BABYLON || (BABYLON = {}));
  85335. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  85336. var BABYLON;
  85337. (function (BABYLON) {
  85338. /**
  85339. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  85340. */
  85341. var PanoramaToCubeMapTools = /** @class */ (function () {
  85342. function PanoramaToCubeMapTools() {
  85343. }
  85344. /**
  85345. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  85346. *
  85347. * @param float32Array The source data.
  85348. * @param inputWidth The width of the input panorama.
  85349. * @param inputhHeight The height of the input panorama.
  85350. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  85351. * @return The cubemap data
  85352. */
  85353. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  85354. if (!float32Array) {
  85355. throw "ConvertPanoramaToCubemap: input cannot be null";
  85356. }
  85357. if (float32Array.length != inputWidth * inputHeight * 3) {
  85358. throw "ConvertPanoramaToCubemap: input size is wrong";
  85359. }
  85360. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  85361. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  85362. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  85363. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  85364. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  85365. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  85366. return {
  85367. front: textureFront,
  85368. back: textureBack,
  85369. left: textureLeft,
  85370. right: textureRight,
  85371. up: textureUp,
  85372. down: textureDown,
  85373. size: size,
  85374. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85375. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  85376. gammaSpace: false,
  85377. };
  85378. };
  85379. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  85380. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  85381. var textureArray = new Float32Array(buffer);
  85382. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  85383. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  85384. var dy = 1 / texSize;
  85385. var fy = 0;
  85386. for (var y = 0; y < texSize; y++) {
  85387. var xv1 = faceData[0];
  85388. var xv2 = faceData[2];
  85389. for (var x = 0; x < texSize; x++) {
  85390. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  85391. v.normalize();
  85392. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  85393. // 3 channels per pixels
  85394. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  85395. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  85396. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  85397. xv1 = xv1.add(rotDX1);
  85398. xv2 = xv2.add(rotDX2);
  85399. }
  85400. fy += dy;
  85401. }
  85402. return textureArray;
  85403. };
  85404. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  85405. var theta = Math.atan2(vDir.z, vDir.x);
  85406. var phi = Math.acos(vDir.y);
  85407. while (theta < -Math.PI)
  85408. theta += 2 * Math.PI;
  85409. while (theta > Math.PI)
  85410. theta -= 2 * Math.PI;
  85411. var dx = theta / Math.PI;
  85412. var dy = phi / Math.PI;
  85413. // recenter.
  85414. dx = dx * 0.5 + 0.5;
  85415. var px = Math.round(dx * inputWidth);
  85416. if (px < 0)
  85417. px = 0;
  85418. else if (px >= inputWidth)
  85419. px = inputWidth - 1;
  85420. var py = Math.round(dy * inputHeight);
  85421. if (py < 0)
  85422. py = 0;
  85423. else if (py >= inputHeight)
  85424. py = inputHeight - 1;
  85425. var inputY = (inputHeight - py - 1);
  85426. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  85427. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  85428. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  85429. return {
  85430. r: r,
  85431. g: g,
  85432. b: b
  85433. };
  85434. };
  85435. PanoramaToCubeMapTools.FACE_FRONT = [
  85436. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85437. new BABYLON.Vector3(1.0, -1.0, -1.0),
  85438. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  85439. new BABYLON.Vector3(1.0, 1.0, -1.0)
  85440. ];
  85441. PanoramaToCubeMapTools.FACE_BACK = [
  85442. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85443. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85444. new BABYLON.Vector3(1.0, 1.0, 1.0),
  85445. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  85446. ];
  85447. PanoramaToCubeMapTools.FACE_RIGHT = [
  85448. new BABYLON.Vector3(1.0, -1.0, -1.0),
  85449. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85450. new BABYLON.Vector3(1.0, 1.0, -1.0),
  85451. new BABYLON.Vector3(1.0, 1.0, 1.0)
  85452. ];
  85453. PanoramaToCubeMapTools.FACE_LEFT = [
  85454. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85455. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85456. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  85457. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  85458. ];
  85459. PanoramaToCubeMapTools.FACE_DOWN = [
  85460. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  85461. new BABYLON.Vector3(1.0, 1.0, -1.0),
  85462. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  85463. new BABYLON.Vector3(1.0, 1.0, 1.0)
  85464. ];
  85465. PanoramaToCubeMapTools.FACE_UP = [
  85466. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85467. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85468. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85469. new BABYLON.Vector3(1.0, -1.0, -1.0)
  85470. ];
  85471. return PanoramaToCubeMapTools;
  85472. }());
  85473. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  85474. })(BABYLON || (BABYLON = {}));
  85475. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  85476. var BABYLON;
  85477. (function (BABYLON) {
  85478. var IndexedVector2 = /** @class */ (function (_super) {
  85479. __extends(IndexedVector2, _super);
  85480. function IndexedVector2(original, index) {
  85481. var _this = _super.call(this, original.x, original.y) || this;
  85482. _this.index = index;
  85483. return _this;
  85484. }
  85485. return IndexedVector2;
  85486. }(BABYLON.Vector2));
  85487. var PolygonPoints = /** @class */ (function () {
  85488. function PolygonPoints() {
  85489. this.elements = new Array();
  85490. }
  85491. PolygonPoints.prototype.add = function (originalPoints) {
  85492. var _this = this;
  85493. var result = new Array();
  85494. originalPoints.forEach(function (point) {
  85495. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  85496. var newPoint = new IndexedVector2(point, _this.elements.length);
  85497. result.push(newPoint);
  85498. _this.elements.push(newPoint);
  85499. }
  85500. });
  85501. return result;
  85502. };
  85503. PolygonPoints.prototype.computeBounds = function () {
  85504. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  85505. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  85506. this.elements.forEach(function (point) {
  85507. // x
  85508. if (point.x < lmin.x) {
  85509. lmin.x = point.x;
  85510. }
  85511. else if (point.x > lmax.x) {
  85512. lmax.x = point.x;
  85513. }
  85514. // y
  85515. if (point.y < lmin.y) {
  85516. lmin.y = point.y;
  85517. }
  85518. else if (point.y > lmax.y) {
  85519. lmax.y = point.y;
  85520. }
  85521. });
  85522. return {
  85523. min: lmin,
  85524. max: lmax,
  85525. width: lmax.x - lmin.x,
  85526. height: lmax.y - lmin.y
  85527. };
  85528. };
  85529. return PolygonPoints;
  85530. }());
  85531. var Polygon = /** @class */ (function () {
  85532. function Polygon() {
  85533. }
  85534. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  85535. return [
  85536. new BABYLON.Vector2(xmin, ymin),
  85537. new BABYLON.Vector2(xmax, ymin),
  85538. new BABYLON.Vector2(xmax, ymax),
  85539. new BABYLON.Vector2(xmin, ymax)
  85540. ];
  85541. };
  85542. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  85543. if (cx === void 0) { cx = 0; }
  85544. if (cy === void 0) { cy = 0; }
  85545. if (numberOfSides === void 0) { numberOfSides = 32; }
  85546. var result = new Array();
  85547. var angle = 0;
  85548. var increment = (Math.PI * 2) / numberOfSides;
  85549. for (var i = 0; i < numberOfSides; i++) {
  85550. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  85551. angle -= increment;
  85552. }
  85553. return result;
  85554. };
  85555. Polygon.Parse = function (input) {
  85556. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  85557. var i, result = [];
  85558. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  85559. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  85560. }
  85561. return result;
  85562. };
  85563. Polygon.StartingAt = function (x, y) {
  85564. return BABYLON.Path2.StartingAt(x, y);
  85565. };
  85566. return Polygon;
  85567. }());
  85568. BABYLON.Polygon = Polygon;
  85569. var PolygonMeshBuilder = /** @class */ (function () {
  85570. function PolygonMeshBuilder(name, contours, scene) {
  85571. this._points = new PolygonPoints();
  85572. this._outlinepoints = new PolygonPoints();
  85573. this._holes = new Array();
  85574. this._epoints = new Array();
  85575. this._eholes = new Array();
  85576. this._name = name;
  85577. this._scene = scene;
  85578. var points;
  85579. if (contours instanceof BABYLON.Path2) {
  85580. points = contours.getPoints();
  85581. }
  85582. else {
  85583. points = contours;
  85584. }
  85585. this._addToepoint(points);
  85586. this._points.add(points);
  85587. this._outlinepoints.add(points);
  85588. if (typeof earcut === 'undefined') {
  85589. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  85590. }
  85591. }
  85592. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  85593. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  85594. var p = points_1[_i];
  85595. this._epoints.push(p.x, p.y);
  85596. }
  85597. };
  85598. PolygonMeshBuilder.prototype.addHole = function (hole) {
  85599. this._points.add(hole);
  85600. var holepoints = new PolygonPoints();
  85601. holepoints.add(hole);
  85602. this._holes.push(holepoints);
  85603. this._eholes.push(this._epoints.length / 2);
  85604. this._addToepoint(hole);
  85605. return this;
  85606. };
  85607. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  85608. var _this = this;
  85609. if (updatable === void 0) { updatable = false; }
  85610. if (depth === void 0) { depth = 0; }
  85611. var result = new BABYLON.Mesh(this._name, this._scene);
  85612. var normals = new Array();
  85613. var positions = new Array();
  85614. var uvs = new Array();
  85615. var bounds = this._points.computeBounds();
  85616. this._points.elements.forEach(function (p) {
  85617. normals.push(0, 1.0, 0);
  85618. positions.push(p.x, 0, p.y);
  85619. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  85620. });
  85621. var indices = new Array();
  85622. var res = earcut(this._epoints, this._eholes, 2);
  85623. for (var i = 0; i < res.length; i++) {
  85624. indices.push(res[i]);
  85625. }
  85626. if (depth > 0) {
  85627. var positionscount = (positions.length / 3); //get the current pointcount
  85628. this._points.elements.forEach(function (p) {
  85629. normals.push(0, -1.0, 0);
  85630. positions.push(p.x, -depth, p.y);
  85631. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  85632. });
  85633. var totalCount = indices.length;
  85634. for (var i = 0; i < totalCount; i += 3) {
  85635. var i0 = indices[i + 0];
  85636. var i1 = indices[i + 1];
  85637. var i2 = indices[i + 2];
  85638. indices.push(i2 + positionscount);
  85639. indices.push(i1 + positionscount);
  85640. indices.push(i0 + positionscount);
  85641. }
  85642. //Add the sides
  85643. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  85644. this._holes.forEach(function (hole) {
  85645. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  85646. });
  85647. }
  85648. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  85649. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  85650. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  85651. result.setIndices(indices);
  85652. return result;
  85653. };
  85654. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  85655. var StartIndex = positions.length / 3;
  85656. var ulength = 0;
  85657. for (var i = 0; i < points.elements.length; i++) {
  85658. var p = points.elements[i];
  85659. var p1;
  85660. if ((i + 1) > points.elements.length - 1) {
  85661. p1 = points.elements[0];
  85662. }
  85663. else {
  85664. p1 = points.elements[i + 1];
  85665. }
  85666. positions.push(p.x, 0, p.y);
  85667. positions.push(p.x, -depth, p.y);
  85668. positions.push(p1.x, 0, p1.y);
  85669. positions.push(p1.x, -depth, p1.y);
  85670. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  85671. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  85672. var v3 = v2.subtract(v1);
  85673. var v4 = new BABYLON.Vector3(0, 1, 0);
  85674. var vn = BABYLON.Vector3.Cross(v3, v4);
  85675. vn = vn.normalize();
  85676. uvs.push(ulength / bounds.width, 0);
  85677. uvs.push(ulength / bounds.width, 1);
  85678. ulength += v3.length();
  85679. uvs.push((ulength / bounds.width), 0);
  85680. uvs.push((ulength / bounds.width), 1);
  85681. if (!flip) {
  85682. normals.push(-vn.x, -vn.y, -vn.z);
  85683. normals.push(-vn.x, -vn.y, -vn.z);
  85684. normals.push(-vn.x, -vn.y, -vn.z);
  85685. normals.push(-vn.x, -vn.y, -vn.z);
  85686. indices.push(StartIndex);
  85687. indices.push(StartIndex + 1);
  85688. indices.push(StartIndex + 2);
  85689. indices.push(StartIndex + 1);
  85690. indices.push(StartIndex + 3);
  85691. indices.push(StartIndex + 2);
  85692. }
  85693. else {
  85694. normals.push(vn.x, vn.y, vn.z);
  85695. normals.push(vn.x, vn.y, vn.z);
  85696. normals.push(vn.x, vn.y, vn.z);
  85697. normals.push(vn.x, vn.y, vn.z);
  85698. indices.push(StartIndex);
  85699. indices.push(StartIndex + 2);
  85700. indices.push(StartIndex + 1);
  85701. indices.push(StartIndex + 1);
  85702. indices.push(StartIndex + 2);
  85703. indices.push(StartIndex + 3);
  85704. }
  85705. StartIndex += 4;
  85706. }
  85707. ;
  85708. };
  85709. return PolygonMeshBuilder;
  85710. }());
  85711. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  85712. })(BABYLON || (BABYLON = {}));
  85713. //# sourceMappingURL=babylon.polygonMesh.js.map
  85714. var BABYLON;
  85715. (function (BABYLON) {
  85716. // Unique ID when we import meshes from Babylon to CSG
  85717. var currentCSGMeshId = 0;
  85718. // # class Vertex
  85719. // Represents a vertex of a polygon. Use your own vertex class instead of this
  85720. // one to provide additional features like texture coordinates and vertex
  85721. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  85722. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  85723. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  85724. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  85725. // is not used anywhere else.
  85726. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  85727. var Vertex = /** @class */ (function () {
  85728. function Vertex(pos, normal, uv) {
  85729. this.pos = pos;
  85730. this.normal = normal;
  85731. this.uv = uv;
  85732. }
  85733. Vertex.prototype.clone = function () {
  85734. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  85735. };
  85736. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  85737. // orientation of a polygon is flipped.
  85738. Vertex.prototype.flip = function () {
  85739. this.normal = this.normal.scale(-1);
  85740. };
  85741. // Create a new vertex between this vertex and `other` by linearly
  85742. // interpolating all properties using a parameter of `t`. Subclasses should
  85743. // override this to interpolate additional properties.
  85744. Vertex.prototype.interpolate = function (other, t) {
  85745. 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));
  85746. };
  85747. return Vertex;
  85748. }());
  85749. // # class Plane
  85750. // Represents a plane in 3D space.
  85751. var Plane = /** @class */ (function () {
  85752. function Plane(normal, w) {
  85753. this.normal = normal;
  85754. this.w = w;
  85755. }
  85756. Plane.FromPoints = function (a, b, c) {
  85757. var v0 = c.subtract(a);
  85758. var v1 = b.subtract(a);
  85759. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  85760. return null;
  85761. }
  85762. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  85763. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  85764. };
  85765. Plane.prototype.clone = function () {
  85766. return new Plane(this.normal.clone(), this.w);
  85767. };
  85768. Plane.prototype.flip = function () {
  85769. this.normal.scaleInPlace(-1);
  85770. this.w = -this.w;
  85771. };
  85772. // Split `polygon` by this plane if needed, then put the polygon or polygon
  85773. // fragments in the appropriate lists. Coplanar polygons go into either
  85774. // `coplanarFront` or `coplanarBack` depending on their orientation with
  85775. // respect to this plane. Polygons in front or in back of this plane go into
  85776. // either `front` or `back`.
  85777. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  85778. var COPLANAR = 0;
  85779. var FRONT = 1;
  85780. var BACK = 2;
  85781. var SPANNING = 3;
  85782. // Classify each point as well as the entire polygon into one of the above
  85783. // four classes.
  85784. var polygonType = 0;
  85785. var types = [];
  85786. var i;
  85787. var t;
  85788. for (i = 0; i < polygon.vertices.length; i++) {
  85789. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  85790. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  85791. polygonType |= type;
  85792. types.push(type);
  85793. }
  85794. // Put the polygon in the correct list, splitting it when necessary.
  85795. switch (polygonType) {
  85796. case COPLANAR:
  85797. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  85798. break;
  85799. case FRONT:
  85800. front.push(polygon);
  85801. break;
  85802. case BACK:
  85803. back.push(polygon);
  85804. break;
  85805. case SPANNING:
  85806. var f = [], b = [];
  85807. for (i = 0; i < polygon.vertices.length; i++) {
  85808. var j = (i + 1) % polygon.vertices.length;
  85809. var ti = types[i], tj = types[j];
  85810. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  85811. if (ti !== BACK)
  85812. f.push(vi);
  85813. if (ti !== FRONT)
  85814. b.push(ti !== BACK ? vi.clone() : vi);
  85815. if ((ti | tj) === SPANNING) {
  85816. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  85817. var v = vi.interpolate(vj, t);
  85818. f.push(v);
  85819. b.push(v.clone());
  85820. }
  85821. }
  85822. var poly;
  85823. if (f.length >= 3) {
  85824. poly = new Polygon(f, polygon.shared);
  85825. if (poly.plane)
  85826. front.push(poly);
  85827. }
  85828. if (b.length >= 3) {
  85829. poly = new Polygon(b, polygon.shared);
  85830. if (poly.plane)
  85831. back.push(poly);
  85832. }
  85833. break;
  85834. }
  85835. };
  85836. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  85837. // point is on the plane.
  85838. Plane.EPSILON = 1e-5;
  85839. return Plane;
  85840. }());
  85841. // # class Polygon
  85842. // Represents a convex polygon. The vertices used to initialize a polygon must
  85843. // be coplanar and form a convex loop.
  85844. //
  85845. // Each convex polygon has a `shared` property, which is shared between all
  85846. // polygons that are clones of each other or were split from the same polygon.
  85847. // This can be used to define per-polygon properties (such as surface color).
  85848. var Polygon = /** @class */ (function () {
  85849. function Polygon(vertices, shared) {
  85850. this.vertices = vertices;
  85851. this.shared = shared;
  85852. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  85853. }
  85854. Polygon.prototype.clone = function () {
  85855. var vertices = this.vertices.map(function (v) { return v.clone(); });
  85856. return new Polygon(vertices, this.shared);
  85857. };
  85858. Polygon.prototype.flip = function () {
  85859. this.vertices.reverse().map(function (v) { v.flip(); });
  85860. this.plane.flip();
  85861. };
  85862. return Polygon;
  85863. }());
  85864. // # class Node
  85865. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  85866. // by picking a polygon to split along. That polygon (and all other coplanar
  85867. // polygons) are added directly to that node and the other polygons are added to
  85868. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  85869. // no distinction between internal and leaf nodes.
  85870. var Node = /** @class */ (function () {
  85871. function Node(polygons) {
  85872. this.plane = null;
  85873. this.front = null;
  85874. this.back = null;
  85875. this.polygons = new Array();
  85876. if (polygons) {
  85877. this.build(polygons);
  85878. }
  85879. }
  85880. Node.prototype.clone = function () {
  85881. var node = new Node();
  85882. node.plane = this.plane && this.plane.clone();
  85883. node.front = this.front && this.front.clone();
  85884. node.back = this.back && this.back.clone();
  85885. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  85886. return node;
  85887. };
  85888. // Convert solid space to empty space and empty space to solid space.
  85889. Node.prototype.invert = function () {
  85890. for (var i = 0; i < this.polygons.length; i++) {
  85891. this.polygons[i].flip();
  85892. }
  85893. if (this.plane) {
  85894. this.plane.flip();
  85895. }
  85896. if (this.front) {
  85897. this.front.invert();
  85898. }
  85899. if (this.back) {
  85900. this.back.invert();
  85901. }
  85902. var temp = this.front;
  85903. this.front = this.back;
  85904. this.back = temp;
  85905. };
  85906. // Recursively remove all polygons in `polygons` that are inside this BSP
  85907. // tree.
  85908. Node.prototype.clipPolygons = function (polygons) {
  85909. if (!this.plane)
  85910. return polygons.slice();
  85911. var front = new Array(), back = new Array();
  85912. for (var i = 0; i < polygons.length; i++) {
  85913. this.plane.splitPolygon(polygons[i], front, back, front, back);
  85914. }
  85915. if (this.front) {
  85916. front = this.front.clipPolygons(front);
  85917. }
  85918. if (this.back) {
  85919. back = this.back.clipPolygons(back);
  85920. }
  85921. else {
  85922. back = [];
  85923. }
  85924. return front.concat(back);
  85925. };
  85926. // Remove all polygons in this BSP tree that are inside the other BSP tree
  85927. // `bsp`.
  85928. Node.prototype.clipTo = function (bsp) {
  85929. this.polygons = bsp.clipPolygons(this.polygons);
  85930. if (this.front)
  85931. this.front.clipTo(bsp);
  85932. if (this.back)
  85933. this.back.clipTo(bsp);
  85934. };
  85935. // Return a list of all polygons in this BSP tree.
  85936. Node.prototype.allPolygons = function () {
  85937. var polygons = this.polygons.slice();
  85938. if (this.front)
  85939. polygons = polygons.concat(this.front.allPolygons());
  85940. if (this.back)
  85941. polygons = polygons.concat(this.back.allPolygons());
  85942. return polygons;
  85943. };
  85944. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  85945. // new polygons are filtered down to the bottom of the tree and become new
  85946. // nodes there. Each set of polygons is partitioned using the first polygon
  85947. // (no heuristic is used to pick a good split).
  85948. Node.prototype.build = function (polygons) {
  85949. if (!polygons.length)
  85950. return;
  85951. if (!this.plane)
  85952. this.plane = polygons[0].plane.clone();
  85953. var front = new Array(), back = new Array();
  85954. for (var i = 0; i < polygons.length; i++) {
  85955. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  85956. }
  85957. if (front.length) {
  85958. if (!this.front)
  85959. this.front = new Node();
  85960. this.front.build(front);
  85961. }
  85962. if (back.length) {
  85963. if (!this.back)
  85964. this.back = new Node();
  85965. this.back.build(back);
  85966. }
  85967. };
  85968. return Node;
  85969. }());
  85970. var CSG = /** @class */ (function () {
  85971. function CSG() {
  85972. this.polygons = new Array();
  85973. }
  85974. // Convert BABYLON.Mesh to BABYLON.CSG
  85975. CSG.FromMesh = function (mesh) {
  85976. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  85977. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  85978. if (mesh instanceof BABYLON.Mesh) {
  85979. mesh.computeWorldMatrix(true);
  85980. matrix = mesh.getWorldMatrix();
  85981. meshPosition = mesh.position.clone();
  85982. meshRotation = mesh.rotation.clone();
  85983. if (mesh.rotationQuaternion) {
  85984. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  85985. }
  85986. meshScaling = mesh.scaling.clone();
  85987. }
  85988. else {
  85989. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  85990. }
  85991. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  85992. var subMeshes = mesh.subMeshes;
  85993. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  85994. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  85995. vertices = [];
  85996. for (var j = 0; j < 3; j++) {
  85997. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  85998. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  85999. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  86000. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  86001. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  86002. vertex = new Vertex(position, normal, uv);
  86003. vertices.push(vertex);
  86004. }
  86005. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  86006. // To handle the case of degenerated triangle
  86007. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  86008. if (polygon.plane)
  86009. polygons.push(polygon);
  86010. }
  86011. }
  86012. var csg = CSG.FromPolygons(polygons);
  86013. csg.matrix = matrix;
  86014. csg.position = meshPosition;
  86015. csg.rotation = meshRotation;
  86016. csg.scaling = meshScaling;
  86017. csg.rotationQuaternion = meshRotationQuaternion;
  86018. currentCSGMeshId++;
  86019. return csg;
  86020. };
  86021. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  86022. CSG.FromPolygons = function (polygons) {
  86023. var csg = new CSG();
  86024. csg.polygons = polygons;
  86025. return csg;
  86026. };
  86027. CSG.prototype.clone = function () {
  86028. var csg = new CSG();
  86029. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  86030. csg.copyTransformAttributes(this);
  86031. return csg;
  86032. };
  86033. CSG.prototype.union = function (csg) {
  86034. var a = new Node(this.clone().polygons);
  86035. var b = new Node(csg.clone().polygons);
  86036. a.clipTo(b);
  86037. b.clipTo(a);
  86038. b.invert();
  86039. b.clipTo(a);
  86040. b.invert();
  86041. a.build(b.allPolygons());
  86042. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86043. };
  86044. CSG.prototype.unionInPlace = function (csg) {
  86045. var a = new Node(this.polygons);
  86046. var b = new Node(csg.polygons);
  86047. a.clipTo(b);
  86048. b.clipTo(a);
  86049. b.invert();
  86050. b.clipTo(a);
  86051. b.invert();
  86052. a.build(b.allPolygons());
  86053. this.polygons = a.allPolygons();
  86054. };
  86055. CSG.prototype.subtract = function (csg) {
  86056. var a = new Node(this.clone().polygons);
  86057. var b = new Node(csg.clone().polygons);
  86058. a.invert();
  86059. a.clipTo(b);
  86060. b.clipTo(a);
  86061. b.invert();
  86062. b.clipTo(a);
  86063. b.invert();
  86064. a.build(b.allPolygons());
  86065. a.invert();
  86066. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86067. };
  86068. CSG.prototype.subtractInPlace = function (csg) {
  86069. var a = new Node(this.polygons);
  86070. var b = new Node(csg.polygons);
  86071. a.invert();
  86072. a.clipTo(b);
  86073. b.clipTo(a);
  86074. b.invert();
  86075. b.clipTo(a);
  86076. b.invert();
  86077. a.build(b.allPolygons());
  86078. a.invert();
  86079. this.polygons = a.allPolygons();
  86080. };
  86081. CSG.prototype.intersect = function (csg) {
  86082. var a = new Node(this.clone().polygons);
  86083. var b = new Node(csg.clone().polygons);
  86084. a.invert();
  86085. b.clipTo(a);
  86086. b.invert();
  86087. a.clipTo(b);
  86088. b.clipTo(a);
  86089. a.build(b.allPolygons());
  86090. a.invert();
  86091. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86092. };
  86093. CSG.prototype.intersectInPlace = function (csg) {
  86094. var a = new Node(this.polygons);
  86095. var b = new Node(csg.polygons);
  86096. a.invert();
  86097. b.clipTo(a);
  86098. b.invert();
  86099. a.clipTo(b);
  86100. b.clipTo(a);
  86101. a.build(b.allPolygons());
  86102. a.invert();
  86103. this.polygons = a.allPolygons();
  86104. };
  86105. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  86106. // not modified.
  86107. CSG.prototype.inverse = function () {
  86108. var csg = this.clone();
  86109. csg.inverseInPlace();
  86110. return csg;
  86111. };
  86112. CSG.prototype.inverseInPlace = function () {
  86113. this.polygons.map(function (p) { p.flip(); });
  86114. };
  86115. // This is used to keep meshes transformations so they can be restored
  86116. // when we build back a Babylon Mesh
  86117. // NB : All CSG operations are performed in world coordinates
  86118. CSG.prototype.copyTransformAttributes = function (csg) {
  86119. this.matrix = csg.matrix;
  86120. this.position = csg.position;
  86121. this.rotation = csg.rotation;
  86122. this.scaling = csg.scaling;
  86123. this.rotationQuaternion = csg.rotationQuaternion;
  86124. return this;
  86125. };
  86126. // Build Raw mesh from CSG
  86127. // Coordinates here are in world space
  86128. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  86129. var matrix = this.matrix.clone();
  86130. matrix.invert();
  86131. 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;
  86132. if (keepSubMeshes) {
  86133. // Sort Polygons, since subMeshes are indices range
  86134. polygons.sort(function (a, b) {
  86135. if (a.shared.meshId === b.shared.meshId) {
  86136. return a.shared.subMeshId - b.shared.subMeshId;
  86137. }
  86138. else {
  86139. return a.shared.meshId - b.shared.meshId;
  86140. }
  86141. });
  86142. }
  86143. for (var i = 0, il = polygons.length; i < il; i++) {
  86144. polygon = polygons[i];
  86145. // Building SubMeshes
  86146. if (!subMesh_dict[polygon.shared.meshId]) {
  86147. subMesh_dict[polygon.shared.meshId] = {};
  86148. }
  86149. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  86150. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  86151. indexStart: +Infinity,
  86152. indexEnd: -Infinity,
  86153. materialIndex: polygon.shared.materialIndex
  86154. };
  86155. }
  86156. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  86157. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  86158. polygonIndices[0] = 0;
  86159. polygonIndices[1] = j - 1;
  86160. polygonIndices[2] = j;
  86161. for (var k = 0; k < 3; k++) {
  86162. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  86163. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  86164. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  86165. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  86166. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  86167. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  86168. // Check if 2 points can be merged
  86169. if (!(typeof vertex_idx !== 'undefined' &&
  86170. normals[vertex_idx * 3] === localNormal.x &&
  86171. normals[vertex_idx * 3 + 1] === localNormal.y &&
  86172. normals[vertex_idx * 3 + 2] === localNormal.z &&
  86173. uvs[vertex_idx * 2] === uv.x &&
  86174. uvs[vertex_idx * 2 + 1] === uv.y)) {
  86175. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  86176. uvs.push(uv.x, uv.y);
  86177. normals.push(normal.x, normal.y, normal.z);
  86178. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  86179. }
  86180. indices.push(vertex_idx);
  86181. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  86182. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  86183. currentIndex++;
  86184. }
  86185. }
  86186. }
  86187. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  86188. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  86189. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  86190. mesh.setIndices(indices, null);
  86191. if (keepSubMeshes) {
  86192. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  86193. var materialIndexOffset = 0, materialMaxIndex;
  86194. mesh.subMeshes = new Array();
  86195. for (var m in subMesh_dict) {
  86196. materialMaxIndex = -1;
  86197. for (var sm in subMesh_dict[m]) {
  86198. subMesh_obj = subMesh_dict[m][sm];
  86199. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  86200. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  86201. }
  86202. materialIndexOffset += ++materialMaxIndex;
  86203. }
  86204. }
  86205. return mesh;
  86206. };
  86207. // Build Mesh from CSG taking material and transforms into account
  86208. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  86209. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  86210. mesh.material = material;
  86211. mesh.position.copyFrom(this.position);
  86212. mesh.rotation.copyFrom(this.rotation);
  86213. if (this.rotationQuaternion) {
  86214. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  86215. }
  86216. mesh.scaling.copyFrom(this.scaling);
  86217. mesh.computeWorldMatrix(true);
  86218. return mesh;
  86219. };
  86220. return CSG;
  86221. }());
  86222. BABYLON.CSG = CSG;
  86223. })(BABYLON || (BABYLON = {}));
  86224. //# sourceMappingURL=babylon.csg.js.map
  86225. var BABYLON;
  86226. (function (BABYLON) {
  86227. var LensFlare = /** @class */ (function () {
  86228. function LensFlare(size, position, color, imgUrl, system) {
  86229. this.size = size;
  86230. this.position = position;
  86231. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  86232. this.color = color || new BABYLON.Color3(1, 1, 1);
  86233. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  86234. this._system = system;
  86235. system.lensFlares.push(this);
  86236. }
  86237. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  86238. return new LensFlare(size, position, color, imgUrl, system);
  86239. };
  86240. LensFlare.prototype.dispose = function () {
  86241. if (this.texture) {
  86242. this.texture.dispose();
  86243. }
  86244. // Remove from scene
  86245. var index = this._system.lensFlares.indexOf(this);
  86246. this._system.lensFlares.splice(index, 1);
  86247. };
  86248. ;
  86249. return LensFlare;
  86250. }());
  86251. BABYLON.LensFlare = LensFlare;
  86252. })(BABYLON || (BABYLON = {}));
  86253. //# sourceMappingURL=babylon.lensFlare.js.map
  86254. var BABYLON;
  86255. (function (BABYLON) {
  86256. // Adds the parser to the scene parsers.
  86257. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  86258. // Lens flares
  86259. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  86260. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  86261. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  86262. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  86263. container.lensFlareSystems.push(lf);
  86264. }
  86265. }
  86266. });
  86267. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  86268. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  86269. if (this.lensFlareSystems[index].name === name) {
  86270. return this.lensFlareSystems[index];
  86271. }
  86272. }
  86273. return null;
  86274. };
  86275. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  86276. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  86277. if (this.lensFlareSystems[index].id === id) {
  86278. return this.lensFlareSystems[index];
  86279. }
  86280. }
  86281. return null;
  86282. };
  86283. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  86284. var index = this.lensFlareSystems.indexOf(toRemove);
  86285. if (index !== -1) {
  86286. this.lensFlareSystems.splice(index, 1);
  86287. }
  86288. return index;
  86289. };
  86290. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  86291. this.lensFlareSystems.push(newLensFlareSystem);
  86292. };
  86293. /**
  86294. * Defines the lens flare scene component responsible to manage any lens flares
  86295. * in a given scene.
  86296. */
  86297. var LensFlareSystemSceneComponent = /** @class */ (function () {
  86298. /**
  86299. * Creates a new instance of the component for the given scene
  86300. * @param scene Defines the scene to register the component in
  86301. */
  86302. function LensFlareSystemSceneComponent(scene) {
  86303. /**
  86304. * The component name helpfull to identify the component in the list of scene components.
  86305. */
  86306. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  86307. this.scene = scene;
  86308. scene.lensFlareSystems = new Array();
  86309. }
  86310. /**
  86311. * Registers the component in a given scene
  86312. */
  86313. LensFlareSystemSceneComponent.prototype.register = function () {
  86314. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  86315. };
  86316. /**
  86317. * Rebuilds the elements related to this component in case of
  86318. * context lost for instance.
  86319. */
  86320. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  86321. // Nothing to do for lens flare
  86322. };
  86323. /**
  86324. * Adds all the element from the container to the scene
  86325. * @param container the container holding the elements
  86326. */
  86327. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  86328. var _this = this;
  86329. if (!container.lensFlareSystems) {
  86330. return;
  86331. }
  86332. container.lensFlareSystems.forEach(function (o) {
  86333. _this.scene.addLensFlareSystem(o);
  86334. });
  86335. };
  86336. /**
  86337. * Removes all the elements in the container from the scene
  86338. * @param container contains the elements to remove
  86339. */
  86340. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  86341. var _this = this;
  86342. if (!container.lensFlareSystems) {
  86343. return;
  86344. }
  86345. container.lensFlareSystems.forEach(function (o) {
  86346. _this.scene.removeLensFlareSystem(o);
  86347. });
  86348. };
  86349. /**
  86350. * Serializes the component data to the specified json object
  86351. * @param serializationObject The object to serialize to
  86352. */
  86353. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  86354. // Lens flares
  86355. serializationObject.lensFlareSystems = [];
  86356. var lensFlareSystems = this.scene.lensFlareSystems;
  86357. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  86358. var lensFlareSystem = lensFlareSystems_1[_i];
  86359. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  86360. }
  86361. };
  86362. /**
  86363. * Disposes the component and the associated ressources.
  86364. */
  86365. LensFlareSystemSceneComponent.prototype.dispose = function () {
  86366. var lensFlareSystems = this.scene.lensFlareSystems;
  86367. while (lensFlareSystems.length) {
  86368. lensFlareSystems[0].dispose();
  86369. }
  86370. };
  86371. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  86372. // Lens flares
  86373. if (this.scene.lensFlaresEnabled) {
  86374. var lensFlareSystems = this.scene.lensFlareSystems;
  86375. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  86376. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  86377. var lensFlareSystem = lensFlareSystems_2[_i];
  86378. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  86379. lensFlareSystem.render();
  86380. }
  86381. }
  86382. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  86383. }
  86384. };
  86385. return LensFlareSystemSceneComponent;
  86386. }());
  86387. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  86388. })(BABYLON || (BABYLON = {}));
  86389. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  86390. var BABYLON;
  86391. (function (BABYLON) {
  86392. var LensFlareSystem = /** @class */ (function () {
  86393. function LensFlareSystem(name, emitter, scene) {
  86394. this.name = name;
  86395. this.lensFlares = new Array();
  86396. this.borderLimit = 300;
  86397. this.viewportBorder = 0;
  86398. this.layerMask = 0x0FFFFFFF;
  86399. this._vertexBuffers = {};
  86400. this._isEnabled = true;
  86401. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86402. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  86403. if (!component) {
  86404. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  86405. scene._addComponent(component);
  86406. }
  86407. this._emitter = emitter;
  86408. this.id = name;
  86409. scene.lensFlareSystems.push(this);
  86410. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  86411. var engine = scene.getEngine();
  86412. // VBO
  86413. var vertices = [];
  86414. vertices.push(1, 1);
  86415. vertices.push(-1, 1);
  86416. vertices.push(-1, -1);
  86417. vertices.push(1, -1);
  86418. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86419. // Indices
  86420. var indices = [];
  86421. indices.push(0);
  86422. indices.push(1);
  86423. indices.push(2);
  86424. indices.push(0);
  86425. indices.push(2);
  86426. indices.push(3);
  86427. this._indexBuffer = engine.createIndexBuffer(indices);
  86428. // Effects
  86429. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  86430. }
  86431. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  86432. get: function () {
  86433. return this._isEnabled;
  86434. },
  86435. set: function (value) {
  86436. this._isEnabled = value;
  86437. },
  86438. enumerable: true,
  86439. configurable: true
  86440. });
  86441. LensFlareSystem.prototype.getScene = function () {
  86442. return this._scene;
  86443. };
  86444. LensFlareSystem.prototype.getEmitter = function () {
  86445. return this._emitter;
  86446. };
  86447. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  86448. this._emitter = newEmitter;
  86449. };
  86450. LensFlareSystem.prototype.getEmitterPosition = function () {
  86451. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  86452. };
  86453. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  86454. var position = this.getEmitterPosition();
  86455. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  86456. this._positionX = position.x;
  86457. this._positionY = position.y;
  86458. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  86459. if (this.viewportBorder > 0) {
  86460. globalViewport.x -= this.viewportBorder;
  86461. globalViewport.y -= this.viewportBorder;
  86462. globalViewport.width += this.viewportBorder * 2;
  86463. globalViewport.height += this.viewportBorder * 2;
  86464. position.x += this.viewportBorder;
  86465. position.y += this.viewportBorder;
  86466. this._positionX += this.viewportBorder;
  86467. this._positionY += this.viewportBorder;
  86468. }
  86469. if (position.z > 0) {
  86470. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  86471. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  86472. return true;
  86473. }
  86474. return true;
  86475. }
  86476. return false;
  86477. };
  86478. /** @hidden */
  86479. LensFlareSystem.prototype._isVisible = function () {
  86480. if (!this._isEnabled || !this._scene.activeCamera) {
  86481. return false;
  86482. }
  86483. var emitterPosition = this.getEmitterPosition();
  86484. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  86485. var distance = direction.length();
  86486. direction.normalize();
  86487. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  86488. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  86489. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  86490. };
  86491. LensFlareSystem.prototype.render = function () {
  86492. if (!this._effect.isReady() || !this._scene.activeCamera)
  86493. return false;
  86494. var engine = this._scene.getEngine();
  86495. var viewport = this._scene.activeCamera.viewport;
  86496. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  86497. // Position
  86498. if (!this.computeEffectivePosition(globalViewport)) {
  86499. return false;
  86500. }
  86501. // Visibility
  86502. if (!this._isVisible()) {
  86503. return false;
  86504. }
  86505. // Intensity
  86506. var awayX;
  86507. var awayY;
  86508. if (this._positionX < this.borderLimit + globalViewport.x) {
  86509. awayX = this.borderLimit + globalViewport.x - this._positionX;
  86510. }
  86511. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  86512. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  86513. }
  86514. else {
  86515. awayX = 0;
  86516. }
  86517. if (this._positionY < this.borderLimit + globalViewport.y) {
  86518. awayY = this.borderLimit + globalViewport.y - this._positionY;
  86519. }
  86520. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  86521. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  86522. }
  86523. else {
  86524. awayY = 0;
  86525. }
  86526. var away = (awayX > awayY) ? awayX : awayY;
  86527. away -= this.viewportBorder;
  86528. if (away > this.borderLimit) {
  86529. away = this.borderLimit;
  86530. }
  86531. var intensity = 1.0 - (away / this.borderLimit);
  86532. if (intensity < 0) {
  86533. return false;
  86534. }
  86535. if (intensity > 1.0) {
  86536. intensity = 1.0;
  86537. }
  86538. if (this.viewportBorder > 0) {
  86539. globalViewport.x += this.viewportBorder;
  86540. globalViewport.y += this.viewportBorder;
  86541. globalViewport.width -= this.viewportBorder * 2;
  86542. globalViewport.height -= this.viewportBorder * 2;
  86543. this._positionX -= this.viewportBorder;
  86544. this._positionY -= this.viewportBorder;
  86545. }
  86546. // Position
  86547. var centerX = globalViewport.x + globalViewport.width / 2;
  86548. var centerY = globalViewport.y + globalViewport.height / 2;
  86549. var distX = centerX - this._positionX;
  86550. var distY = centerY - this._positionY;
  86551. // Effects
  86552. engine.enableEffect(this._effect);
  86553. engine.setState(false);
  86554. engine.setDepthBuffer(false);
  86555. // VBOs
  86556. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  86557. // Flares
  86558. for (var index = 0; index < this.lensFlares.length; index++) {
  86559. var flare = this.lensFlares[index];
  86560. engine.setAlphaMode(flare.alphaMode);
  86561. var x = centerX - (distX * flare.position);
  86562. var y = centerY - (distY * flare.position);
  86563. var cw = flare.size;
  86564. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  86565. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  86566. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  86567. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  86568. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  86569. // Texture
  86570. this._effect.setTexture("textureSampler", flare.texture);
  86571. // Color
  86572. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  86573. // Draw order
  86574. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86575. }
  86576. engine.setDepthBuffer(true);
  86577. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86578. return true;
  86579. };
  86580. LensFlareSystem.prototype.dispose = function () {
  86581. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86582. if (vertexBuffer) {
  86583. vertexBuffer.dispose();
  86584. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86585. }
  86586. if (this._indexBuffer) {
  86587. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86588. this._indexBuffer = null;
  86589. }
  86590. while (this.lensFlares.length) {
  86591. this.lensFlares[0].dispose();
  86592. }
  86593. // Remove from scene
  86594. var index = this._scene.lensFlareSystems.indexOf(this);
  86595. this._scene.lensFlareSystems.splice(index, 1);
  86596. };
  86597. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  86598. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  86599. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  86600. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  86601. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  86602. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  86603. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  86604. var parsedFlare = parsedLensFlareSystem.flares[index];
  86605. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  86606. }
  86607. return lensFlareSystem;
  86608. };
  86609. LensFlareSystem.prototype.serialize = function () {
  86610. var serializationObject = {};
  86611. serializationObject.id = this.id;
  86612. serializationObject.name = this.name;
  86613. serializationObject.emitterId = this.getEmitter().id;
  86614. serializationObject.borderLimit = this.borderLimit;
  86615. serializationObject.flares = [];
  86616. for (var index = 0; index < this.lensFlares.length; index++) {
  86617. var flare = this.lensFlares[index];
  86618. serializationObject.flares.push({
  86619. size: flare.size,
  86620. position: flare.position,
  86621. color: flare.color.asArray(),
  86622. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  86623. });
  86624. }
  86625. return serializationObject;
  86626. };
  86627. return LensFlareSystem;
  86628. }());
  86629. BABYLON.LensFlareSystem = LensFlareSystem;
  86630. })(BABYLON || (BABYLON = {}));
  86631. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  86632. var BABYLON;
  86633. (function (BABYLON) {
  86634. /**
  86635. * This is a holder class for the physics joint created by the physics plugin.
  86636. * It holds a set of functions to control the underlying joint.
  86637. */
  86638. var PhysicsJoint = /** @class */ (function () {
  86639. function PhysicsJoint(type, jointData) {
  86640. this.type = type;
  86641. this.jointData = jointData;
  86642. jointData.nativeParams = jointData.nativeParams || {};
  86643. }
  86644. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  86645. get: function () {
  86646. return this._physicsJoint;
  86647. },
  86648. set: function (newJoint) {
  86649. if (this._physicsJoint) {
  86650. //remove from the wolrd
  86651. }
  86652. this._physicsJoint = newJoint;
  86653. },
  86654. enumerable: true,
  86655. configurable: true
  86656. });
  86657. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  86658. set: function (physicsPlugin) {
  86659. this._physicsPlugin = physicsPlugin;
  86660. },
  86661. enumerable: true,
  86662. configurable: true
  86663. });
  86664. /**
  86665. * Execute a function that is physics-plugin specific.
  86666. * @param {Function} func the function that will be executed.
  86667. * It accepts two parameters: the physics world and the physics joint.
  86668. */
  86669. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  86670. func(this._physicsPlugin.world, this._physicsJoint);
  86671. };
  86672. //TODO check if the native joints are the same
  86673. //Joint Types
  86674. PhysicsJoint.DistanceJoint = 0;
  86675. PhysicsJoint.HingeJoint = 1;
  86676. PhysicsJoint.BallAndSocketJoint = 2;
  86677. PhysicsJoint.WheelJoint = 3;
  86678. PhysicsJoint.SliderJoint = 4;
  86679. //OIMO
  86680. PhysicsJoint.PrismaticJoint = 5;
  86681. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  86682. PhysicsJoint.UniversalJoint = 6;
  86683. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  86684. //Cannon
  86685. //Similar to a Ball-Joint. Different in params
  86686. PhysicsJoint.PointToPointJoint = 8;
  86687. //Cannon only at the moment
  86688. PhysicsJoint.SpringJoint = 9;
  86689. PhysicsJoint.LockJoint = 10;
  86690. return PhysicsJoint;
  86691. }());
  86692. BABYLON.PhysicsJoint = PhysicsJoint;
  86693. /**
  86694. * A class representing a physics distance joint.
  86695. */
  86696. var DistanceJoint = /** @class */ (function (_super) {
  86697. __extends(DistanceJoint, _super);
  86698. function DistanceJoint(jointData) {
  86699. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  86700. }
  86701. /**
  86702. * Update the predefined distance.
  86703. */
  86704. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  86705. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  86706. };
  86707. return DistanceJoint;
  86708. }(PhysicsJoint));
  86709. BABYLON.DistanceJoint = DistanceJoint;
  86710. var MotorEnabledJoint = /** @class */ (function (_super) {
  86711. __extends(MotorEnabledJoint, _super);
  86712. function MotorEnabledJoint(type, jointData) {
  86713. return _super.call(this, type, jointData) || this;
  86714. }
  86715. /**
  86716. * Set the motor values.
  86717. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86718. * @param {number} force the force to apply
  86719. * @param {number} maxForce max force for this motor.
  86720. */
  86721. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  86722. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  86723. };
  86724. /**
  86725. * Set the motor's limits.
  86726. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86727. */
  86728. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  86729. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  86730. };
  86731. return MotorEnabledJoint;
  86732. }(PhysicsJoint));
  86733. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  86734. /**
  86735. * This class represents a single hinge physics joint
  86736. */
  86737. var HingeJoint = /** @class */ (function (_super) {
  86738. __extends(HingeJoint, _super);
  86739. function HingeJoint(jointData) {
  86740. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  86741. }
  86742. /**
  86743. * Set the motor values.
  86744. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86745. * @param {number} force the force to apply
  86746. * @param {number} maxForce max force for this motor.
  86747. */
  86748. HingeJoint.prototype.setMotor = function (force, maxForce) {
  86749. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  86750. };
  86751. /**
  86752. * Set the motor's limits.
  86753. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86754. */
  86755. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  86756. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  86757. };
  86758. return HingeJoint;
  86759. }(MotorEnabledJoint));
  86760. BABYLON.HingeJoint = HingeJoint;
  86761. /**
  86762. * This class represents a dual hinge physics joint (same as wheel joint)
  86763. */
  86764. var Hinge2Joint = /** @class */ (function (_super) {
  86765. __extends(Hinge2Joint, _super);
  86766. function Hinge2Joint(jointData) {
  86767. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  86768. }
  86769. /**
  86770. * Set the motor values.
  86771. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86772. * @param {number} force the force to apply
  86773. * @param {number} maxForce max force for this motor.
  86774. * @param {motorIndex} the motor's index, 0 or 1.
  86775. */
  86776. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  86777. if (motorIndex === void 0) { motorIndex = 0; }
  86778. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  86779. };
  86780. /**
  86781. * Set the motor limits.
  86782. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86783. * @param {number} upperLimit the upper limit
  86784. * @param {number} lowerLimit lower limit
  86785. * @param {motorIndex} the motor's index, 0 or 1.
  86786. */
  86787. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  86788. if (motorIndex === void 0) { motorIndex = 0; }
  86789. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  86790. };
  86791. return Hinge2Joint;
  86792. }(MotorEnabledJoint));
  86793. BABYLON.Hinge2Joint = Hinge2Joint;
  86794. })(BABYLON || (BABYLON = {}));
  86795. //# sourceMappingURL=babylon.physicsJoint.js.map
  86796. var BABYLON;
  86797. (function (BABYLON) {
  86798. var PhysicsImpostor = /** @class */ (function () {
  86799. function PhysicsImpostor(object, type, _options, _scene) {
  86800. if (_options === void 0) { _options = { mass: 0 }; }
  86801. var _this = this;
  86802. this.object = object;
  86803. this.type = type;
  86804. this._options = _options;
  86805. this._scene = _scene;
  86806. this._bodyUpdateRequired = false;
  86807. this._onBeforePhysicsStepCallbacks = new Array();
  86808. this._onAfterPhysicsStepCallbacks = new Array();
  86809. this._onPhysicsCollideCallbacks = [];
  86810. this._deltaPosition = BABYLON.Vector3.Zero();
  86811. this._isDisposed = false;
  86812. //temp variables for parent rotation calculations
  86813. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  86814. this._tmpQuat = new BABYLON.Quaternion();
  86815. this._tmpQuat2 = new BABYLON.Quaternion();
  86816. /**
  86817. * this function is executed by the physics engine.
  86818. */
  86819. this.beforeStep = function () {
  86820. if (!_this._physicsEngine) {
  86821. return;
  86822. }
  86823. _this.object.translate(_this._deltaPosition, -1);
  86824. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  86825. _this.object.computeWorldMatrix(false);
  86826. if (_this.object.parent && _this.object.rotationQuaternion) {
  86827. _this.getParentsRotation();
  86828. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  86829. }
  86830. else {
  86831. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  86832. }
  86833. if (!_this._options.disableBidirectionalTransformation) {
  86834. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  86835. }
  86836. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  86837. func(_this);
  86838. });
  86839. };
  86840. /**
  86841. * this function is executed by the physics engine.
  86842. */
  86843. this.afterStep = function () {
  86844. if (!_this._physicsEngine) {
  86845. return;
  86846. }
  86847. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  86848. func(_this);
  86849. });
  86850. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  86851. // object has now its world rotation. needs to be converted to local.
  86852. if (_this.object.parent && _this.object.rotationQuaternion) {
  86853. _this.getParentsRotation();
  86854. _this._tmpQuat.conjugateInPlace();
  86855. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  86856. }
  86857. // take the position set and make it the absolute position of this object.
  86858. _this.object.setAbsolutePosition(_this.object.position);
  86859. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  86860. _this.object.translate(_this._deltaPosition, 1);
  86861. };
  86862. /**
  86863. * Legacy collision detection event support
  86864. */
  86865. this.onCollideEvent = null;
  86866. //event and body object due to cannon's event-based architecture.
  86867. this.onCollide = function (e) {
  86868. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  86869. return;
  86870. }
  86871. if (!_this._physicsEngine) {
  86872. return;
  86873. }
  86874. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  86875. if (otherImpostor) {
  86876. // Legacy collision detection event support
  86877. if (_this.onCollideEvent) {
  86878. _this.onCollideEvent(_this, otherImpostor);
  86879. }
  86880. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  86881. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  86882. }).forEach(function (obj) {
  86883. obj.callback(_this, otherImpostor);
  86884. });
  86885. }
  86886. };
  86887. //sanity check!
  86888. if (!this.object) {
  86889. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  86890. return;
  86891. }
  86892. //legacy support for old syntax.
  86893. if (!this._scene && object.getScene) {
  86894. this._scene = object.getScene();
  86895. }
  86896. if (!this._scene) {
  86897. return;
  86898. }
  86899. this._physicsEngine = this._scene.getPhysicsEngine();
  86900. if (!this._physicsEngine) {
  86901. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  86902. }
  86903. else {
  86904. //set the object's quaternion, if not set
  86905. if (!this.object.rotationQuaternion) {
  86906. if (this.object.rotation) {
  86907. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  86908. }
  86909. else {
  86910. this.object.rotationQuaternion = new BABYLON.Quaternion();
  86911. }
  86912. }
  86913. //default options params
  86914. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  86915. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  86916. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  86917. this._joints = [];
  86918. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  86919. if (!this.object.parent || this._options.ignoreParent) {
  86920. this._init();
  86921. }
  86922. else if (this.object.parent.physicsImpostor) {
  86923. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  86924. }
  86925. }
  86926. }
  86927. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  86928. get: function () {
  86929. return this._isDisposed;
  86930. },
  86931. enumerable: true,
  86932. configurable: true
  86933. });
  86934. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  86935. get: function () {
  86936. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  86937. },
  86938. set: function (value) {
  86939. this.setMass(value);
  86940. },
  86941. enumerable: true,
  86942. configurable: true
  86943. });
  86944. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  86945. get: function () {
  86946. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  86947. },
  86948. set: function (value) {
  86949. if (!this._physicsEngine) {
  86950. return;
  86951. }
  86952. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  86953. },
  86954. enumerable: true,
  86955. configurable: true
  86956. });
  86957. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  86958. get: function () {
  86959. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  86960. },
  86961. set: function (value) {
  86962. if (!this._physicsEngine) {
  86963. return;
  86964. }
  86965. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  86966. },
  86967. enumerable: true,
  86968. configurable: true
  86969. });
  86970. /**
  86971. * This function will completly initialize this impostor.
  86972. * It will create a new body - but only if this mesh has no parent.
  86973. * If it has, this impostor will not be used other than to define the impostor
  86974. * of the child mesh.
  86975. * @hidden
  86976. */
  86977. PhysicsImpostor.prototype._init = function () {
  86978. if (!this._physicsEngine) {
  86979. return;
  86980. }
  86981. this._physicsEngine.removeImpostor(this);
  86982. this.physicsBody = null;
  86983. this._parent = this._parent || this._getPhysicsParent();
  86984. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  86985. this._physicsEngine.addImpostor(this);
  86986. }
  86987. };
  86988. PhysicsImpostor.prototype._getPhysicsParent = function () {
  86989. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  86990. var parentMesh = this.object.parent;
  86991. return parentMesh.physicsImpostor;
  86992. }
  86993. return null;
  86994. };
  86995. /**
  86996. * Should a new body be generated.
  86997. */
  86998. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  86999. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  87000. };
  87001. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  87002. this.forceUpdate();
  87003. };
  87004. /**
  87005. * Force a regeneration of this or the parent's impostor's body.
  87006. * Use under cautious - This will remove all joints already implemented.
  87007. */
  87008. PhysicsImpostor.prototype.forceUpdate = function () {
  87009. this._init();
  87010. if (this.parent && !this._options.ignoreParent) {
  87011. this.parent.forceUpdate();
  87012. }
  87013. };
  87014. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  87015. /*public get mesh(): AbstractMesh {
  87016. return this._mesh;
  87017. }*/
  87018. /**
  87019. * Gets the body that holds this impostor. Either its own, or its parent.
  87020. */
  87021. get: function () {
  87022. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  87023. },
  87024. /**
  87025. * Set the physics body. Used mainly by the physics engine/plugin
  87026. */
  87027. set: function (physicsBody) {
  87028. if (this._physicsBody && this._physicsEngine) {
  87029. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  87030. }
  87031. this._physicsBody = physicsBody;
  87032. this.resetUpdateFlags();
  87033. },
  87034. enumerable: true,
  87035. configurable: true
  87036. });
  87037. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  87038. get: function () {
  87039. return !this._options.ignoreParent && this._parent ? this._parent : null;
  87040. },
  87041. set: function (value) {
  87042. this._parent = value;
  87043. },
  87044. enumerable: true,
  87045. configurable: true
  87046. });
  87047. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  87048. this._bodyUpdateRequired = false;
  87049. };
  87050. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  87051. if (this.object.getBoundingInfo) {
  87052. var q = this.object.rotationQuaternion;
  87053. //reset rotation
  87054. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  87055. //calculate the world matrix with no rotation
  87056. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  87057. var boundingInfo = this.object.getBoundingInfo();
  87058. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  87059. //bring back the rotation
  87060. this.object.rotationQuaternion = q;
  87061. //calculate the world matrix with the new rotation
  87062. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  87063. return size;
  87064. }
  87065. else {
  87066. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  87067. }
  87068. };
  87069. PhysicsImpostor.prototype.getObjectCenter = function () {
  87070. if (this.object.getBoundingInfo) {
  87071. var boundingInfo = this.object.getBoundingInfo();
  87072. return boundingInfo.boundingBox.centerWorld;
  87073. }
  87074. else {
  87075. return this.object.position;
  87076. }
  87077. };
  87078. /**
  87079. * Get a specific parametes from the options parameter.
  87080. */
  87081. PhysicsImpostor.prototype.getParam = function (paramName) {
  87082. return this._options[paramName];
  87083. };
  87084. /**
  87085. * Sets a specific parameter in the options given to the physics plugin
  87086. */
  87087. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  87088. this._options[paramName] = value;
  87089. this._bodyUpdateRequired = true;
  87090. };
  87091. /**
  87092. * Specifically change the body's mass option. Won't recreate the physics body object
  87093. */
  87094. PhysicsImpostor.prototype.setMass = function (mass) {
  87095. if (this.getParam("mass") !== mass) {
  87096. this.setParam("mass", mass);
  87097. }
  87098. if (this._physicsEngine) {
  87099. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  87100. }
  87101. };
  87102. PhysicsImpostor.prototype.getLinearVelocity = function () {
  87103. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  87104. };
  87105. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  87106. if (this._physicsEngine) {
  87107. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  87108. }
  87109. };
  87110. PhysicsImpostor.prototype.getAngularVelocity = function () {
  87111. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  87112. };
  87113. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  87114. if (this._physicsEngine) {
  87115. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  87116. }
  87117. };
  87118. /**
  87119. * Execute a function with the physics plugin native code.
  87120. * Provide a function the will have two variables - the world object and the physics body object.
  87121. */
  87122. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  87123. if (this._physicsEngine) {
  87124. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  87125. }
  87126. };
  87127. /**
  87128. * Register a function that will be executed before the physics world is stepping forward.
  87129. */
  87130. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  87131. this._onBeforePhysicsStepCallbacks.push(func);
  87132. };
  87133. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  87134. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  87135. if (index > -1) {
  87136. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  87137. }
  87138. else {
  87139. BABYLON.Tools.Warn("Function to remove was not found");
  87140. }
  87141. };
  87142. /**
  87143. * Register a function that will be executed after the physics step
  87144. */
  87145. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  87146. this._onAfterPhysicsStepCallbacks.push(func);
  87147. };
  87148. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  87149. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  87150. if (index > -1) {
  87151. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  87152. }
  87153. else {
  87154. BABYLON.Tools.Warn("Function to remove was not found");
  87155. }
  87156. };
  87157. /**
  87158. * register a function that will be executed when this impostor collides against a different body.
  87159. */
  87160. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  87161. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  87162. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  87163. };
  87164. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  87165. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  87166. var index = -1;
  87167. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  87168. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  87169. // chcek the arrays match
  87170. var sameList = cbDef.otherImpostors.every(function (impostor) {
  87171. return collidedAgainstList.indexOf(impostor) > -1;
  87172. });
  87173. if (sameList) {
  87174. index = idx;
  87175. }
  87176. return sameList;
  87177. }
  87178. return false;
  87179. });
  87180. if (found) {
  87181. this._onPhysicsCollideCallbacks.splice(index, 1);
  87182. }
  87183. else {
  87184. BABYLON.Tools.Warn("Function to remove was not found");
  87185. }
  87186. };
  87187. PhysicsImpostor.prototype.getParentsRotation = function () {
  87188. var parent = this.object.parent;
  87189. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  87190. while (parent) {
  87191. if (parent.rotationQuaternion) {
  87192. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  87193. }
  87194. else {
  87195. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  87196. }
  87197. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  87198. parent = parent.parent;
  87199. }
  87200. return this._tmpQuat;
  87201. };
  87202. /**
  87203. * Apply a force
  87204. */
  87205. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  87206. if (this._physicsEngine) {
  87207. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  87208. }
  87209. return this;
  87210. };
  87211. /**
  87212. * Apply an impulse
  87213. */
  87214. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  87215. if (this._physicsEngine) {
  87216. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  87217. }
  87218. return this;
  87219. };
  87220. /**
  87221. * A help function to create a joint.
  87222. */
  87223. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  87224. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  87225. this.addJoint(otherImpostor, joint);
  87226. return this;
  87227. };
  87228. /**
  87229. * Add a joint to this impostor with a different impostor.
  87230. */
  87231. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  87232. this._joints.push({
  87233. otherImpostor: otherImpostor,
  87234. joint: joint
  87235. });
  87236. if (this._physicsEngine) {
  87237. this._physicsEngine.addJoint(this, otherImpostor, joint);
  87238. }
  87239. return this;
  87240. };
  87241. /**
  87242. * Will keep this body still, in a sleep mode.
  87243. */
  87244. PhysicsImpostor.prototype.sleep = function () {
  87245. if (this._physicsEngine) {
  87246. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  87247. }
  87248. return this;
  87249. };
  87250. /**
  87251. * Wake the body up.
  87252. */
  87253. PhysicsImpostor.prototype.wakeUp = function () {
  87254. if (this._physicsEngine) {
  87255. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  87256. }
  87257. return this;
  87258. };
  87259. PhysicsImpostor.prototype.clone = function (newObject) {
  87260. if (!newObject)
  87261. return null;
  87262. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  87263. };
  87264. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  87265. var _this = this;
  87266. //no dispose if no physics engine is available.
  87267. if (!this._physicsEngine) {
  87268. return;
  87269. }
  87270. this._joints.forEach(function (j) {
  87271. if (_this._physicsEngine) {
  87272. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  87273. }
  87274. });
  87275. //dispose the physics body
  87276. this._physicsEngine.removeImpostor(this);
  87277. if (this.parent) {
  87278. this.parent.forceUpdate();
  87279. }
  87280. else {
  87281. /*this._object.getChildMeshes().forEach(function(mesh) {
  87282. if (mesh.physicsImpostor) {
  87283. if (disposeChildren) {
  87284. mesh.physicsImpostor.dispose();
  87285. mesh.physicsImpostor = null;
  87286. }
  87287. }
  87288. })*/
  87289. }
  87290. this._isDisposed = true;
  87291. };
  87292. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  87293. this._deltaPosition.copyFrom(position);
  87294. };
  87295. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  87296. if (!this._deltaRotation) {
  87297. this._deltaRotation = new BABYLON.Quaternion();
  87298. }
  87299. this._deltaRotation.copyFrom(rotation);
  87300. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  87301. };
  87302. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  87303. if (this._physicsEngine) {
  87304. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  87305. }
  87306. return this;
  87307. };
  87308. PhysicsImpostor.prototype.getRadius = function () {
  87309. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  87310. };
  87311. /**
  87312. * Sync a bone with this impostor
  87313. * @param bone The bone to sync to the impostor.
  87314. * @param boneMesh The mesh that the bone is influencing.
  87315. * @param jointPivot The pivot of the joint / bone in local space.
  87316. * @param distToJoint Optional distance from the impostor to the joint.
  87317. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  87318. */
  87319. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  87320. var tempVec = PhysicsImpostor._tmpVecs[0];
  87321. var mesh = this.object;
  87322. if (mesh.rotationQuaternion) {
  87323. if (adjustRotation) {
  87324. var tempQuat = PhysicsImpostor._tmpQuat;
  87325. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  87326. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  87327. }
  87328. else {
  87329. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  87330. }
  87331. }
  87332. tempVec.x = 0;
  87333. tempVec.y = 0;
  87334. tempVec.z = 0;
  87335. if (jointPivot) {
  87336. tempVec.x = jointPivot.x;
  87337. tempVec.y = jointPivot.y;
  87338. tempVec.z = jointPivot.z;
  87339. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  87340. if (distToJoint === undefined || distToJoint === null) {
  87341. distToJoint = jointPivot.length();
  87342. }
  87343. tempVec.x *= distToJoint;
  87344. tempVec.y *= distToJoint;
  87345. tempVec.z *= distToJoint;
  87346. }
  87347. if (bone.getParent()) {
  87348. tempVec.addInPlace(mesh.getAbsolutePosition());
  87349. bone.setAbsolutePosition(tempVec, boneMesh);
  87350. }
  87351. else {
  87352. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  87353. boneMesh.position.x -= tempVec.x;
  87354. boneMesh.position.y -= tempVec.y;
  87355. boneMesh.position.z -= tempVec.z;
  87356. }
  87357. };
  87358. /**
  87359. * Sync impostor to a bone
  87360. * @param bone The bone that the impostor will be synced to.
  87361. * @param boneMesh The mesh that the bone is influencing.
  87362. * @param jointPivot The pivot of the joint / bone in local space.
  87363. * @param distToJoint Optional distance from the impostor to the joint.
  87364. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  87365. * @param boneAxis Optional vector3 axis the bone is aligned with
  87366. */
  87367. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  87368. var mesh = this.object;
  87369. if (mesh.rotationQuaternion) {
  87370. if (adjustRotation) {
  87371. var tempQuat = PhysicsImpostor._tmpQuat;
  87372. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  87373. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  87374. }
  87375. else {
  87376. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  87377. }
  87378. }
  87379. var pos = PhysicsImpostor._tmpVecs[0];
  87380. var boneDir = PhysicsImpostor._tmpVecs[1];
  87381. if (!boneAxis) {
  87382. boneAxis = PhysicsImpostor._tmpVecs[2];
  87383. boneAxis.x = 0;
  87384. boneAxis.y = 1;
  87385. boneAxis.z = 0;
  87386. }
  87387. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  87388. bone.getAbsolutePositionToRef(boneMesh, pos);
  87389. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  87390. distToJoint = jointPivot.length();
  87391. }
  87392. if (distToJoint !== undefined && distToJoint !== null) {
  87393. pos.x += boneDir.x * distToJoint;
  87394. pos.y += boneDir.y * distToJoint;
  87395. pos.z += boneDir.z * distToJoint;
  87396. }
  87397. mesh.setAbsolutePosition(pos);
  87398. };
  87399. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  87400. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  87401. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87402. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  87403. //Impostor types
  87404. PhysicsImpostor.NoImpostor = 0;
  87405. PhysicsImpostor.SphereImpostor = 1;
  87406. PhysicsImpostor.BoxImpostor = 2;
  87407. PhysicsImpostor.PlaneImpostor = 3;
  87408. PhysicsImpostor.MeshImpostor = 4;
  87409. PhysicsImpostor.CylinderImpostor = 7;
  87410. PhysicsImpostor.ParticleImpostor = 8;
  87411. PhysicsImpostor.HeightmapImpostor = 9;
  87412. return PhysicsImpostor;
  87413. }());
  87414. BABYLON.PhysicsImpostor = PhysicsImpostor;
  87415. })(BABYLON || (BABYLON = {}));
  87416. //# sourceMappingURL=babylon.physicsImpostor.js.map
  87417. var BABYLON;
  87418. (function (BABYLON) {
  87419. var PhysicsEngine = /** @class */ (function () {
  87420. function PhysicsEngine(gravity, _physicsPlugin) {
  87421. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  87422. this._physicsPlugin = _physicsPlugin;
  87423. //new methods and parameters
  87424. this._impostors = [];
  87425. this._joints = [];
  87426. if (!this._physicsPlugin.isSupported()) {
  87427. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  87428. + "Please make sure it is included.");
  87429. }
  87430. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  87431. this.setGravity(gravity);
  87432. this.setTimeStep();
  87433. }
  87434. PhysicsEngine.prototype.setGravity = function (gravity) {
  87435. this.gravity = gravity;
  87436. this._physicsPlugin.setGravity(this.gravity);
  87437. };
  87438. /**
  87439. * Set the time step of the physics engine.
  87440. * default is 1/60.
  87441. * To slow it down, enter 1/600 for example.
  87442. * To speed it up, 1/30
  87443. * @param {number} newTimeStep the new timestep to apply to this world.
  87444. */
  87445. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  87446. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  87447. this._physicsPlugin.setTimeStep(newTimeStep);
  87448. };
  87449. /**
  87450. * Get the time step of the physics engine.
  87451. */
  87452. PhysicsEngine.prototype.getTimeStep = function () {
  87453. return this._physicsPlugin.getTimeStep();
  87454. };
  87455. PhysicsEngine.prototype.dispose = function () {
  87456. this._impostors.forEach(function (impostor) {
  87457. impostor.dispose();
  87458. });
  87459. this._physicsPlugin.dispose();
  87460. };
  87461. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  87462. return this._physicsPlugin.name;
  87463. };
  87464. /**
  87465. * Adding a new impostor for the impostor tracking.
  87466. * This will be done by the impostor itself.
  87467. * @param {PhysicsImpostor} impostor the impostor to add
  87468. */
  87469. PhysicsEngine.prototype.addImpostor = function (impostor) {
  87470. impostor.uniqueId = this._impostors.push(impostor);
  87471. //if no parent, generate the body
  87472. if (!impostor.parent) {
  87473. this._physicsPlugin.generatePhysicsBody(impostor);
  87474. }
  87475. };
  87476. /**
  87477. * Remove an impostor from the engine.
  87478. * This impostor and its mesh will not longer be updated by the physics engine.
  87479. * @param {PhysicsImpostor} impostor the impostor to remove
  87480. */
  87481. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  87482. var index = this._impostors.indexOf(impostor);
  87483. if (index > -1) {
  87484. var removed = this._impostors.splice(index, 1);
  87485. //Is it needed?
  87486. if (removed.length) {
  87487. //this will also remove it from the world.
  87488. removed[0].physicsBody = null;
  87489. }
  87490. }
  87491. };
  87492. /**
  87493. * Add a joint to the physics engine
  87494. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  87495. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  87496. * @param {PhysicsJoint} the joint that will connect both impostors.
  87497. */
  87498. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  87499. var impostorJoint = {
  87500. mainImpostor: mainImpostor,
  87501. connectedImpostor: connectedImpostor,
  87502. joint: joint
  87503. };
  87504. joint.physicsPlugin = this._physicsPlugin;
  87505. this._joints.push(impostorJoint);
  87506. this._physicsPlugin.generateJoint(impostorJoint);
  87507. };
  87508. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  87509. var matchingJoints = this._joints.filter(function (impostorJoint) {
  87510. return (impostorJoint.connectedImpostor === connectedImpostor
  87511. && impostorJoint.joint === joint
  87512. && impostorJoint.mainImpostor === mainImpostor);
  87513. });
  87514. if (matchingJoints.length) {
  87515. this._physicsPlugin.removeJoint(matchingJoints[0]);
  87516. //TODO remove it from the list as well
  87517. }
  87518. };
  87519. /**
  87520. * Called by the scene. no need to call it.
  87521. * @hidden
  87522. */
  87523. PhysicsEngine.prototype._step = function (delta) {
  87524. var _this = this;
  87525. //check if any mesh has no body / requires an update
  87526. this._impostors.forEach(function (impostor) {
  87527. if (impostor.isBodyInitRequired()) {
  87528. _this._physicsPlugin.generatePhysicsBody(impostor);
  87529. }
  87530. });
  87531. if (delta > 0.1) {
  87532. delta = 0.1;
  87533. }
  87534. else if (delta <= 0) {
  87535. delta = 1.0 / 60.0;
  87536. }
  87537. this._physicsPlugin.executeStep(delta, this._impostors);
  87538. };
  87539. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  87540. return this._physicsPlugin;
  87541. };
  87542. PhysicsEngine.prototype.getImpostors = function () {
  87543. return this._impostors;
  87544. };
  87545. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  87546. for (var i = 0; i < this._impostors.length; ++i) {
  87547. if (this._impostors[i].object === object) {
  87548. return this._impostors[i];
  87549. }
  87550. }
  87551. return null;
  87552. };
  87553. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  87554. for (var i = 0; i < this._impostors.length; ++i) {
  87555. if (this._impostors[i].physicsBody === body) {
  87556. return this._impostors[i];
  87557. }
  87558. }
  87559. return null;
  87560. };
  87561. // Statics
  87562. PhysicsEngine.Epsilon = 0.001;
  87563. return PhysicsEngine;
  87564. }());
  87565. BABYLON.PhysicsEngine = PhysicsEngine;
  87566. })(BABYLON || (BABYLON = {}));
  87567. //# sourceMappingURL=babylon.physicsEngine.js.map
  87568. var BABYLON;
  87569. (function (BABYLON) {
  87570. var PhysicsHelper = /** @class */ (function () {
  87571. function PhysicsHelper(scene) {
  87572. this._scene = scene;
  87573. this._physicsEngine = this._scene.getPhysicsEngine();
  87574. if (!this._physicsEngine) {
  87575. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  87576. }
  87577. }
  87578. /**
  87579. * @param {Vector3} origin the origin of the explosion
  87580. * @param {number} radius the explosion radius
  87581. * @param {number} strength the explosion strength
  87582. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87583. */
  87584. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  87585. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87586. if (!this._physicsEngine) {
  87587. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  87588. return null;
  87589. }
  87590. var impostors = this._physicsEngine.getImpostors();
  87591. if (impostors.length === 0) {
  87592. return null;
  87593. }
  87594. var event = new PhysicsRadialExplosionEvent(this._scene);
  87595. impostors.forEach(function (impostor) {
  87596. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  87597. if (!impostorForceAndContactPoint) {
  87598. return;
  87599. }
  87600. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87601. });
  87602. event.dispose(false);
  87603. return event;
  87604. };
  87605. /**
  87606. * @param {Vector3} origin the origin of the explosion
  87607. * @param {number} radius the explosion radius
  87608. * @param {number} strength the explosion strength
  87609. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87610. */
  87611. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  87612. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87613. if (!this._physicsEngine) {
  87614. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87615. return null;
  87616. }
  87617. var impostors = this._physicsEngine.getImpostors();
  87618. if (impostors.length === 0) {
  87619. return null;
  87620. }
  87621. var event = new PhysicsRadialExplosionEvent(this._scene);
  87622. impostors.forEach(function (impostor) {
  87623. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  87624. if (!impostorForceAndContactPoint) {
  87625. return;
  87626. }
  87627. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87628. });
  87629. event.dispose(false);
  87630. return event;
  87631. };
  87632. /**
  87633. * @param {Vector3} origin the origin of the explosion
  87634. * @param {number} radius the explosion radius
  87635. * @param {number} strength the explosion strength
  87636. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87637. */
  87638. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  87639. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87640. if (!this._physicsEngine) {
  87641. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87642. return null;
  87643. }
  87644. var impostors = this._physicsEngine.getImpostors();
  87645. if (impostors.length === 0) {
  87646. return null;
  87647. }
  87648. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  87649. event.dispose(false);
  87650. return event;
  87651. };
  87652. /**
  87653. * @param {Vector3} origin the origin of the updraft
  87654. * @param {number} radius the radius of the updraft
  87655. * @param {number} strength the strength of the updraft
  87656. * @param {number} height the height of the updraft
  87657. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  87658. */
  87659. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  87660. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  87661. if (!this._physicsEngine) {
  87662. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87663. return null;
  87664. }
  87665. if (this._physicsEngine.getImpostors().length === 0) {
  87666. return null;
  87667. }
  87668. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  87669. event.dispose(false);
  87670. return event;
  87671. };
  87672. /**
  87673. * @param {Vector3} origin the of the vortex
  87674. * @param {number} radius the radius of the vortex
  87675. * @param {number} strength the strength of the vortex
  87676. * @param {number} height the height of the vortex
  87677. */
  87678. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  87679. if (!this._physicsEngine) {
  87680. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87681. return null;
  87682. }
  87683. if (this._physicsEngine.getImpostors().length === 0) {
  87684. return null;
  87685. }
  87686. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  87687. event.dispose(false);
  87688. return event;
  87689. };
  87690. return PhysicsHelper;
  87691. }());
  87692. BABYLON.PhysicsHelper = PhysicsHelper;
  87693. /***** Radial explosion *****/
  87694. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  87695. function PhysicsRadialExplosionEvent(scene) {
  87696. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  87697. this._rays = [];
  87698. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  87699. this._scene = scene;
  87700. }
  87701. /**
  87702. * Returns the data related to the radial explosion event (sphere & rays).
  87703. * @returns {PhysicsRadialExplosionEventData}
  87704. */
  87705. PhysicsRadialExplosionEvent.prototype.getData = function () {
  87706. this._dataFetched = true;
  87707. return {
  87708. sphere: this._sphere,
  87709. rays: this._rays,
  87710. };
  87711. };
  87712. /**
  87713. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  87714. * @param impostor
  87715. * @param {Vector3} origin the origin of the explosion
  87716. * @param {number} radius the explosion radius
  87717. * @param {number} strength the explosion strength
  87718. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  87719. * @returns {Nullable<PhysicsForceAndContactPoint>}
  87720. */
  87721. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  87722. if (impostor.mass === 0) {
  87723. return null;
  87724. }
  87725. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  87726. return null;
  87727. }
  87728. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  87729. return null;
  87730. }
  87731. var impostorObjectCenter = impostor.getObjectCenter();
  87732. var direction = impostorObjectCenter.subtract(origin);
  87733. var ray = new BABYLON.Ray(origin, direction, radius);
  87734. this._rays.push(ray);
  87735. var hit = ray.intersectsMesh(impostor.object);
  87736. var contactPoint = hit.pickedPoint;
  87737. if (!contactPoint) {
  87738. return null;
  87739. }
  87740. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  87741. if (distanceFromOrigin > radius) {
  87742. return null;
  87743. }
  87744. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  87745. ? strength
  87746. : strength * (1 - (distanceFromOrigin / radius));
  87747. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  87748. return { force: force, contactPoint: contactPoint };
  87749. };
  87750. /**
  87751. * Disposes the sphere.
  87752. * @param {bolean} force
  87753. */
  87754. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  87755. var _this = this;
  87756. if (force === void 0) { force = true; }
  87757. if (force) {
  87758. this._sphere.dispose();
  87759. }
  87760. else {
  87761. setTimeout(function () {
  87762. if (!_this._dataFetched) {
  87763. _this._sphere.dispose();
  87764. }
  87765. }, 0);
  87766. }
  87767. };
  87768. /*** Helpers ***/
  87769. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  87770. if (!this._sphere) {
  87771. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  87772. this._sphere.isVisible = false;
  87773. }
  87774. };
  87775. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  87776. var impostorObject = impostor.object;
  87777. this._prepareSphere();
  87778. this._sphere.position = origin;
  87779. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  87780. this._sphere._updateBoundingInfo();
  87781. this._sphere.computeWorldMatrix(true);
  87782. return this._sphere.intersectsMesh(impostorObject, true);
  87783. };
  87784. return PhysicsRadialExplosionEvent;
  87785. }());
  87786. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  87787. /***** Gravitational Field *****/
  87788. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  87789. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  87790. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87791. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87792. this._physicsHelper = physicsHelper;
  87793. this._scene = scene;
  87794. this._origin = origin;
  87795. this._radius = radius;
  87796. this._strength = strength;
  87797. this._falloff = falloff;
  87798. this._tickCallback = this._tick.bind(this);
  87799. }
  87800. /**
  87801. * Returns the data related to the gravitational field event (sphere).
  87802. * @returns {PhysicsGravitationalFieldEventData}
  87803. */
  87804. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  87805. this._dataFetched = true;
  87806. return {
  87807. sphere: this._sphere,
  87808. };
  87809. };
  87810. /**
  87811. * Enables the gravitational field.
  87812. */
  87813. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  87814. this._tickCallback.call(this);
  87815. this._scene.registerBeforeRender(this._tickCallback);
  87816. };
  87817. /**
  87818. * Disables the gravitational field.
  87819. */
  87820. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  87821. this._scene.unregisterBeforeRender(this._tickCallback);
  87822. };
  87823. /**
  87824. * Disposes the sphere.
  87825. * @param {bolean} force
  87826. */
  87827. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  87828. var _this = this;
  87829. if (force === void 0) { force = true; }
  87830. if (force) {
  87831. this._sphere.dispose();
  87832. }
  87833. else {
  87834. setTimeout(function () {
  87835. if (!_this._dataFetched) {
  87836. _this._sphere.dispose();
  87837. }
  87838. }, 0);
  87839. }
  87840. };
  87841. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  87842. // Since the params won't change, we fetch the event only once
  87843. if (this._sphere) {
  87844. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  87845. }
  87846. else {
  87847. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  87848. if (radialExplosionEvent) {
  87849. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  87850. }
  87851. }
  87852. };
  87853. return PhysicsGravitationalFieldEvent;
  87854. }());
  87855. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  87856. /***** Updraft *****/
  87857. var PhysicsUpdraftEvent = /** @class */ (function () {
  87858. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  87859. this._scene = _scene;
  87860. this._origin = _origin;
  87861. this._radius = _radius;
  87862. this._strength = _strength;
  87863. this._height = _height;
  87864. this._updraftMode = _updraftMode;
  87865. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  87866. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  87867. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  87868. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87869. this._physicsEngine = this._scene.getPhysicsEngine();
  87870. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  87871. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  87872. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  87873. this._originDirection = this._origin.subtract(this._originTop).normalize();
  87874. }
  87875. this._tickCallback = this._tick.bind(this);
  87876. }
  87877. /**
  87878. * Returns the data related to the updraft event (cylinder).
  87879. * @returns {PhysicsUpdraftEventData}
  87880. */
  87881. PhysicsUpdraftEvent.prototype.getData = function () {
  87882. this._dataFetched = true;
  87883. return {
  87884. cylinder: this._cylinder,
  87885. };
  87886. };
  87887. /**
  87888. * Enables the updraft.
  87889. */
  87890. PhysicsUpdraftEvent.prototype.enable = function () {
  87891. this._tickCallback.call(this);
  87892. this._scene.registerBeforeRender(this._tickCallback);
  87893. };
  87894. /**
  87895. * Disables the cortex.
  87896. */
  87897. PhysicsUpdraftEvent.prototype.disable = function () {
  87898. this._scene.unregisterBeforeRender(this._tickCallback);
  87899. };
  87900. /**
  87901. * Disposes the sphere.
  87902. * @param {bolean} force
  87903. */
  87904. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  87905. var _this = this;
  87906. if (force === void 0) { force = true; }
  87907. if (force) {
  87908. this._cylinder.dispose();
  87909. }
  87910. else {
  87911. setTimeout(function () {
  87912. if (!_this._dataFetched) {
  87913. _this._cylinder.dispose();
  87914. }
  87915. }, 0);
  87916. }
  87917. };
  87918. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  87919. if (impostor.mass === 0) {
  87920. return null;
  87921. }
  87922. if (!this._intersectsWithCylinder(impostor)) {
  87923. return null;
  87924. }
  87925. var impostorObjectCenter = impostor.getObjectCenter();
  87926. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  87927. var direction = this._originDirection;
  87928. }
  87929. else {
  87930. var direction = impostorObjectCenter.subtract(this._originTop);
  87931. }
  87932. var multiplier = this._strength * -1;
  87933. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  87934. return { force: force, contactPoint: impostorObjectCenter };
  87935. };
  87936. PhysicsUpdraftEvent.prototype._tick = function () {
  87937. var _this = this;
  87938. this._physicsEngine.getImpostors().forEach(function (impostor) {
  87939. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  87940. if (!impostorForceAndContactPoint) {
  87941. return;
  87942. }
  87943. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87944. });
  87945. };
  87946. /*** Helpers ***/
  87947. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  87948. if (!this._cylinder) {
  87949. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  87950. height: this._height,
  87951. diameter: this._radius * 2,
  87952. }, this._scene);
  87953. this._cylinder.isVisible = false;
  87954. }
  87955. };
  87956. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  87957. var impostorObject = impostor.object;
  87958. this._prepareCylinder();
  87959. this._cylinder.position = this._cylinderPosition;
  87960. return this._cylinder.intersectsMesh(impostorObject, true);
  87961. };
  87962. return PhysicsUpdraftEvent;
  87963. }());
  87964. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  87965. /***** Vortex *****/
  87966. var PhysicsVortexEvent = /** @class */ (function () {
  87967. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  87968. this._scene = _scene;
  87969. this._origin = _origin;
  87970. this._radius = _radius;
  87971. this._strength = _strength;
  87972. this._height = _height;
  87973. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  87974. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  87975. this._updraftMultiplier = 0.02;
  87976. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  87977. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87978. this._physicsEngine = this._scene.getPhysicsEngine();
  87979. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  87980. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  87981. this._tickCallback = this._tick.bind(this);
  87982. }
  87983. /**
  87984. * Returns the data related to the vortex event (cylinder).
  87985. * @returns {PhysicsVortexEventData}
  87986. */
  87987. PhysicsVortexEvent.prototype.getData = function () {
  87988. this._dataFetched = true;
  87989. return {
  87990. cylinder: this._cylinder,
  87991. };
  87992. };
  87993. /**
  87994. * Enables the vortex.
  87995. */
  87996. PhysicsVortexEvent.prototype.enable = function () {
  87997. this._tickCallback.call(this);
  87998. this._scene.registerBeforeRender(this._tickCallback);
  87999. };
  88000. /**
  88001. * Disables the cortex.
  88002. */
  88003. PhysicsVortexEvent.prototype.disable = function () {
  88004. this._scene.unregisterBeforeRender(this._tickCallback);
  88005. };
  88006. /**
  88007. * Disposes the sphere.
  88008. * @param {bolean} force
  88009. */
  88010. PhysicsVortexEvent.prototype.dispose = function (force) {
  88011. var _this = this;
  88012. if (force === void 0) { force = true; }
  88013. if (force) {
  88014. this._cylinder.dispose();
  88015. }
  88016. else {
  88017. setTimeout(function () {
  88018. if (!_this._dataFetched) {
  88019. _this._cylinder.dispose();
  88020. }
  88021. }, 0);
  88022. }
  88023. };
  88024. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  88025. if (impostor.mass === 0) {
  88026. return null;
  88027. }
  88028. if (!this._intersectsWithCylinder(impostor)) {
  88029. return null;
  88030. }
  88031. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  88032. return null;
  88033. }
  88034. var impostorObjectCenter = impostor.getObjectCenter();
  88035. 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)
  88036. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  88037. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  88038. var hit = ray.intersectsMesh(impostor.object);
  88039. var contactPoint = hit.pickedPoint;
  88040. if (!contactPoint) {
  88041. return null;
  88042. }
  88043. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  88044. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  88045. var directionToOrigin = contactPoint.normalize();
  88046. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  88047. directionToOrigin = directionToOrigin.negate();
  88048. }
  88049. // TODO: find a more physically based solution
  88050. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  88051. var forceX = directionToOrigin.x * this._strength / 8;
  88052. var forceY = directionToOrigin.y * this._updraftMultiplier;
  88053. var forceZ = directionToOrigin.z * this._strength / 8;
  88054. }
  88055. else {
  88056. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  88057. var forceY = this._originTop.y * this._updraftMultiplier;
  88058. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  88059. }
  88060. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  88061. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  88062. return { force: force, contactPoint: impostorObjectCenter };
  88063. };
  88064. PhysicsVortexEvent.prototype._tick = function () {
  88065. var _this = this;
  88066. this._physicsEngine.getImpostors().forEach(function (impostor) {
  88067. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  88068. if (!impostorForceAndContactPoint) {
  88069. return;
  88070. }
  88071. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88072. });
  88073. };
  88074. /*** Helpers ***/
  88075. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  88076. if (!this._cylinder) {
  88077. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  88078. height: this._height,
  88079. diameter: this._radius * 2,
  88080. }, this._scene);
  88081. this._cylinder.isVisible = false;
  88082. }
  88083. };
  88084. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  88085. var impostorObject = impostor.object;
  88086. this._prepareCylinder();
  88087. this._cylinder.position = this._cylinderPosition;
  88088. return this._cylinder.intersectsMesh(impostorObject, true);
  88089. };
  88090. return PhysicsVortexEvent;
  88091. }());
  88092. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  88093. /***** Enums *****/
  88094. /**
  88095. * The strenght of the force in correspondence to the distance of the affected object
  88096. */
  88097. var PhysicsRadialImpulseFalloff;
  88098. (function (PhysicsRadialImpulseFalloff) {
  88099. /** Defines that impulse is constant in strength across it's whole radius */
  88100. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  88101. /** DEfines that impulse gets weaker if it's further from the origin */
  88102. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  88103. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  88104. /**
  88105. * The strenght of the force in correspondence to the distance of the affected object
  88106. */
  88107. var PhysicsUpdraftMode;
  88108. (function (PhysicsUpdraftMode) {
  88109. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  88110. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  88111. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  88112. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  88113. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  88114. })(BABYLON || (BABYLON = {}));
  88115. //# sourceMappingURL=babylon.physicsHelper.js.map
  88116. var BABYLON;
  88117. (function (BABYLON) {
  88118. var CannonJSPlugin = /** @class */ (function () {
  88119. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  88120. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  88121. if (iterations === void 0) { iterations = 10; }
  88122. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  88123. this.name = "CannonJSPlugin";
  88124. this._physicsMaterials = new Array();
  88125. this._fixedTimeStep = 1 / 60;
  88126. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  88127. this.BJSCANNON = CANNON;
  88128. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  88129. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  88130. this._tmpPosition = BABYLON.Vector3.Zero();
  88131. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  88132. this._tmpUnityRotation = new BABYLON.Quaternion();
  88133. if (!this.isSupported()) {
  88134. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  88135. return;
  88136. }
  88137. this._extendNamespace();
  88138. this.world = new this.BJSCANNON.World();
  88139. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  88140. this.world.solver.iterations = iterations;
  88141. }
  88142. CannonJSPlugin.prototype.setGravity = function (gravity) {
  88143. this.world.gravity.copy(gravity);
  88144. };
  88145. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  88146. this._fixedTimeStep = timeStep;
  88147. };
  88148. CannonJSPlugin.prototype.getTimeStep = function () {
  88149. return this._fixedTimeStep;
  88150. };
  88151. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  88152. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  88153. };
  88154. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  88155. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  88156. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  88157. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  88158. };
  88159. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  88160. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  88161. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  88162. impostor.physicsBody.applyForce(impulse, worldPoint);
  88163. };
  88164. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  88165. //parent-child relationship. Does this impostor has a parent impostor?
  88166. if (impostor.parent) {
  88167. if (impostor.physicsBody) {
  88168. this.removePhysicsBody(impostor);
  88169. //TODO is that needed?
  88170. impostor.forceUpdate();
  88171. }
  88172. return;
  88173. }
  88174. //should a new body be created for this impostor?
  88175. if (impostor.isBodyInitRequired()) {
  88176. var shape = this._createShape(impostor);
  88177. //unregister events, if body is being changed
  88178. var oldBody = impostor.physicsBody;
  88179. if (oldBody) {
  88180. this.removePhysicsBody(impostor);
  88181. }
  88182. //create the body and material
  88183. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  88184. var bodyCreationObject = {
  88185. mass: impostor.getParam("mass"),
  88186. material: material
  88187. };
  88188. // A simple extend, in case native options were used.
  88189. var nativeOptions = impostor.getParam("nativeOptions");
  88190. for (var key in nativeOptions) {
  88191. if (nativeOptions.hasOwnProperty(key)) {
  88192. bodyCreationObject[key] = nativeOptions[key];
  88193. }
  88194. }
  88195. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  88196. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  88197. this.world.addEventListener("preStep", impostor.beforeStep);
  88198. this.world.addEventListener("postStep", impostor.afterStep);
  88199. impostor.physicsBody.addShape(shape);
  88200. this.world.add(impostor.physicsBody);
  88201. //try to keep the body moving in the right direction by taking old properties.
  88202. //Should be tested!
  88203. if (oldBody) {
  88204. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  88205. impostor.physicsBody[param].copy(oldBody[param]);
  88206. });
  88207. }
  88208. this._processChildMeshes(impostor);
  88209. }
  88210. //now update the body's transformation
  88211. this._updatePhysicsBodyTransformation(impostor);
  88212. };
  88213. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  88214. var _this = this;
  88215. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  88216. var currentRotation = mainImpostor.object.rotationQuaternion;
  88217. if (meshChildren.length) {
  88218. var processMesh = function (localPosition, mesh) {
  88219. if (!currentRotation || !mesh.rotationQuaternion) {
  88220. return;
  88221. }
  88222. var childImpostor = mesh.getPhysicsImpostor();
  88223. if (childImpostor) {
  88224. var parent = childImpostor.parent;
  88225. if (parent !== mainImpostor) {
  88226. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  88227. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  88228. if (childImpostor.physicsBody) {
  88229. _this.removePhysicsBody(childImpostor);
  88230. childImpostor.physicsBody = null;
  88231. }
  88232. childImpostor.parent = mainImpostor;
  88233. childImpostor.resetUpdateFlags();
  88234. 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));
  88235. //Add the mass of the children.
  88236. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  88237. }
  88238. }
  88239. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  88240. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  88241. };
  88242. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  88243. }
  88244. };
  88245. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  88246. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  88247. this.world.removeEventListener("preStep", impostor.beforeStep);
  88248. this.world.removeEventListener("postStep", impostor.afterStep);
  88249. this.world.remove(impostor.physicsBody);
  88250. };
  88251. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  88252. var mainBody = impostorJoint.mainImpostor.physicsBody;
  88253. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  88254. if (!mainBody || !connectedBody) {
  88255. return;
  88256. }
  88257. var constraint;
  88258. var jointData = impostorJoint.joint.jointData;
  88259. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  88260. var constraintData = {
  88261. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  88262. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  88263. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  88264. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  88265. maxForce: jointData.nativeParams.maxForce,
  88266. collideConnected: !!jointData.collision
  88267. };
  88268. switch (impostorJoint.joint.type) {
  88269. case BABYLON.PhysicsJoint.HingeJoint:
  88270. case BABYLON.PhysicsJoint.Hinge2Joint:
  88271. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  88272. break;
  88273. case BABYLON.PhysicsJoint.DistanceJoint:
  88274. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  88275. break;
  88276. case BABYLON.PhysicsJoint.SpringJoint:
  88277. var springData = jointData;
  88278. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  88279. restLength: springData.length,
  88280. stiffness: springData.stiffness,
  88281. damping: springData.damping,
  88282. localAnchorA: constraintData.pivotA,
  88283. localAnchorB: constraintData.pivotB
  88284. });
  88285. break;
  88286. case BABYLON.PhysicsJoint.LockJoint:
  88287. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  88288. break;
  88289. case BABYLON.PhysicsJoint.PointToPointJoint:
  88290. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  88291. default:
  88292. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  88293. break;
  88294. }
  88295. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  88296. constraint.collideConnected = !!jointData.collision;
  88297. impostorJoint.joint.physicsJoint = constraint;
  88298. //don't add spring as constraint, as it is not one.
  88299. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  88300. this.world.addConstraint(constraint);
  88301. }
  88302. else {
  88303. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  88304. constraint.applyForce();
  88305. });
  88306. }
  88307. };
  88308. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  88309. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  88310. };
  88311. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  88312. var index;
  88313. var mat;
  88314. for (index = 0; index < this._physicsMaterials.length; index++) {
  88315. mat = this._physicsMaterials[index];
  88316. if (mat.friction === friction && mat.restitution === restitution) {
  88317. return mat;
  88318. }
  88319. }
  88320. var currentMat = new this.BJSCANNON.Material(name);
  88321. currentMat.friction = friction;
  88322. currentMat.restitution = restitution;
  88323. this._physicsMaterials.push(currentMat);
  88324. return currentMat;
  88325. };
  88326. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  88327. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  88328. };
  88329. CannonJSPlugin.prototype._createShape = function (impostor) {
  88330. var object = impostor.object;
  88331. var returnValue;
  88332. var extendSize = impostor.getObjectExtendSize();
  88333. switch (impostor.type) {
  88334. case BABYLON.PhysicsImpostor.SphereImpostor:
  88335. var radiusX = extendSize.x;
  88336. var radiusY = extendSize.y;
  88337. var radiusZ = extendSize.z;
  88338. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  88339. break;
  88340. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  88341. case BABYLON.PhysicsImpostor.CylinderImpostor:
  88342. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  88343. break;
  88344. case BABYLON.PhysicsImpostor.BoxImpostor:
  88345. var box = extendSize.scale(0.5);
  88346. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  88347. break;
  88348. case BABYLON.PhysicsImpostor.PlaneImpostor:
  88349. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  88350. returnValue = new this.BJSCANNON.Plane();
  88351. break;
  88352. case BABYLON.PhysicsImpostor.MeshImpostor:
  88353. // should transform the vertex data to world coordinates!!
  88354. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  88355. var rawFaces = object.getIndices ? object.getIndices() : [];
  88356. if (!rawVerts)
  88357. return;
  88358. // get only scale! so the object could transform correctly.
  88359. var oldPosition = object.position.clone();
  88360. var oldRotation = object.rotation && object.rotation.clone();
  88361. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  88362. object.position.copyFromFloats(0, 0, 0);
  88363. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  88364. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  88365. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  88366. var transform = object.computeWorldMatrix(true);
  88367. // convert rawVerts to object space
  88368. var temp = new Array();
  88369. var index;
  88370. for (index = 0; index < rawVerts.length; index += 3) {
  88371. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  88372. }
  88373. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  88374. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  88375. //now set back the transformation!
  88376. object.position.copyFrom(oldPosition);
  88377. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  88378. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  88379. break;
  88380. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  88381. var oldPosition2 = object.position.clone();
  88382. var oldRotation2 = object.rotation && object.rotation.clone();
  88383. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  88384. object.position.copyFromFloats(0, 0, 0);
  88385. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  88386. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  88387. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  88388. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  88389. returnValue = this._createHeightmap(object);
  88390. object.position.copyFrom(oldPosition2);
  88391. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  88392. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  88393. object.computeWorldMatrix(true);
  88394. break;
  88395. case BABYLON.PhysicsImpostor.ParticleImpostor:
  88396. returnValue = new this.BJSCANNON.Particle();
  88397. break;
  88398. }
  88399. return returnValue;
  88400. };
  88401. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  88402. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  88403. var transform = object.computeWorldMatrix(true);
  88404. // convert rawVerts to object space
  88405. var temp = new Array();
  88406. var index;
  88407. for (index = 0; index < pos.length; index += 3) {
  88408. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  88409. }
  88410. pos = temp;
  88411. var matrix = new Array();
  88412. //For now pointDepth will not be used and will be automatically calculated.
  88413. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  88414. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  88415. var boundingInfo = object.getBoundingInfo();
  88416. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  88417. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  88418. var elementSize = dim * 2 / arraySize;
  88419. for (var i = 0; i < pos.length; i = i + 3) {
  88420. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  88421. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  88422. var y = -pos[i + 2] + minY;
  88423. if (!matrix[x]) {
  88424. matrix[x] = [];
  88425. }
  88426. if (!matrix[x][z]) {
  88427. matrix[x][z] = y;
  88428. }
  88429. matrix[x][z] = Math.max(y, matrix[x][z]);
  88430. }
  88431. for (var x = 0; x <= arraySize; ++x) {
  88432. if (!matrix[x]) {
  88433. var loc = 1;
  88434. while (!matrix[(x + loc) % arraySize]) {
  88435. loc++;
  88436. }
  88437. matrix[x] = matrix[(x + loc) % arraySize].slice();
  88438. //console.log("missing x", x);
  88439. }
  88440. for (var z = 0; z <= arraySize; ++z) {
  88441. if (!matrix[x][z]) {
  88442. var loc = 1;
  88443. var newValue;
  88444. while (newValue === undefined) {
  88445. newValue = matrix[x][(z + loc++) % arraySize];
  88446. }
  88447. matrix[x][z] = newValue;
  88448. }
  88449. }
  88450. }
  88451. var shape = new this.BJSCANNON.Heightfield(matrix, {
  88452. elementSize: elementSize
  88453. });
  88454. //For future reference, needed for body transformation
  88455. shape.minY = minY;
  88456. return shape;
  88457. };
  88458. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  88459. var object = impostor.object;
  88460. //make sure it is updated...
  88461. object.computeWorldMatrix && object.computeWorldMatrix(true);
  88462. // The delta between the mesh position and the mesh bounding box center
  88463. var bInfo = object.getBoundingInfo();
  88464. if (!bInfo)
  88465. return;
  88466. var center = impostor.getObjectCenter();
  88467. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  88468. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  88469. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  88470. this._tmpPosition.copyFrom(center);
  88471. var quaternion = object.rotationQuaternion;
  88472. if (!quaternion) {
  88473. return;
  88474. }
  88475. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  88476. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  88477. //-90 DEG in X, precalculated
  88478. quaternion = quaternion.multiply(this._minus90X);
  88479. //Invert! (Precalculated, 90 deg in X)
  88480. //No need to clone. this will never change.
  88481. impostor.setDeltaRotation(this._plus90X);
  88482. }
  88483. //If it is a heightfield, if should be centered.
  88484. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  88485. var mesh = object;
  88486. var boundingInfo = mesh.getBoundingInfo();
  88487. //calculate the correct body position:
  88488. var rotationQuaternion = mesh.rotationQuaternion;
  88489. mesh.rotationQuaternion = this._tmpUnityRotation;
  88490. mesh.computeWorldMatrix(true);
  88491. //get original center with no rotation
  88492. var c = center.clone();
  88493. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  88494. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  88495. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  88496. mesh.setPreTransformMatrix(p);
  88497. mesh.computeWorldMatrix(true);
  88498. //calculate the translation
  88499. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  88500. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  88501. //add it inverted to the delta
  88502. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  88503. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  88504. //rotation is back
  88505. mesh.rotationQuaternion = rotationQuaternion;
  88506. mesh.setPreTransformMatrix(oldPivot);
  88507. mesh.computeWorldMatrix(true);
  88508. }
  88509. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  88510. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  88511. //this._tmpPosition.copyFrom(object.position);
  88512. }
  88513. impostor.setDeltaPosition(this._tmpDeltaPosition);
  88514. //Now update the impostor object
  88515. impostor.physicsBody.position.copy(this._tmpPosition);
  88516. impostor.physicsBody.quaternion.copy(quaternion);
  88517. };
  88518. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  88519. impostor.object.position.copyFrom(impostor.physicsBody.position);
  88520. if (impostor.object.rotationQuaternion) {
  88521. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  88522. }
  88523. };
  88524. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  88525. impostor.physicsBody.position.copy(newPosition);
  88526. impostor.physicsBody.quaternion.copy(newRotation);
  88527. };
  88528. CannonJSPlugin.prototype.isSupported = function () {
  88529. return this.BJSCANNON !== undefined;
  88530. };
  88531. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  88532. impostor.physicsBody.velocity.copy(velocity);
  88533. };
  88534. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  88535. impostor.physicsBody.angularVelocity.copy(velocity);
  88536. };
  88537. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  88538. var v = impostor.physicsBody.velocity;
  88539. if (!v) {
  88540. return null;
  88541. }
  88542. return new BABYLON.Vector3(v.x, v.y, v.z);
  88543. };
  88544. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  88545. var v = impostor.physicsBody.angularVelocity;
  88546. if (!v) {
  88547. return null;
  88548. }
  88549. return new BABYLON.Vector3(v.x, v.y, v.z);
  88550. };
  88551. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  88552. impostor.physicsBody.mass = mass;
  88553. impostor.physicsBody.updateMassProperties();
  88554. };
  88555. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  88556. return impostor.physicsBody.mass;
  88557. };
  88558. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  88559. return impostor.physicsBody.material.friction;
  88560. };
  88561. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  88562. impostor.physicsBody.material.friction = friction;
  88563. };
  88564. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  88565. return impostor.physicsBody.material.restitution;
  88566. };
  88567. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  88568. impostor.physicsBody.material.restitution = restitution;
  88569. };
  88570. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  88571. impostor.physicsBody.sleep();
  88572. };
  88573. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  88574. impostor.physicsBody.wakeUp();
  88575. };
  88576. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  88577. joint.physicsJoint.distance = maxDistance;
  88578. };
  88579. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  88580. // if (!motorIndex) {
  88581. // joint.physicsJoint.enableMotor();
  88582. // }
  88583. // }
  88584. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  88585. // if (!motorIndex) {
  88586. // joint.physicsJoint.disableMotor();
  88587. // }
  88588. // }
  88589. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  88590. if (!motorIndex) {
  88591. joint.physicsJoint.enableMotor();
  88592. joint.physicsJoint.setMotorSpeed(speed);
  88593. if (maxForce) {
  88594. this.setLimit(joint, maxForce);
  88595. }
  88596. }
  88597. };
  88598. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  88599. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  88600. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  88601. };
  88602. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  88603. var body = impostor.physicsBody;
  88604. mesh.position.x = body.position.x;
  88605. mesh.position.y = body.position.y;
  88606. mesh.position.z = body.position.z;
  88607. if (mesh.rotationQuaternion) {
  88608. mesh.rotationQuaternion.x = body.quaternion.x;
  88609. mesh.rotationQuaternion.y = body.quaternion.y;
  88610. mesh.rotationQuaternion.z = body.quaternion.z;
  88611. mesh.rotationQuaternion.w = body.quaternion.w;
  88612. }
  88613. };
  88614. CannonJSPlugin.prototype.getRadius = function (impostor) {
  88615. var shape = impostor.physicsBody.shapes[0];
  88616. return shape.boundingSphereRadius;
  88617. };
  88618. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  88619. var shape = impostor.physicsBody.shapes[0];
  88620. result.x = shape.halfExtents.x * 2;
  88621. result.y = shape.halfExtents.y * 2;
  88622. result.z = shape.halfExtents.z * 2;
  88623. };
  88624. CannonJSPlugin.prototype.dispose = function () {
  88625. };
  88626. CannonJSPlugin.prototype._extendNamespace = function () {
  88627. //this will force cannon to execute at least one step when using interpolation
  88628. var step_tmp1 = new this.BJSCANNON.Vec3();
  88629. var Engine = this.BJSCANNON;
  88630. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  88631. maxSubSteps = maxSubSteps || 10;
  88632. timeSinceLastCalled = timeSinceLastCalled || 0;
  88633. if (timeSinceLastCalled === 0) {
  88634. this.internalStep(dt);
  88635. this.time += dt;
  88636. }
  88637. else {
  88638. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  88639. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  88640. var t0 = performance.now();
  88641. for (var i = 0; i !== internalSteps; i++) {
  88642. this.internalStep(dt);
  88643. if (performance.now() - t0 > dt * 1000) {
  88644. break;
  88645. }
  88646. }
  88647. this.time += timeSinceLastCalled;
  88648. var h = this.time % dt;
  88649. var h_div_dt = h / dt;
  88650. var interpvelo = step_tmp1;
  88651. var bodies = this.bodies;
  88652. for (var j = 0; j !== bodies.length; j++) {
  88653. var b = bodies[j];
  88654. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  88655. b.position.vsub(b.previousPosition, interpvelo);
  88656. interpvelo.scale(h_div_dt, interpvelo);
  88657. b.position.vadd(interpvelo, b.interpolatedPosition);
  88658. }
  88659. else {
  88660. b.interpolatedPosition.copy(b.position);
  88661. b.interpolatedQuaternion.copy(b.quaternion);
  88662. }
  88663. }
  88664. }
  88665. };
  88666. };
  88667. return CannonJSPlugin;
  88668. }());
  88669. BABYLON.CannonJSPlugin = CannonJSPlugin;
  88670. })(BABYLON || (BABYLON = {}));
  88671. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  88672. var BABYLON;
  88673. (function (BABYLON) {
  88674. var OimoJSPlugin = /** @class */ (function () {
  88675. function OimoJSPlugin(iterations) {
  88676. this.name = "OimoJSPlugin";
  88677. this._tmpImpostorsArray = [];
  88678. this._tmpPositionVector = BABYLON.Vector3.Zero();
  88679. this.BJSOIMO = OIMO;
  88680. this.world = new this.BJSOIMO.World({
  88681. iterations: iterations
  88682. });
  88683. this.world.clear();
  88684. }
  88685. OimoJSPlugin.prototype.setGravity = function (gravity) {
  88686. this.world.gravity.copy(gravity);
  88687. };
  88688. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  88689. this.world.timeStep = timeStep;
  88690. };
  88691. OimoJSPlugin.prototype.getTimeStep = function () {
  88692. return this.world.timeStep;
  88693. };
  88694. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  88695. var _this = this;
  88696. impostors.forEach(function (impostor) {
  88697. impostor.beforeStep();
  88698. });
  88699. this.world.step();
  88700. impostors.forEach(function (impostor) {
  88701. impostor.afterStep();
  88702. //update the ordered impostors array
  88703. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  88704. });
  88705. //check for collisions
  88706. var contact = this.world.contacts;
  88707. while (contact !== null) {
  88708. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  88709. contact = contact.next;
  88710. continue;
  88711. }
  88712. //is this body colliding with any other? get the impostor
  88713. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  88714. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  88715. if (!mainImpostor || !collidingImpostor) {
  88716. contact = contact.next;
  88717. continue;
  88718. }
  88719. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  88720. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  88721. contact = contact.next;
  88722. }
  88723. };
  88724. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  88725. var mass = impostor.physicsBody.mass;
  88726. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  88727. };
  88728. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  88729. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  88730. this.applyImpulse(impostor, force, contactPoint);
  88731. };
  88732. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  88733. var _this = this;
  88734. //parent-child relationship. Does this impostor has a parent impostor?
  88735. if (impostor.parent) {
  88736. if (impostor.physicsBody) {
  88737. this.removePhysicsBody(impostor);
  88738. //TODO is that needed?
  88739. impostor.forceUpdate();
  88740. }
  88741. return;
  88742. }
  88743. if (impostor.isBodyInitRequired()) {
  88744. var bodyConfig = {
  88745. name: impostor.uniqueId,
  88746. //Oimo must have mass, also for static objects.
  88747. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  88748. size: [],
  88749. type: [],
  88750. pos: [],
  88751. posShape: [],
  88752. rot: [],
  88753. rotShape: [],
  88754. move: impostor.getParam("mass") !== 0,
  88755. density: impostor.getParam("mass"),
  88756. friction: impostor.getParam("friction"),
  88757. restitution: impostor.getParam("restitution"),
  88758. //Supporting older versions of Oimo
  88759. world: this.world
  88760. };
  88761. var impostors = [impostor];
  88762. var addToArray = function (parent) {
  88763. if (!parent.getChildMeshes)
  88764. return;
  88765. parent.getChildMeshes().forEach(function (m) {
  88766. if (m.physicsImpostor) {
  88767. impostors.push(m.physicsImpostor);
  88768. //m.physicsImpostor._init();
  88769. }
  88770. });
  88771. };
  88772. addToArray(impostor.object);
  88773. var checkWithEpsilon_1 = function (value) {
  88774. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  88775. };
  88776. var globalQuaternion_1 = new BABYLON.Quaternion();
  88777. impostors.forEach(function (i) {
  88778. if (!i.object.rotationQuaternion) {
  88779. return;
  88780. }
  88781. //get the correct bounding box
  88782. var oldQuaternion = i.object.rotationQuaternion;
  88783. globalQuaternion_1 = oldQuaternion.clone();
  88784. var rot = oldQuaternion.toEulerAngles();
  88785. var extendSize = i.getObjectExtendSize();
  88786. var radToDeg = 57.295779513082320876;
  88787. if (i === impostor) {
  88788. var center = impostor.getObjectCenter();
  88789. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  88790. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  88791. //Can also use Array.prototype.push.apply
  88792. bodyConfig.pos.push(center.x);
  88793. bodyConfig.pos.push(center.y);
  88794. bodyConfig.pos.push(center.z);
  88795. bodyConfig.posShape.push(0, 0, 0);
  88796. //tmp solution
  88797. bodyConfig.rot.push(0);
  88798. bodyConfig.rot.push(0);
  88799. bodyConfig.rot.push(0);
  88800. bodyConfig.rotShape.push(0, 0, 0);
  88801. }
  88802. else {
  88803. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  88804. bodyConfig.posShape.push(localPosition.x);
  88805. bodyConfig.posShape.push(localPosition.y);
  88806. bodyConfig.posShape.push(localPosition.z);
  88807. bodyConfig.pos.push(0, 0, 0);
  88808. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  88809. bodyConfig.rot.push(0);
  88810. bodyConfig.rot.push(0);
  88811. bodyConfig.rot.push(0);
  88812. bodyConfig.rotShape.push(rot.x * radToDeg);
  88813. bodyConfig.rotShape.push(rot.y * radToDeg);
  88814. bodyConfig.rotShape.push(rot.z * radToDeg);
  88815. }
  88816. // register mesh
  88817. switch (i.type) {
  88818. case BABYLON.PhysicsImpostor.ParticleImpostor:
  88819. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  88820. case BABYLON.PhysicsImpostor.SphereImpostor:
  88821. var radiusX = extendSize.x;
  88822. var radiusY = extendSize.y;
  88823. var radiusZ = extendSize.z;
  88824. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  88825. bodyConfig.type.push('sphere');
  88826. //due to the way oimo works with compounds, add 3 times
  88827. bodyConfig.size.push(size);
  88828. bodyConfig.size.push(size);
  88829. bodyConfig.size.push(size);
  88830. break;
  88831. case BABYLON.PhysicsImpostor.CylinderImpostor:
  88832. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  88833. var sizeY = checkWithEpsilon_1(extendSize.y);
  88834. bodyConfig.type.push('cylinder');
  88835. bodyConfig.size.push(sizeX);
  88836. bodyConfig.size.push(sizeY);
  88837. //due to the way oimo works with compounds, add one more value.
  88838. bodyConfig.size.push(sizeY);
  88839. break;
  88840. case BABYLON.PhysicsImpostor.PlaneImpostor:
  88841. case BABYLON.PhysicsImpostor.BoxImpostor:
  88842. default:
  88843. var sizeX = checkWithEpsilon_1(extendSize.x);
  88844. var sizeY = checkWithEpsilon_1(extendSize.y);
  88845. var sizeZ = checkWithEpsilon_1(extendSize.z);
  88846. bodyConfig.type.push('box');
  88847. //if (i === impostor) {
  88848. bodyConfig.size.push(sizeX);
  88849. bodyConfig.size.push(sizeY);
  88850. bodyConfig.size.push(sizeZ);
  88851. //} else {
  88852. // bodyConfig.size.push(0,0,0);
  88853. //}
  88854. break;
  88855. }
  88856. //actually not needed, but hey...
  88857. i.object.rotationQuaternion = oldQuaternion;
  88858. });
  88859. impostor.physicsBody = this.world.add(bodyConfig);
  88860. // set the quaternion, ignoring the previously defined (euler) rotation
  88861. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  88862. // update with delta 0, so the body will reveive the new rotation.
  88863. impostor.physicsBody.updatePosition(0);
  88864. }
  88865. else {
  88866. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  88867. }
  88868. impostor.setDeltaPosition(this._tmpPositionVector);
  88869. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  88870. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  88871. };
  88872. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  88873. //impostor.physicsBody.dispose();
  88874. //Same as : (older oimo versions)
  88875. this.world.removeRigidBody(impostor.physicsBody);
  88876. };
  88877. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  88878. var mainBody = impostorJoint.mainImpostor.physicsBody;
  88879. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  88880. if (!mainBody || !connectedBody) {
  88881. return;
  88882. }
  88883. var jointData = impostorJoint.joint.jointData;
  88884. var options = jointData.nativeParams || {};
  88885. var type;
  88886. var nativeJointData = {
  88887. body1: mainBody,
  88888. body2: connectedBody,
  88889. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  88890. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  88891. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  88892. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  88893. min: options.min,
  88894. max: options.max,
  88895. collision: options.collision || jointData.collision,
  88896. spring: options.spring,
  88897. //supporting older version of Oimo
  88898. world: this.world
  88899. };
  88900. switch (impostorJoint.joint.type) {
  88901. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  88902. type = "jointBall";
  88903. break;
  88904. case BABYLON.PhysicsJoint.SpringJoint:
  88905. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  88906. var springData = jointData;
  88907. nativeJointData.min = springData.length || nativeJointData.min;
  88908. //Max should also be set, just make sure it is at least min
  88909. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  88910. case BABYLON.PhysicsJoint.DistanceJoint:
  88911. type = "jointDistance";
  88912. nativeJointData.max = jointData.maxDistance;
  88913. break;
  88914. case BABYLON.PhysicsJoint.PrismaticJoint:
  88915. type = "jointPrisme";
  88916. break;
  88917. case BABYLON.PhysicsJoint.SliderJoint:
  88918. type = "jointSlide";
  88919. break;
  88920. case BABYLON.PhysicsJoint.WheelJoint:
  88921. type = "jointWheel";
  88922. break;
  88923. case BABYLON.PhysicsJoint.HingeJoint:
  88924. default:
  88925. type = "jointHinge";
  88926. break;
  88927. }
  88928. nativeJointData.type = type;
  88929. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  88930. };
  88931. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  88932. //Bug in Oimo prevents us from disposing a joint in the playground
  88933. //joint.joint.physicsJoint.dispose();
  88934. //So we will bruteforce it!
  88935. try {
  88936. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  88937. }
  88938. catch (e) {
  88939. BABYLON.Tools.Warn(e);
  88940. }
  88941. };
  88942. OimoJSPlugin.prototype.isSupported = function () {
  88943. return this.BJSOIMO !== undefined;
  88944. };
  88945. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  88946. if (!impostor.physicsBody.sleeping) {
  88947. //TODO check that
  88948. /*if (impostor.physicsBody.shapes.next) {
  88949. var parentShape = this._getLastShape(impostor.physicsBody);
  88950. impostor.object.position.copyFrom(parentShape.position);
  88951. console.log(parentShape.position);
  88952. } else {*/
  88953. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  88954. //}
  88955. if (impostor.object.rotationQuaternion) {
  88956. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  88957. }
  88958. }
  88959. };
  88960. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  88961. var body = impostor.physicsBody;
  88962. body.position.copy(newPosition);
  88963. body.orientation.copy(newRotation);
  88964. body.syncShapes();
  88965. body.awake();
  88966. };
  88967. /*private _getLastShape(body: any): any {
  88968. var lastShape = body.shapes;
  88969. while (lastShape.next) {
  88970. lastShape = lastShape.next;
  88971. }
  88972. return lastShape;
  88973. }*/
  88974. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  88975. impostor.physicsBody.linearVelocity.copy(velocity);
  88976. };
  88977. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  88978. impostor.physicsBody.angularVelocity.copy(velocity);
  88979. };
  88980. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  88981. var v = impostor.physicsBody.linearVelocity;
  88982. if (!v) {
  88983. return null;
  88984. }
  88985. return new BABYLON.Vector3(v.x, v.y, v.z);
  88986. };
  88987. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  88988. var v = impostor.physicsBody.angularVelocity;
  88989. if (!v) {
  88990. return null;
  88991. }
  88992. return new BABYLON.Vector3(v.x, v.y, v.z);
  88993. };
  88994. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  88995. var staticBody = mass === 0;
  88996. //this will actually set the body's density and not its mass.
  88997. //But this is how oimo treats the mass variable.
  88998. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  88999. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  89000. };
  89001. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  89002. return impostor.physicsBody.shapes.density;
  89003. };
  89004. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  89005. return impostor.physicsBody.shapes.friction;
  89006. };
  89007. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  89008. impostor.physicsBody.shapes.friction = friction;
  89009. };
  89010. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  89011. return impostor.physicsBody.shapes.restitution;
  89012. };
  89013. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  89014. impostor.physicsBody.shapes.restitution = restitution;
  89015. };
  89016. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  89017. impostor.physicsBody.sleep();
  89018. };
  89019. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  89020. impostor.physicsBody.awake();
  89021. };
  89022. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  89023. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  89024. if (minDistance !== void 0) {
  89025. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  89026. }
  89027. };
  89028. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  89029. //TODO separate rotational and transational motors.
  89030. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  89031. if (motor) {
  89032. motor.setMotor(speed, maxForce);
  89033. }
  89034. };
  89035. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  89036. //TODO separate rotational and transational motors.
  89037. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  89038. if (motor) {
  89039. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  89040. }
  89041. };
  89042. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  89043. var body = impostor.physicsBody;
  89044. mesh.position.x = body.position.x;
  89045. mesh.position.y = body.position.y;
  89046. mesh.position.z = body.position.z;
  89047. if (mesh.rotationQuaternion) {
  89048. mesh.rotationQuaternion.x = body.orientation.x;
  89049. mesh.rotationQuaternion.y = body.orientation.y;
  89050. mesh.rotationQuaternion.z = body.orientation.z;
  89051. mesh.rotationQuaternion.w = body.orientation.s;
  89052. }
  89053. };
  89054. OimoJSPlugin.prototype.getRadius = function (impostor) {
  89055. return impostor.physicsBody.shapes.radius;
  89056. };
  89057. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  89058. var shape = impostor.physicsBody.shapes;
  89059. result.x = shape.halfWidth * 2;
  89060. result.y = shape.halfHeight * 2;
  89061. result.z = shape.halfDepth * 2;
  89062. };
  89063. OimoJSPlugin.prototype.dispose = function () {
  89064. this.world.clear();
  89065. };
  89066. return OimoJSPlugin;
  89067. }());
  89068. BABYLON.OimoJSPlugin = OimoJSPlugin;
  89069. })(BABYLON || (BABYLON = {}));
  89070. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  89071. var BABYLON;
  89072. (function (BABYLON) {
  89073. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  89074. // All values and structures referenced from:
  89075. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  89076. var DDS_MAGIC = 0x20534444;
  89077. var
  89078. //DDSD_CAPS = 0x1,
  89079. //DDSD_HEIGHT = 0x2,
  89080. //DDSD_WIDTH = 0x4,
  89081. //DDSD_PITCH = 0x8,
  89082. //DDSD_PIXELFORMAT = 0x1000,
  89083. DDSD_MIPMAPCOUNT = 0x20000;
  89084. //DDSD_LINEARSIZE = 0x80000,
  89085. //DDSD_DEPTH = 0x800000;
  89086. // var DDSCAPS_COMPLEX = 0x8,
  89087. // DDSCAPS_MIPMAP = 0x400000,
  89088. // DDSCAPS_TEXTURE = 0x1000;
  89089. var DDSCAPS2_CUBEMAP = 0x200;
  89090. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  89091. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  89092. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  89093. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  89094. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  89095. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  89096. // DDSCAPS2_VOLUME = 0x200000;
  89097. var
  89098. //DDPF_ALPHAPIXELS = 0x1,
  89099. //DDPF_ALPHA = 0x2,
  89100. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  89101. //DDPF_YUV = 0x200,
  89102. DDPF_LUMINANCE = 0x20000;
  89103. function FourCCToInt32(value) {
  89104. return value.charCodeAt(0) +
  89105. (value.charCodeAt(1) << 8) +
  89106. (value.charCodeAt(2) << 16) +
  89107. (value.charCodeAt(3) << 24);
  89108. }
  89109. function Int32ToFourCC(value) {
  89110. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  89111. }
  89112. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  89113. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  89114. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  89115. var FOURCC_DX10 = FourCCToInt32("DX10");
  89116. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  89117. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  89118. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  89119. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  89120. var headerLengthInt = 31; // The header length in 32 bit ints
  89121. // Offsets into the header array
  89122. var off_magic = 0;
  89123. var off_size = 1;
  89124. var off_flags = 2;
  89125. var off_height = 3;
  89126. var off_width = 4;
  89127. var off_mipmapCount = 7;
  89128. var off_pfFlags = 20;
  89129. var off_pfFourCC = 21;
  89130. var off_RGBbpp = 22;
  89131. var off_RMask = 23;
  89132. var off_GMask = 24;
  89133. var off_BMask = 25;
  89134. var off_AMask = 26;
  89135. // var off_caps1 = 27;
  89136. var off_caps2 = 28;
  89137. // var off_caps3 = 29;
  89138. // var off_caps4 = 30;
  89139. var off_dxgiFormat = 32;
  89140. ;
  89141. var DDSTools = /** @class */ (function () {
  89142. function DDSTools() {
  89143. }
  89144. DDSTools.GetDDSInfo = function (arrayBuffer) {
  89145. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  89146. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  89147. var mipmapCount = 1;
  89148. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  89149. mipmapCount = Math.max(1, header[off_mipmapCount]);
  89150. }
  89151. var fourCC = header[off_pfFourCC];
  89152. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  89153. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89154. switch (fourCC) {
  89155. case FOURCC_D3DFMT_R16G16B16A16F:
  89156. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89157. break;
  89158. case FOURCC_D3DFMT_R32G32B32A32F:
  89159. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89160. break;
  89161. case FOURCC_DX10:
  89162. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  89163. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89164. break;
  89165. }
  89166. }
  89167. return {
  89168. width: header[off_width],
  89169. height: header[off_height],
  89170. mipmapCount: mipmapCount,
  89171. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  89172. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  89173. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  89174. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  89175. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  89176. dxgiFormat: dxgiFormat,
  89177. textureType: textureType
  89178. };
  89179. };
  89180. DDSTools._ToHalfFloat = function (value) {
  89181. if (!DDSTools._FloatView) {
  89182. DDSTools._FloatView = new Float32Array(1);
  89183. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  89184. }
  89185. DDSTools._FloatView[0] = value;
  89186. var x = DDSTools._Int32View[0];
  89187. var bits = (x >> 16) & 0x8000; /* Get the sign */
  89188. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  89189. var e = (x >> 23) & 0xff; /* Using int is faster here */
  89190. /* If zero, or denormal, or exponent underflows too much for a denormal
  89191. * half, return signed zero. */
  89192. if (e < 103) {
  89193. return bits;
  89194. }
  89195. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  89196. if (e > 142) {
  89197. bits |= 0x7c00;
  89198. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  89199. * not Inf, so make sure we set one mantissa bit too. */
  89200. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  89201. return bits;
  89202. }
  89203. /* If exponent underflows but not too much, return a denormal */
  89204. if (e < 113) {
  89205. m |= 0x0800;
  89206. /* Extra rounding may overflow and set mantissa to 0 and exponent
  89207. * to 1, which is OK. */
  89208. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  89209. return bits;
  89210. }
  89211. bits |= ((e - 112) << 10) | (m >> 1);
  89212. bits += m & 1;
  89213. return bits;
  89214. };
  89215. DDSTools._FromHalfFloat = function (value) {
  89216. var s = (value & 0x8000) >> 15;
  89217. var e = (value & 0x7C00) >> 10;
  89218. var f = value & 0x03FF;
  89219. if (e === 0) {
  89220. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  89221. }
  89222. else if (e == 0x1F) {
  89223. return f ? NaN : ((s ? -1 : 1) * Infinity);
  89224. }
  89225. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  89226. };
  89227. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89228. var destArray = new Float32Array(dataLength);
  89229. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89230. var index = 0;
  89231. for (var y = 0; y < height; y++) {
  89232. for (var x = 0; x < width; x++) {
  89233. var srcPos = (x + y * width) * 4;
  89234. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  89235. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  89236. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  89237. if (DDSTools.StoreLODInAlphaChannel) {
  89238. destArray[index + 3] = lod;
  89239. }
  89240. else {
  89241. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  89242. }
  89243. index += 4;
  89244. }
  89245. }
  89246. return destArray;
  89247. };
  89248. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89249. if (DDSTools.StoreLODInAlphaChannel) {
  89250. var destArray = new Uint16Array(dataLength);
  89251. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89252. var index = 0;
  89253. for (var y = 0; y < height; y++) {
  89254. for (var x = 0; x < width; x++) {
  89255. var srcPos = (x + y * width) * 4;
  89256. destArray[index] = srcData[srcPos];
  89257. destArray[index + 1] = srcData[srcPos + 1];
  89258. destArray[index + 2] = srcData[srcPos + 2];
  89259. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  89260. index += 4;
  89261. }
  89262. }
  89263. return destArray;
  89264. }
  89265. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  89266. };
  89267. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89268. if (DDSTools.StoreLODInAlphaChannel) {
  89269. var destArray = new Float32Array(dataLength);
  89270. var srcData = new Float32Array(arrayBuffer, dataOffset);
  89271. var index = 0;
  89272. for (var y = 0; y < height; y++) {
  89273. for (var x = 0; x < width; x++) {
  89274. var srcPos = (x + y * width) * 4;
  89275. destArray[index] = srcData[srcPos];
  89276. destArray[index + 1] = srcData[srcPos + 1];
  89277. destArray[index + 2] = srcData[srcPos + 2];
  89278. destArray[index + 3] = lod;
  89279. index += 4;
  89280. }
  89281. }
  89282. return destArray;
  89283. }
  89284. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  89285. };
  89286. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89287. var destArray = new Uint8Array(dataLength);
  89288. var srcData = new Float32Array(arrayBuffer, dataOffset);
  89289. var index = 0;
  89290. for (var y = 0; y < height; y++) {
  89291. for (var x = 0; x < width; x++) {
  89292. var srcPos = (x + y * width) * 4;
  89293. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  89294. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  89295. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  89296. if (DDSTools.StoreLODInAlphaChannel) {
  89297. destArray[index + 3] = lod;
  89298. }
  89299. else {
  89300. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  89301. }
  89302. index += 4;
  89303. }
  89304. }
  89305. return destArray;
  89306. };
  89307. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89308. var destArray = new Uint8Array(dataLength);
  89309. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89310. var index = 0;
  89311. for (var y = 0; y < height; y++) {
  89312. for (var x = 0; x < width; x++) {
  89313. var srcPos = (x + y * width) * 4;
  89314. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  89315. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  89316. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  89317. if (DDSTools.StoreLODInAlphaChannel) {
  89318. destArray[index + 3] = lod;
  89319. }
  89320. else {
  89321. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  89322. }
  89323. index += 4;
  89324. }
  89325. }
  89326. return destArray;
  89327. };
  89328. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  89329. var byteArray = new Uint8Array(dataLength);
  89330. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89331. var index = 0;
  89332. for (var y = 0; y < height; y++) {
  89333. for (var x = 0; x < width; x++) {
  89334. var srcPos = (x + y * width) * 4;
  89335. byteArray[index] = srcData[srcPos + rOffset];
  89336. byteArray[index + 1] = srcData[srcPos + gOffset];
  89337. byteArray[index + 2] = srcData[srcPos + bOffset];
  89338. byteArray[index + 3] = srcData[srcPos + aOffset];
  89339. index += 4;
  89340. }
  89341. }
  89342. return byteArray;
  89343. };
  89344. DDSTools._ExtractLongWordOrder = function (value) {
  89345. if (value === 0 || value === 255 || value === -16777216) {
  89346. return 0;
  89347. }
  89348. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  89349. };
  89350. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  89351. var byteArray = new Uint8Array(dataLength);
  89352. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89353. var index = 0;
  89354. for (var y = 0; y < height; y++) {
  89355. for (var x = 0; x < width; x++) {
  89356. var srcPos = (x + y * width) * 3;
  89357. byteArray[index] = srcData[srcPos + rOffset];
  89358. byteArray[index + 1] = srcData[srcPos + gOffset];
  89359. byteArray[index + 2] = srcData[srcPos + bOffset];
  89360. index += 3;
  89361. }
  89362. }
  89363. return byteArray;
  89364. };
  89365. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  89366. var byteArray = new Uint8Array(dataLength);
  89367. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89368. var index = 0;
  89369. for (var y = 0; y < height; y++) {
  89370. for (var x = 0; x < width; x++) {
  89371. var srcPos = (x + y * width);
  89372. byteArray[index] = srcData[srcPos];
  89373. index++;
  89374. }
  89375. }
  89376. return byteArray;
  89377. };
  89378. /**
  89379. * Uploads DDS Levels to a Babylon Texture
  89380. * @hidden
  89381. */
  89382. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  89383. if (lodIndex === void 0) { lodIndex = -1; }
  89384. var sphericalPolynomialFaces = null;
  89385. if (info.sphericalPolynomial) {
  89386. sphericalPolynomialFaces = new Array();
  89387. }
  89388. var ext = engine.getCaps().s3tc;
  89389. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  89390. var fourCC, width, height, dataLength = 0, dataOffset;
  89391. var byteArray, mipmapCount, mip;
  89392. var internalCompressedFormat = 0;
  89393. var blockBytes = 1;
  89394. if (header[off_magic] !== DDS_MAGIC) {
  89395. BABYLON.Tools.Error("Invalid magic number in DDS header");
  89396. return;
  89397. }
  89398. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  89399. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  89400. return;
  89401. }
  89402. if (info.isCompressed && !ext) {
  89403. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  89404. return;
  89405. }
  89406. var bpp = header[off_RGBbpp];
  89407. dataOffset = header[off_size] + 4;
  89408. var computeFormats = false;
  89409. if (info.isFourCC) {
  89410. fourCC = header[off_pfFourCC];
  89411. switch (fourCC) {
  89412. case FOURCC_DXT1:
  89413. blockBytes = 8;
  89414. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  89415. break;
  89416. case FOURCC_DXT3:
  89417. blockBytes = 16;
  89418. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  89419. break;
  89420. case FOURCC_DXT5:
  89421. blockBytes = 16;
  89422. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  89423. break;
  89424. case FOURCC_D3DFMT_R16G16B16A16F:
  89425. computeFormats = true;
  89426. break;
  89427. case FOURCC_D3DFMT_R32G32B32A32F:
  89428. computeFormats = true;
  89429. break;
  89430. case FOURCC_DX10:
  89431. // There is an additionnal header so dataOffset need to be changed
  89432. dataOffset += 5 * 4; // 5 uints
  89433. var supported = false;
  89434. switch (info.dxgiFormat) {
  89435. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  89436. computeFormats = true;
  89437. supported = true;
  89438. break;
  89439. case DXGI_FORMAT_B8G8R8X8_UNORM:
  89440. info.isRGB = true;
  89441. info.isFourCC = false;
  89442. bpp = 32;
  89443. supported = true;
  89444. break;
  89445. }
  89446. if (supported) {
  89447. break;
  89448. }
  89449. default:
  89450. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  89451. return;
  89452. }
  89453. }
  89454. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  89455. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  89456. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  89457. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  89458. if (computeFormats) {
  89459. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  89460. }
  89461. mipmapCount = 1;
  89462. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  89463. mipmapCount = Math.max(1, header[off_mipmapCount]);
  89464. }
  89465. for (var face = 0; face < faces; face++) {
  89466. width = header[off_width];
  89467. height = header[off_height];
  89468. for (mip = 0; mip < mipmapCount; ++mip) {
  89469. if (lodIndex === -1 || lodIndex === mip) {
  89470. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  89471. var i = (lodIndex === -1) ? mip : 0;
  89472. if (!info.isCompressed && info.isFourCC) {
  89473. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89474. dataLength = width * height * 4;
  89475. var floatArray = null;
  89476. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  89477. if (bpp === 128) {
  89478. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89479. if (sphericalPolynomialFaces && i == 0) {
  89480. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89481. }
  89482. }
  89483. else if (bpp === 64) {
  89484. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89485. if (sphericalPolynomialFaces && i == 0) {
  89486. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89487. }
  89488. }
  89489. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89490. }
  89491. else {
  89492. if (bpp === 128) {
  89493. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89494. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89495. if (sphericalPolynomialFaces && i == 0) {
  89496. sphericalPolynomialFaces.push(floatArray);
  89497. }
  89498. }
  89499. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  89500. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89501. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89502. if (sphericalPolynomialFaces && i == 0) {
  89503. sphericalPolynomialFaces.push(floatArray);
  89504. }
  89505. }
  89506. else { // 64
  89507. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89508. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89509. if (sphericalPolynomialFaces && i == 0) {
  89510. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89511. }
  89512. }
  89513. }
  89514. if (floatArray) {
  89515. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  89516. }
  89517. }
  89518. else if (info.isRGB) {
  89519. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89520. if (bpp === 24) {
  89521. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  89522. dataLength = width * height * 3;
  89523. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  89524. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89525. }
  89526. else { // 32
  89527. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89528. dataLength = width * height * 4;
  89529. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  89530. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89531. }
  89532. }
  89533. else if (info.isLuminance) {
  89534. var unpackAlignment = engine._getUnpackAlignement();
  89535. var unpaddedRowSize = width;
  89536. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  89537. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  89538. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  89539. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  89540. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89541. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89542. }
  89543. else {
  89544. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  89545. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  89546. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89547. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  89548. }
  89549. }
  89550. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  89551. width *= 0.5;
  89552. height *= 0.5;
  89553. width = Math.max(1.0, width);
  89554. height = Math.max(1.0, height);
  89555. }
  89556. if (currentFace !== undefined) {
  89557. // Loading a single face
  89558. break;
  89559. }
  89560. }
  89561. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  89562. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  89563. size: header[off_width],
  89564. right: sphericalPolynomialFaces[0],
  89565. left: sphericalPolynomialFaces[1],
  89566. up: sphericalPolynomialFaces[2],
  89567. down: sphericalPolynomialFaces[3],
  89568. front: sphericalPolynomialFaces[4],
  89569. back: sphericalPolynomialFaces[5],
  89570. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  89571. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  89572. gammaSpace: false,
  89573. });
  89574. }
  89575. else {
  89576. info.sphericalPolynomial = undefined;
  89577. }
  89578. };
  89579. DDSTools.StoreLODInAlphaChannel = false;
  89580. return DDSTools;
  89581. }());
  89582. BABYLON.DDSTools = DDSTools;
  89583. })(BABYLON || (BABYLON = {}));
  89584. //# sourceMappingURL=babylon.dds.js.map
  89585. var BABYLON;
  89586. (function (BABYLON) {
  89587. /**
  89588. * Implementation of the DDS Texture Loader.
  89589. */
  89590. var DDSTextureLoader = /** @class */ (function () {
  89591. function DDSTextureLoader() {
  89592. /**
  89593. * Defines wether the loader supports cascade loading the different faces.
  89594. */
  89595. this.supportCascades = true;
  89596. }
  89597. /**
  89598. * This returns if the loader support the current file information.
  89599. * @param extension defines the file extension of the file being loaded
  89600. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89601. * @param fallback defines the fallback internal texture if any
  89602. * @param isBase64 defines whether the texture is encoded as a base64
  89603. * @param isBuffer defines whether the texture data are stored as a buffer
  89604. * @returns true if the loader can load the specified file
  89605. */
  89606. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89607. return extension.indexOf(".dds") === 0;
  89608. };
  89609. /**
  89610. * Transform the url before loading if required.
  89611. * @param rootUrl the url of the texture
  89612. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89613. * @returns the transformed texture
  89614. */
  89615. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89616. return rootUrl;
  89617. };
  89618. /**
  89619. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89620. * @param rootUrl the url of the texture
  89621. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89622. * @returns the fallback texture
  89623. */
  89624. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89625. return null;
  89626. };
  89627. /**
  89628. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89629. * @param data contains the texture data
  89630. * @param texture defines the BabylonJS internal texture
  89631. * @param createPolynomials will be true if polynomials have been requested
  89632. * @param onLoad defines the callback to trigger once the texture is ready
  89633. * @param onError defines the callback to trigger in case of error
  89634. */
  89635. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  89636. var engine = texture.getEngine();
  89637. var info;
  89638. var loadMipmap = false;
  89639. if (Array.isArray(imgs)) {
  89640. for (var index = 0; index < imgs.length; index++) {
  89641. var data_1 = imgs[index];
  89642. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  89643. texture.width = info.width;
  89644. texture.height = info.height;
  89645. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  89646. engine._unpackFlipY(info.isCompressed);
  89647. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  89648. if (!info.isFourCC && info.mipmapCount === 1) {
  89649. engine.generateMipMapsForCubemap(texture);
  89650. }
  89651. }
  89652. }
  89653. else {
  89654. var data = imgs;
  89655. info = BABYLON.DDSTools.GetDDSInfo(data);
  89656. texture.width = info.width;
  89657. texture.height = info.height;
  89658. if (createPolynomials) {
  89659. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  89660. }
  89661. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  89662. engine._unpackFlipY(info.isCompressed);
  89663. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  89664. if (!info.isFourCC && info.mipmapCount === 1) {
  89665. engine.generateMipMapsForCubemap(texture);
  89666. }
  89667. }
  89668. engine._setCubeMapTextureParams(loadMipmap);
  89669. texture.isReady = true;
  89670. if (onLoad) {
  89671. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  89672. }
  89673. };
  89674. /**
  89675. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89676. * @param data contains the texture data
  89677. * @param texture defines the BabylonJS internal texture
  89678. * @param callback defines the method to call once ready to upload
  89679. */
  89680. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  89681. var info = BABYLON.DDSTools.GetDDSInfo(data);
  89682. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  89683. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  89684. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  89685. });
  89686. };
  89687. return DDSTextureLoader;
  89688. }());
  89689. // Register the loader.
  89690. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  89691. })(BABYLON || (BABYLON = {}));
  89692. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  89693. var BABYLON;
  89694. (function (BABYLON) {
  89695. /*
  89696. * Based on jsTGALoader - Javascript loader for TGA file
  89697. * By Vincent Thibault
  89698. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  89699. */
  89700. var TGATools = /** @class */ (function () {
  89701. function TGATools() {
  89702. }
  89703. TGATools.GetTGAHeader = function (data) {
  89704. var offset = 0;
  89705. var header = {
  89706. id_length: data[offset++],
  89707. colormap_type: data[offset++],
  89708. image_type: data[offset++],
  89709. colormap_index: data[offset++] | data[offset++] << 8,
  89710. colormap_length: data[offset++] | data[offset++] << 8,
  89711. colormap_size: data[offset++],
  89712. origin: [
  89713. data[offset++] | data[offset++] << 8,
  89714. data[offset++] | data[offset++] << 8
  89715. ],
  89716. width: data[offset++] | data[offset++] << 8,
  89717. height: data[offset++] | data[offset++] << 8,
  89718. pixel_size: data[offset++],
  89719. flags: data[offset++]
  89720. };
  89721. return header;
  89722. };
  89723. /**
  89724. * Uploads TGA content to a Babylon Texture
  89725. * @hidden
  89726. */
  89727. TGATools.UploadContent = function (texture, data) {
  89728. // Not enough data to contain header ?
  89729. if (data.length < 19) {
  89730. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  89731. return;
  89732. }
  89733. // Read Header
  89734. var offset = 18;
  89735. var header = TGATools.GetTGAHeader(data);
  89736. // Assume it's a valid Targa file.
  89737. if (header.id_length + offset > data.length) {
  89738. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  89739. return;
  89740. }
  89741. // Skip not needed data
  89742. offset += header.id_length;
  89743. var use_rle = false;
  89744. var use_pal = false;
  89745. var use_grey = false;
  89746. // Get some informations.
  89747. switch (header.image_type) {
  89748. case TGATools._TYPE_RLE_INDEXED:
  89749. use_rle = true;
  89750. case TGATools._TYPE_INDEXED:
  89751. use_pal = true;
  89752. break;
  89753. case TGATools._TYPE_RLE_RGB:
  89754. use_rle = true;
  89755. case TGATools._TYPE_RGB:
  89756. // use_rgb = true;
  89757. break;
  89758. case TGATools._TYPE_RLE_GREY:
  89759. use_rle = true;
  89760. case TGATools._TYPE_GREY:
  89761. use_grey = true;
  89762. break;
  89763. }
  89764. var pixel_data;
  89765. // var numAlphaBits = header.flags & 0xf;
  89766. var pixel_size = header.pixel_size >> 3;
  89767. var pixel_total = header.width * header.height * pixel_size;
  89768. // Read palettes
  89769. var palettes;
  89770. if (use_pal) {
  89771. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  89772. }
  89773. // Read LRE
  89774. if (use_rle) {
  89775. pixel_data = new Uint8Array(pixel_total);
  89776. var c, count, i;
  89777. var localOffset = 0;
  89778. var pixels = new Uint8Array(pixel_size);
  89779. while (offset < pixel_total && localOffset < pixel_total) {
  89780. c = data[offset++];
  89781. count = (c & 0x7f) + 1;
  89782. // RLE pixels
  89783. if (c & 0x80) {
  89784. // Bind pixel tmp array
  89785. for (i = 0; i < pixel_size; ++i) {
  89786. pixels[i] = data[offset++];
  89787. }
  89788. // Copy pixel array
  89789. for (i = 0; i < count; ++i) {
  89790. pixel_data.set(pixels, localOffset + i * pixel_size);
  89791. }
  89792. localOffset += pixel_size * count;
  89793. }
  89794. // Raw pixels
  89795. else {
  89796. count *= pixel_size;
  89797. for (i = 0; i < count; ++i) {
  89798. pixel_data[localOffset + i] = data[offset++];
  89799. }
  89800. localOffset += count;
  89801. }
  89802. }
  89803. }
  89804. // RAW Pixels
  89805. else {
  89806. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  89807. }
  89808. // Load to texture
  89809. var x_start, y_start, x_step, y_step, y_end, x_end;
  89810. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  89811. default:
  89812. case TGATools._ORIGIN_UL:
  89813. x_start = 0;
  89814. x_step = 1;
  89815. x_end = header.width;
  89816. y_start = 0;
  89817. y_step = 1;
  89818. y_end = header.height;
  89819. break;
  89820. case TGATools._ORIGIN_BL:
  89821. x_start = 0;
  89822. x_step = 1;
  89823. x_end = header.width;
  89824. y_start = header.height - 1;
  89825. y_step = -1;
  89826. y_end = -1;
  89827. break;
  89828. case TGATools._ORIGIN_UR:
  89829. x_start = header.width - 1;
  89830. x_step = -1;
  89831. x_end = -1;
  89832. y_start = 0;
  89833. y_step = 1;
  89834. y_end = header.height;
  89835. break;
  89836. case TGATools._ORIGIN_BR:
  89837. x_start = header.width - 1;
  89838. x_step = -1;
  89839. x_end = -1;
  89840. y_start = header.height - 1;
  89841. y_step = -1;
  89842. y_end = -1;
  89843. break;
  89844. }
  89845. // Load the specify method
  89846. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  89847. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  89848. var engine = texture.getEngine();
  89849. engine._uploadDataToTextureDirectly(texture, imageData);
  89850. };
  89851. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89852. var image = pixel_data, colormap = palettes;
  89853. var width = header.width, height = header.height;
  89854. var color, i = 0, x, y;
  89855. var imageData = new Uint8Array(width * height * 4);
  89856. for (y = y_start; y !== y_end; y += y_step) {
  89857. for (x = x_start; x !== x_end; x += x_step, i++) {
  89858. color = image[i];
  89859. imageData[(x + width * y) * 4 + 3] = 255;
  89860. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  89861. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  89862. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  89863. }
  89864. }
  89865. return imageData;
  89866. };
  89867. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89868. var image = pixel_data;
  89869. var width = header.width, height = header.height;
  89870. var color, i = 0, x, y;
  89871. var imageData = new Uint8Array(width * height * 4);
  89872. for (y = y_start; y !== y_end; y += y_step) {
  89873. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  89874. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  89875. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  89876. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  89877. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  89878. imageData[(x + width * y) * 4 + 0] = r;
  89879. imageData[(x + width * y) * 4 + 1] = g;
  89880. imageData[(x + width * y) * 4 + 2] = b;
  89881. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  89882. }
  89883. }
  89884. return imageData;
  89885. };
  89886. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89887. var image = pixel_data;
  89888. var width = header.width, height = header.height;
  89889. var i = 0, x, y;
  89890. var imageData = new Uint8Array(width * height * 4);
  89891. for (y = y_start; y !== y_end; y += y_step) {
  89892. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  89893. imageData[(x + width * y) * 4 + 3] = 255;
  89894. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89895. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  89896. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  89897. }
  89898. }
  89899. return imageData;
  89900. };
  89901. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89902. var image = pixel_data;
  89903. var width = header.width, height = header.height;
  89904. var i = 0, x, y;
  89905. var imageData = new Uint8Array(width * height * 4);
  89906. for (y = y_start; y !== y_end; y += y_step) {
  89907. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  89908. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89909. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  89910. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  89911. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  89912. }
  89913. }
  89914. return imageData;
  89915. };
  89916. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89917. var image = pixel_data;
  89918. var width = header.width, height = header.height;
  89919. var color, i = 0, x, y;
  89920. var imageData = new Uint8Array(width * height * 4);
  89921. for (y = y_start; y !== y_end; y += y_step) {
  89922. for (x = x_start; x !== x_end; x += x_step, i++) {
  89923. color = image[i];
  89924. imageData[(x + width * y) * 4 + 0] = color;
  89925. imageData[(x + width * y) * 4 + 1] = color;
  89926. imageData[(x + width * y) * 4 + 2] = color;
  89927. imageData[(x + width * y) * 4 + 3] = 255;
  89928. }
  89929. }
  89930. return imageData;
  89931. };
  89932. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89933. var image = pixel_data;
  89934. var width = header.width, height = header.height;
  89935. var i = 0, x, y;
  89936. var imageData = new Uint8Array(width * height * 4);
  89937. for (y = y_start; y !== y_end; y += y_step) {
  89938. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  89939. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  89940. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  89941. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89942. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  89943. }
  89944. }
  89945. return imageData;
  89946. };
  89947. //private static _TYPE_NO_DATA = 0;
  89948. TGATools._TYPE_INDEXED = 1;
  89949. TGATools._TYPE_RGB = 2;
  89950. TGATools._TYPE_GREY = 3;
  89951. TGATools._TYPE_RLE_INDEXED = 9;
  89952. TGATools._TYPE_RLE_RGB = 10;
  89953. TGATools._TYPE_RLE_GREY = 11;
  89954. TGATools._ORIGIN_MASK = 0x30;
  89955. TGATools._ORIGIN_SHIFT = 0x04;
  89956. TGATools._ORIGIN_BL = 0x00;
  89957. TGATools._ORIGIN_BR = 0x01;
  89958. TGATools._ORIGIN_UL = 0x02;
  89959. TGATools._ORIGIN_UR = 0x03;
  89960. return TGATools;
  89961. }());
  89962. BABYLON.TGATools = TGATools;
  89963. })(BABYLON || (BABYLON = {}));
  89964. //# sourceMappingURL=babylon.tga.js.map
  89965. var BABYLON;
  89966. (function (BABYLON) {
  89967. /**
  89968. * Implementation of the TGA Texture Loader.
  89969. */
  89970. var TGATextureLoader = /** @class */ (function () {
  89971. function TGATextureLoader() {
  89972. /**
  89973. * Defines wether the loader supports cascade loading the different faces.
  89974. */
  89975. this.supportCascades = false;
  89976. }
  89977. /**
  89978. * This returns if the loader support the current file information.
  89979. * @param extension defines the file extension of the file being loaded
  89980. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89981. * @param fallback defines the fallback internal texture if any
  89982. * @param isBase64 defines whether the texture is encoded as a base64
  89983. * @param isBuffer defines whether the texture data are stored as a buffer
  89984. * @returns true if the loader can load the specified file
  89985. */
  89986. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89987. return extension.indexOf(".tga") === 0;
  89988. };
  89989. /**
  89990. * Transform the url before loading if required.
  89991. * @param rootUrl the url of the texture
  89992. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89993. * @returns the transformed texture
  89994. */
  89995. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89996. return rootUrl;
  89997. };
  89998. /**
  89999. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90000. * @param rootUrl the url of the texture
  90001. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90002. * @returns the fallback texture
  90003. */
  90004. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90005. return null;
  90006. };
  90007. /**
  90008. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90009. * @param data contains the texture data
  90010. * @param texture defines the BabylonJS internal texture
  90011. * @param createPolynomials will be true if polynomials have been requested
  90012. * @param onLoad defines the callback to trigger once the texture is ready
  90013. * @param onError defines the callback to trigger in case of error
  90014. */
  90015. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90016. throw ".env not supported in Cube.";
  90017. };
  90018. /**
  90019. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90020. * @param data contains the texture data
  90021. * @param texture defines the BabylonJS internal texture
  90022. * @param callback defines the method to call once ready to upload
  90023. */
  90024. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  90025. var uintData = new Uint8Array(data);
  90026. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  90027. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  90028. BABYLON.TGATools.UploadContent(texture, uintData);
  90029. });
  90030. };
  90031. return TGATextureLoader;
  90032. }());
  90033. // Register the loader.
  90034. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  90035. })(BABYLON || (BABYLON = {}));
  90036. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  90037. var BABYLON;
  90038. (function (BABYLON) {
  90039. /**
  90040. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  90041. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  90042. */
  90043. var KhronosTextureContainer = /** @class */ (function () {
  90044. /**
  90045. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  90046. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  90047. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  90048. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  90049. */
  90050. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  90051. this.arrayBuffer = arrayBuffer;
  90052. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  90053. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  90054. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  90055. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  90056. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  90057. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  90058. BABYLON.Tools.Error("texture missing KTX identifier");
  90059. return;
  90060. }
  90061. // load the reset of the header in native 32 bit int
  90062. var header = new Int32Array(this.arrayBuffer, 12, 13);
  90063. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  90064. var oppositeEndianess = header[0] === 0x01020304;
  90065. // read all the header elements in order they exist in the file, without modification (sans endainness)
  90066. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  90067. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  90068. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  90069. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  90070. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  90071. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  90072. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  90073. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  90074. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  90075. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  90076. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  90077. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  90078. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  90079. if (this.glType !== 0) {
  90080. BABYLON.Tools.Error("only compressed formats currently supported");
  90081. return;
  90082. }
  90083. else {
  90084. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  90085. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  90086. }
  90087. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  90088. BABYLON.Tools.Error("only 2D textures currently supported");
  90089. return;
  90090. }
  90091. if (this.numberOfArrayElements !== 0) {
  90092. BABYLON.Tools.Error("texture arrays not currently supported");
  90093. return;
  90094. }
  90095. if (this.numberOfFaces !== facesExpected) {
  90096. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  90097. return;
  90098. }
  90099. // we now have a completely validated file, so could use existence of loadType as success
  90100. // would need to make this more elaborate & adjust checks above to support more than one load type
  90101. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  90102. }
  90103. // not as fast hardware based, but will probably never need to use
  90104. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  90105. return ((val & 0xFF) << 24)
  90106. | ((val & 0xFF00) << 8)
  90107. | ((val >> 8) & 0xFF00)
  90108. | ((val >> 24) & 0xFF);
  90109. };
  90110. /**
  90111. * Uploads KTX content to a Babylon Texture.
  90112. * It is assumed that the texture has already been created & is currently bound
  90113. * @hidden
  90114. */
  90115. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  90116. switch (this.loadType) {
  90117. case KhronosTextureContainer.COMPRESSED_2D:
  90118. this._upload2DCompressedLevels(texture, loadMipmaps);
  90119. break;
  90120. case KhronosTextureContainer.TEX_2D:
  90121. case KhronosTextureContainer.COMPRESSED_3D:
  90122. case KhronosTextureContainer.TEX_3D:
  90123. }
  90124. };
  90125. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  90126. // initialize width & height for level 1
  90127. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  90128. var width = this.pixelWidth;
  90129. var height = this.pixelHeight;
  90130. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  90131. for (var level = 0; level < mipmapCount; level++) {
  90132. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  90133. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  90134. for (var face = 0; face < this.numberOfFaces; face++) {
  90135. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  90136. var engine = texture.getEngine();
  90137. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  90138. dataOffset += imageSize; // add size of the image for the next face/mipmap
  90139. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  90140. }
  90141. width = Math.max(1.0, width * 0.5);
  90142. height = Math.max(1.0, height * 0.5);
  90143. }
  90144. };
  90145. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  90146. // load types
  90147. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  90148. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  90149. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  90150. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  90151. return KhronosTextureContainer;
  90152. }());
  90153. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  90154. })(BABYLON || (BABYLON = {}));
  90155. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  90156. var BABYLON;
  90157. (function (BABYLON) {
  90158. /**
  90159. * Implementation of the KTX Texture Loader.
  90160. */
  90161. var KTXTextureLoader = /** @class */ (function () {
  90162. function KTXTextureLoader() {
  90163. /**
  90164. * Defines wether the loader supports cascade loading the different faces.
  90165. */
  90166. this.supportCascades = false;
  90167. }
  90168. /**
  90169. * This returns if the loader support the current file information.
  90170. * @param extension defines the file extension of the file being loaded
  90171. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90172. * @param fallback defines the fallback internal texture if any
  90173. * @param isBase64 defines whether the texture is encoded as a base64
  90174. * @param isBuffer defines whether the texture data are stored as a buffer
  90175. * @returns true if the loader can load the specified file
  90176. */
  90177. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90178. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  90179. return true;
  90180. }
  90181. return false;
  90182. };
  90183. /**
  90184. * Transform the url before loading if required.
  90185. * @param rootUrl the url of the texture
  90186. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90187. * @returns the transformed texture
  90188. */
  90189. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90190. var lastDot = rootUrl.lastIndexOf('.');
  90191. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  90192. };
  90193. /**
  90194. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90195. * @param rootUrl the url of the texture
  90196. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90197. * @returns the fallback texture
  90198. */
  90199. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90200. // remove the format appended to the rootUrl in the original createCubeTexture call.
  90201. var exp = new RegExp("" + textureFormatInUse + "$");
  90202. return rootUrl.replace(exp, "");
  90203. };
  90204. /**
  90205. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90206. * @param data contains the texture data
  90207. * @param texture defines the BabylonJS internal texture
  90208. * @param createPolynomials will be true if polynomials have been requested
  90209. * @param onLoad defines the callback to trigger once the texture is ready
  90210. * @param onError defines the callback to trigger in case of error
  90211. */
  90212. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90213. if (Array.isArray(data)) {
  90214. return;
  90215. }
  90216. var engine = texture.getEngine();
  90217. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  90218. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  90219. engine._unpackFlipY(true);
  90220. ktx.uploadLevels(texture, texture.generateMipMaps);
  90221. texture.width = ktx.pixelWidth;
  90222. texture.height = ktx.pixelHeight;
  90223. engine._setCubeMapTextureParams(loadMipmap);
  90224. texture.isReady = true;
  90225. };
  90226. /**
  90227. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90228. * @param data contains the texture data
  90229. * @param texture defines the BabylonJS internal texture
  90230. * @param callback defines the method to call once ready to upload
  90231. */
  90232. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  90233. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  90234. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  90235. ktx.uploadLevels(texture, texture.generateMipMaps);
  90236. });
  90237. };
  90238. return KTXTextureLoader;
  90239. }());
  90240. // Register the loader.
  90241. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  90242. })(BABYLON || (BABYLON = {}));
  90243. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  90244. var BABYLON;
  90245. (function (BABYLON) {
  90246. /**
  90247. * Sets of helpers addressing the serialization and deserialization of environment texture
  90248. * stored in a BabylonJS env file.
  90249. * Those files are usually stored as .env files.
  90250. */
  90251. var EnvironmentTextureTools = /** @class */ (function () {
  90252. function EnvironmentTextureTools() {
  90253. }
  90254. /**
  90255. * Gets the environment info from an env file.
  90256. * @param data The array buffer containing the .env bytes.
  90257. * @returns the environment file info (the json header) if successfully parsed.
  90258. */
  90259. EnvironmentTextureTools.GetEnvInfo = function (data) {
  90260. var dataView = new DataView(data);
  90261. var pos = 0;
  90262. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  90263. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  90264. BABYLON.Tools.Error('Not a babylon environment map');
  90265. return null;
  90266. }
  90267. }
  90268. // Read json manifest - collect characters up to null terminator
  90269. var manifestString = '';
  90270. var charCode = 0x00;
  90271. while ((charCode = dataView.getUint8(pos++))) {
  90272. manifestString += String.fromCharCode(charCode);
  90273. }
  90274. var manifest = JSON.parse(manifestString);
  90275. if (manifest.specular) {
  90276. // Extend the header with the position of the payload.
  90277. manifest.specular.specularDataPosition = pos;
  90278. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  90279. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  90280. }
  90281. return manifest;
  90282. };
  90283. /**
  90284. * Creates an environment texture from a loaded cube texture.
  90285. * @param texture defines the cube texture to convert in env file
  90286. * @return a promise containing the environment data if succesfull.
  90287. */
  90288. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  90289. var _this = this;
  90290. var internalTexture = texture.getInternalTexture();
  90291. if (!internalTexture) {
  90292. return Promise.reject("The cube texture is invalid.");
  90293. }
  90294. if (!texture._prefiltered) {
  90295. return Promise.reject("The cube texture is invalid (not prefiltered).");
  90296. }
  90297. var engine = internalTexture.getEngine();
  90298. if (engine && engine.premultipliedAlpha) {
  90299. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  90300. }
  90301. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  90302. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  90303. }
  90304. var canvas = engine.getRenderingCanvas();
  90305. if (!canvas) {
  90306. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  90307. }
  90308. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90309. if (!engine.getCaps().textureFloatRender) {
  90310. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90311. if (!engine.getCaps().textureHalfFloatRender) {
  90312. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  90313. }
  90314. }
  90315. var cubeWidth = internalTexture.width;
  90316. var hostingScene = new BABYLON.Scene(engine);
  90317. var specularTextures = {};
  90318. var promises = [];
  90319. // Read and collect all mipmaps data from the cube.
  90320. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  90321. mipmapsCount = Math.round(mipmapsCount);
  90322. var _loop_1 = function (i) {
  90323. var faceWidth = Math.pow(2, mipmapsCount - i);
  90324. var _loop_2 = function (face) {
  90325. var data = texture.readPixels(face, i);
  90326. // Creates a temp texture with the face data.
  90327. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  90328. // And rgbdEncode them.
  90329. var promise = new Promise(function (resolve, reject) {
  90330. 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);
  90331. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  90332. rgbdPostProcess.onApply = function (effect) {
  90333. effect._bindTexture("textureSampler", tempTexture);
  90334. };
  90335. // As the process needs to happen on the main canvas, keep track of the current size
  90336. var currentW = engine.getRenderWidth();
  90337. var currentH = engine.getRenderHeight();
  90338. // Set the desired size for the texture
  90339. engine.setSize(faceWidth, faceWidth);
  90340. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  90341. // Reading datas from WebGL
  90342. BABYLON.Tools.ToBlob(canvas, function (blob) {
  90343. var fileReader = new FileReader();
  90344. fileReader.onload = function (event) {
  90345. var arrayBuffer = event.target.result;
  90346. specularTextures[i * 6 + face] = arrayBuffer;
  90347. resolve();
  90348. };
  90349. fileReader.readAsArrayBuffer(blob);
  90350. });
  90351. // Reapply the previous canvas size
  90352. engine.setSize(currentW, currentH);
  90353. });
  90354. });
  90355. promises.push(promise);
  90356. };
  90357. // All faces of the cube.
  90358. for (var face = 0; face < 6; face++) {
  90359. _loop_2(face);
  90360. }
  90361. };
  90362. for (var i = 0; i <= mipmapsCount; i++) {
  90363. _loop_1(i);
  90364. }
  90365. // Once all the textures haves been collected as RGBD stored in PNGs
  90366. return Promise.all(promises).then(function () {
  90367. // We can delete the hosting scene keeping track of all the creation objects
  90368. hostingScene.dispose();
  90369. // Creates the json header for the env texture
  90370. var info = {
  90371. version: 1,
  90372. width: cubeWidth,
  90373. irradiance: _this._CreateEnvTextureIrradiance(texture),
  90374. specular: {
  90375. mipmaps: [],
  90376. lodGenerationScale: texture.lodGenerationScale
  90377. }
  90378. };
  90379. // Sets the specular image data information
  90380. var position = 0;
  90381. for (var i = 0; i <= mipmapsCount; i++) {
  90382. for (var face = 0; face < 6; face++) {
  90383. var byteLength = specularTextures[i * 6 + face].byteLength;
  90384. info.specular.mipmaps.push({
  90385. length: byteLength,
  90386. position: position
  90387. });
  90388. position += byteLength;
  90389. }
  90390. }
  90391. // Encode the JSON as an array buffer
  90392. var infoString = JSON.stringify(info);
  90393. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  90394. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  90395. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  90396. infoView[i] = infoString.charCodeAt(i);
  90397. }
  90398. // Ends up with a null terminator for easier parsing
  90399. infoView[infoString.length] = 0x00;
  90400. // Computes the final required size and creates the storage
  90401. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  90402. var finalBuffer = new ArrayBuffer(totalSize);
  90403. var finalBufferView = new Uint8Array(finalBuffer);
  90404. var dataView = new DataView(finalBuffer);
  90405. // Copy the magic bytes identifying the file in
  90406. var pos = 0;
  90407. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  90408. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  90409. }
  90410. // Add the json info
  90411. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  90412. pos += infoBuffer.byteLength;
  90413. // Finally inserts the texture data
  90414. for (var i = 0; i <= mipmapsCount; i++) {
  90415. for (var face = 0; face < 6; face++) {
  90416. var dataBuffer = specularTextures[i * 6 + face];
  90417. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  90418. pos += dataBuffer.byteLength;
  90419. }
  90420. }
  90421. // Voila
  90422. return finalBuffer;
  90423. });
  90424. };
  90425. /**
  90426. * Creates a JSON representation of the spherical data.
  90427. * @param texture defines the texture containing the polynomials
  90428. * @return the JSON representation of the spherical info
  90429. */
  90430. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  90431. var polynmials = texture.sphericalPolynomial;
  90432. if (polynmials == null) {
  90433. return null;
  90434. }
  90435. return {
  90436. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  90437. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  90438. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  90439. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  90440. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  90441. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  90442. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  90443. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  90444. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  90445. };
  90446. };
  90447. /**
  90448. * Uploads the texture info contained in the env file to the GPU.
  90449. * @param texture defines the internal texture to upload to
  90450. * @param arrayBuffer defines the buffer cotaining the data to load
  90451. * @param info defines the texture info retrieved through the GetEnvInfo method
  90452. * @returns a promise
  90453. */
  90454. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  90455. if (info.version !== 1) {
  90456. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  90457. }
  90458. var specularInfo = info.specular;
  90459. if (!specularInfo) {
  90460. // Nothing else parsed so far
  90461. return Promise.resolve();
  90462. }
  90463. // Double checks the enclosed info
  90464. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  90465. mipmapsCount = Math.round(mipmapsCount) + 1;
  90466. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  90467. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  90468. }
  90469. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  90470. var imageData = new Array(mipmapsCount);
  90471. for (var i = 0; i < mipmapsCount; i++) {
  90472. imageData[i] = new Array(6);
  90473. for (var face = 0; face < 6; face++) {
  90474. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  90475. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  90476. }
  90477. }
  90478. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  90479. };
  90480. /**
  90481. * Uploads the levels of image data to the GPU.
  90482. * @param texture defines the internal texture to upload to
  90483. * @param imageData defines the array buffer views of image data [mipmap][face]
  90484. * @returns a promise
  90485. */
  90486. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  90487. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  90488. throw new Error("Texture size must be a power of two");
  90489. }
  90490. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  90491. // Gets everything ready.
  90492. var engine = texture.getEngine();
  90493. var expandTexture = false;
  90494. var generateNonLODTextures = false;
  90495. var rgbdPostProcess = null;
  90496. var cubeRtt = null;
  90497. var lodTextures = null;
  90498. var caps = engine.getCaps();
  90499. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90500. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90501. texture.generateMipMaps = true;
  90502. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  90503. // Add extra process if texture lod is not supported
  90504. if (!caps.textureLOD) {
  90505. expandTexture = false;
  90506. generateNonLODTextures = true;
  90507. lodTextures = {};
  90508. }
  90509. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  90510. else if (engine.webGLVersion < 2) {
  90511. expandTexture = false;
  90512. }
  90513. // If half float available we can uncompress the texture
  90514. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  90515. expandTexture = true;
  90516. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90517. }
  90518. // If full float available we can uncompress the texture
  90519. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  90520. expandTexture = true;
  90521. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90522. }
  90523. // Expand the texture if possible
  90524. if (expandTexture) {
  90525. // Simply run through the decode PP
  90526. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  90527. texture._isRGBD = false;
  90528. texture.invertY = false;
  90529. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  90530. generateDepthBuffer: false,
  90531. generateMipMaps: true,
  90532. generateStencilBuffer: false,
  90533. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  90534. type: texture.type,
  90535. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  90536. });
  90537. }
  90538. else {
  90539. texture._isRGBD = true;
  90540. texture.invertY = true;
  90541. // In case of missing support, applies the same patch than DDS files.
  90542. if (generateNonLODTextures) {
  90543. var mipSlices = 3;
  90544. var scale = texture._lodGenerationScale;
  90545. var offset = texture._lodGenerationOffset;
  90546. for (var i = 0; i < mipSlices; i++) {
  90547. //compute LOD from even spacing in smoothness (matching shader calculation)
  90548. var smoothness = i / (mipSlices - 1);
  90549. var roughness = 1 - smoothness;
  90550. var minLODIndex = offset; // roughness = 0
  90551. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  90552. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  90553. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  90554. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  90555. glTextureFromLod.isCube = true;
  90556. glTextureFromLod.invertY = true;
  90557. glTextureFromLod.generateMipMaps = false;
  90558. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  90559. // Wrap in a base texture for easy binding.
  90560. var lodTexture = new BABYLON.BaseTexture(null);
  90561. lodTexture.isCube = true;
  90562. lodTexture._texture = glTextureFromLod;
  90563. lodTextures[mipmapIndex] = lodTexture;
  90564. switch (i) {
  90565. case 0:
  90566. texture._lodTextureLow = lodTexture;
  90567. break;
  90568. case 1:
  90569. texture._lodTextureMid = lodTexture;
  90570. break;
  90571. case 2:
  90572. texture._lodTextureHigh = lodTexture;
  90573. break;
  90574. }
  90575. }
  90576. }
  90577. }
  90578. var promises = [];
  90579. var _loop_3 = function (i) {
  90580. var _loop_4 = function (face) {
  90581. // Constructs an image element from image data
  90582. var bytes = imageData[i][face];
  90583. var blob = new Blob([bytes], { type: 'image/png' });
  90584. var url = URL.createObjectURL(blob);
  90585. var image = new Image();
  90586. image.src = url;
  90587. // Enqueue promise to upload to the texture.
  90588. var promise = new Promise(function (resolve, reject) {
  90589. image.onload = function () {
  90590. if (expandTexture) {
  90591. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  90592. reject(message);
  90593. }, image);
  90594. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  90595. // Uncompress the data to a RTT
  90596. rgbdPostProcess.onApply = function (effect) {
  90597. effect._bindTexture("textureSampler", tempTexture_1);
  90598. effect.setFloat2("scale", 1, 1);
  90599. };
  90600. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  90601. // Cleanup
  90602. engine.restoreDefaultFramebuffer();
  90603. tempTexture_1.dispose();
  90604. window.URL.revokeObjectURL(url);
  90605. resolve();
  90606. });
  90607. }
  90608. else {
  90609. engine._uploadImageToTexture(texture, image, face, i);
  90610. // Upload the face to the non lod texture support
  90611. if (generateNonLODTextures) {
  90612. var lodTexture = lodTextures[i];
  90613. if (lodTexture) {
  90614. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  90615. }
  90616. }
  90617. resolve();
  90618. }
  90619. };
  90620. image.onerror = function (error) {
  90621. reject(error);
  90622. };
  90623. });
  90624. promises.push(promise);
  90625. };
  90626. // All faces
  90627. for (var face = 0; face < 6; face++) {
  90628. _loop_4(face);
  90629. }
  90630. };
  90631. // All mipmaps up to provided number of images
  90632. for (var i = 0; i < imageData.length; i++) {
  90633. _loop_3(i);
  90634. }
  90635. // Fill remaining mipmaps with black textures.
  90636. if (imageData.length < mipmapsCount) {
  90637. var data = void 0;
  90638. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  90639. var dataLength = size * size * 4;
  90640. switch (texture.type) {
  90641. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  90642. data = new Uint8Array(dataLength);
  90643. break;
  90644. }
  90645. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  90646. data = new Uint16Array(dataLength);
  90647. break;
  90648. }
  90649. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  90650. data = new Float32Array(dataLength);
  90651. break;
  90652. }
  90653. }
  90654. for (var i = imageData.length; i < mipmapsCount; i++) {
  90655. for (var face = 0; face < 6; face++) {
  90656. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  90657. }
  90658. }
  90659. }
  90660. // Once all done, finishes the cleanup and return
  90661. return Promise.all(promises).then(function () {
  90662. // Release temp RTT.
  90663. if (cubeRtt) {
  90664. engine._releaseFramebufferObjects(cubeRtt);
  90665. cubeRtt._swapAndDie(texture);
  90666. }
  90667. // Release temp Post Process.
  90668. if (rgbdPostProcess) {
  90669. rgbdPostProcess.dispose();
  90670. }
  90671. // Flag internal texture as ready in case they are in use.
  90672. if (generateNonLODTextures) {
  90673. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  90674. texture._lodTextureHigh._texture.isReady = true;
  90675. }
  90676. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  90677. texture._lodTextureMid._texture.isReady = true;
  90678. }
  90679. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  90680. texture._lodTextureLow._texture.isReady = true;
  90681. }
  90682. }
  90683. });
  90684. };
  90685. /**
  90686. * Uploads spherical polynomials information to the texture.
  90687. * @param texture defines the texture we are trying to upload the information to
  90688. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  90689. */
  90690. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  90691. if (info.version !== 1) {
  90692. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  90693. }
  90694. var irradianceInfo = info.irradiance;
  90695. if (!irradianceInfo) {
  90696. return;
  90697. }
  90698. var sp = new BABYLON.SphericalPolynomial();
  90699. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  90700. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  90701. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  90702. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  90703. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  90704. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  90705. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  90706. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  90707. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  90708. texture._sphericalPolynomial = sp;
  90709. };
  90710. /**
  90711. * Magic number identifying the env file.
  90712. */
  90713. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  90714. return EnvironmentTextureTools;
  90715. }());
  90716. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  90717. })(BABYLON || (BABYLON = {}));
  90718. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  90719. var BABYLON;
  90720. (function (BABYLON) {
  90721. /**
  90722. * Implementation of the ENV Texture Loader.
  90723. */
  90724. var ENVTextureLoader = /** @class */ (function () {
  90725. function ENVTextureLoader() {
  90726. /**
  90727. * Defines wether the loader supports cascade loading the different faces.
  90728. */
  90729. this.supportCascades = false;
  90730. }
  90731. /**
  90732. * This returns if the loader support the current file information.
  90733. * @param extension defines the file extension of the file being loaded
  90734. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90735. * @param fallback defines the fallback internal texture if any
  90736. * @param isBase64 defines whether the texture is encoded as a base64
  90737. * @param isBuffer defines whether the texture data are stored as a buffer
  90738. * @returns true if the loader can load the specified file
  90739. */
  90740. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90741. return extension.indexOf(".env") === 0;
  90742. };
  90743. /**
  90744. * Transform the url before loading if required.
  90745. * @param rootUrl the url of the texture
  90746. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90747. * @returns the transformed texture
  90748. */
  90749. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90750. return rootUrl;
  90751. };
  90752. /**
  90753. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90754. * @param rootUrl the url of the texture
  90755. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90756. * @returns the fallback texture
  90757. */
  90758. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90759. return null;
  90760. };
  90761. /**
  90762. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90763. * @param data contains the texture data
  90764. * @param texture defines the BabylonJS internal texture
  90765. * @param createPolynomials will be true if polynomials have been requested
  90766. * @param onLoad defines the callback to trigger once the texture is ready
  90767. * @param onError defines the callback to trigger in case of error
  90768. */
  90769. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90770. if (Array.isArray(data)) {
  90771. return;
  90772. }
  90773. data = data;
  90774. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  90775. if (info) {
  90776. texture.width = info.width;
  90777. texture.height = info.width;
  90778. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  90779. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  90780. texture.isReady = true;
  90781. if (onLoad) {
  90782. onLoad();
  90783. }
  90784. });
  90785. }
  90786. else if (onError) {
  90787. onError("Can not parse the environment file", null);
  90788. }
  90789. };
  90790. /**
  90791. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90792. * @param data contains the texture data
  90793. * @param texture defines the BabylonJS internal texture
  90794. * @param callback defines the method to call once ready to upload
  90795. */
  90796. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  90797. throw ".env not supported in 2d.";
  90798. };
  90799. return ENVTextureLoader;
  90800. }());
  90801. // Register the loader.
  90802. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  90803. })(BABYLON || (BABYLON = {}));
  90804. //# sourceMappingURL=babylon.envTextureLoader.js.map
  90805. var BABYLON;
  90806. (function (BABYLON) {
  90807. /**
  90808. * Renders a layer on top of an existing scene
  90809. */
  90810. var UtilityLayerRenderer = /** @class */ (function () {
  90811. /**
  90812. * Instantiates a UtilityLayerRenderer
  90813. * @param originalScene the original scene that will be rendered on top of
  90814. */
  90815. function UtilityLayerRenderer(
  90816. /** the original scene that will be rendered on top of */
  90817. originalScene) {
  90818. var _this = this;
  90819. this.originalScene = originalScene;
  90820. this._pointerCaptures = {};
  90821. this._lastPointerEvents = {};
  90822. /**
  90823. * If the utility layer should automatically be rendered on top of existing scene
  90824. */
  90825. this.shouldRender = true;
  90826. /**
  90827. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  90828. */
  90829. this.onlyCheckPointerDownEvents = true;
  90830. /**
  90831. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  90832. */
  90833. this.processAllEvents = false;
  90834. /**
  90835. * Observable raised when the pointer move from the utility layer scene to the main scene
  90836. */
  90837. this.onPointerOutObservable = new BABYLON.Observable();
  90838. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  90839. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  90840. this.utilityLayerScene._allowPostProcessClear = false;
  90841. originalScene.getEngine().scenes.pop();
  90842. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  90843. this.utilityLayerScene.detachControl();
  90844. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  90845. if (!_this.processAllEvents) {
  90846. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  90847. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  90848. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  90849. return;
  90850. }
  90851. }
  90852. var pointerEvent = (prePointerInfo.event);
  90853. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  90854. _this._pointerCaptures[pointerEvent.pointerId] = false;
  90855. return;
  90856. }
  90857. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  90858. if (!prePointerInfo.ray && utilityScenePick) {
  90859. prePointerInfo.ray = utilityScenePick.ray;
  90860. }
  90861. // always fire the prepointer oversvable
  90862. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  90863. // allow every non pointer down event to flow to the utility layer
  90864. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  90865. if (!prePointerInfo.skipOnPointerObservable) {
  90866. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  90867. }
  90868. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  90869. _this._pointerCaptures[pointerEvent.pointerId] = false;
  90870. }
  90871. return;
  90872. }
  90873. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  90874. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  90875. if (utilityScenePick && utilityScenePick.hit) {
  90876. if (!prePointerInfo.skipOnPointerObservable) {
  90877. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  90878. }
  90879. prePointerInfo.skipOnPointerObservable = true;
  90880. }
  90881. }
  90882. else {
  90883. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  90884. var pointerEvent_1 = (prePointerInfo.event);
  90885. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  90886. if (originalScenePick && utilityScenePick) {
  90887. // No pick in utility scene
  90888. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  90889. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  90890. // We touched an utility mesh present in the main scene
  90891. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  90892. prePointerInfo.skipOnPointerObservable = true;
  90893. }
  90894. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  90895. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  90896. }
  90897. }
  90898. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  90899. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  90900. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  90901. // If a previous utility layer set this, do not unset this
  90902. if (!prePointerInfo.skipOnPointerObservable) {
  90903. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  90904. }
  90905. }
  90906. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  90907. // We have a pick in both scenes but main is closer than utility
  90908. // We touched an utility mesh present in the main scene
  90909. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  90910. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  90911. prePointerInfo.skipOnPointerObservable = true;
  90912. }
  90913. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  90914. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  90915. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  90916. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  90917. }
  90918. }
  90919. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  90920. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  90921. }
  90922. }
  90923. }
  90924. });
  90925. // Render directly on top of existing scene without clearing
  90926. this.utilityLayerScene.autoClear = false;
  90927. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  90928. if (_this.shouldRender) {
  90929. _this.render();
  90930. }
  90931. });
  90932. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  90933. _this.dispose();
  90934. });
  90935. this._updateCamera();
  90936. }
  90937. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  90938. /**
  90939. * 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)
  90940. */
  90941. get: function () {
  90942. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  90943. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  90944. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  90945. UtilityLayerRenderer._DefaultUtilityLayer = null;
  90946. });
  90947. }
  90948. return UtilityLayerRenderer._DefaultUtilityLayer;
  90949. },
  90950. enumerable: true,
  90951. configurable: true
  90952. });
  90953. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  90954. /**
  90955. * 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)
  90956. */
  90957. get: function () {
  90958. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  90959. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  90960. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  90961. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  90962. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  90963. });
  90964. }
  90965. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  90966. },
  90967. enumerable: true,
  90968. configurable: true
  90969. });
  90970. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  90971. if (!prePointerInfo.skipOnPointerObservable) {
  90972. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  90973. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  90974. }
  90975. };
  90976. /**
  90977. * Renders the utility layers scene on top of the original scene
  90978. */
  90979. UtilityLayerRenderer.prototype.render = function () {
  90980. this._updateCamera();
  90981. if (this.utilityLayerScene.activeCamera) {
  90982. // Set the camera's scene to utility layers scene
  90983. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  90984. var camera = this.utilityLayerScene.activeCamera;
  90985. camera._scene = this.utilityLayerScene;
  90986. if (camera.leftCamera) {
  90987. camera.leftCamera._scene = this.utilityLayerScene;
  90988. }
  90989. if (camera.rightCamera) {
  90990. camera.rightCamera._scene = this.utilityLayerScene;
  90991. }
  90992. this.utilityLayerScene.render(false);
  90993. // Reset camera's scene back to original
  90994. camera._scene = oldScene;
  90995. if (camera.leftCamera) {
  90996. camera.leftCamera._scene = oldScene;
  90997. }
  90998. if (camera.rightCamera) {
  90999. camera.rightCamera._scene = oldScene;
  91000. }
  91001. }
  91002. };
  91003. /**
  91004. * Disposes of the renderer
  91005. */
  91006. UtilityLayerRenderer.prototype.dispose = function () {
  91007. this.onPointerOutObservable.clear();
  91008. if (this._afterRenderObserver) {
  91009. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  91010. }
  91011. if (this._sceneDisposeObserver) {
  91012. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91013. }
  91014. if (this._originalPointerObserver) {
  91015. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  91016. }
  91017. this.utilityLayerScene.dispose();
  91018. };
  91019. UtilityLayerRenderer.prototype._updateCamera = function () {
  91020. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  91021. };
  91022. UtilityLayerRenderer._DefaultUtilityLayer = null;
  91023. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  91024. return UtilityLayerRenderer;
  91025. }());
  91026. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  91027. })(BABYLON || (BABYLON = {}));
  91028. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  91029. //# sourceMappingURL=babylon.behavior.js.map
  91030. var BABYLON;
  91031. (function (BABYLON) {
  91032. /**
  91033. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  91034. */
  91035. var PointerDragBehavior = /** @class */ (function () {
  91036. /**
  91037. * Creates a pointer drag behavior that can be attached to a mesh
  91038. * @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)
  91039. */
  91040. function PointerDragBehavior(options) {
  91041. /**
  91042. * 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)
  91043. */
  91044. this.maxDragAngle = 0;
  91045. /**
  91046. * @hidden
  91047. */
  91048. this._useAlternatePickedPointAboveMaxDragAngle = false;
  91049. /**
  91050. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  91051. */
  91052. this.currentDraggingPointerID = -1;
  91053. /**
  91054. * If the behavior is currently in a dragging state
  91055. */
  91056. this.dragging = false;
  91057. /**
  91058. * 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)
  91059. */
  91060. this.dragDeltaRatio = 0.2;
  91061. /**
  91062. * If the drag plane orientation should be updated during the dragging (Default: true)
  91063. */
  91064. this.updateDragPlane = true;
  91065. // Debug mode will display drag planes to help visualize behavior
  91066. this._debugMode = false;
  91067. this._moving = false;
  91068. /**
  91069. * Fires each time the attached mesh is dragged with the pointer
  91070. * * delta between last drag position and current drag position in world space
  91071. * * dragDistance along the drag axis
  91072. * * dragPlaneNormal normal of the current drag plane used during the drag
  91073. * * dragPlanePoint in world space where the drag intersects the drag plane
  91074. */
  91075. this.onDragObservable = new BABYLON.Observable();
  91076. /**
  91077. * Fires each time a drag begins (eg. mouse down on mesh)
  91078. */
  91079. this.onDragStartObservable = new BABYLON.Observable();
  91080. /**
  91081. * Fires each time a drag ends (eg. mouse release after drag)
  91082. */
  91083. this.onDragEndObservable = new BABYLON.Observable();
  91084. /**
  91085. * If the attached mesh should be moved when dragged
  91086. */
  91087. this.moveAttached = true;
  91088. /**
  91089. * If the drag behavior will react to drag events (Default: true)
  91090. */
  91091. this.enabled = true;
  91092. /**
  91093. * If camera controls should be detached during the drag
  91094. */
  91095. this.detachCameraControls = true;
  91096. /**
  91097. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  91098. */
  91099. this.useObjectOrienationForDragging = true;
  91100. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  91101. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  91102. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  91103. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  91104. this._attachedElement = null;
  91105. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  91106. this._lastPointerRay = {};
  91107. this._dragDelta = new BABYLON.Vector3();
  91108. // Variables to avoid instantiation in the below method
  91109. this._pointA = new BABYLON.Vector3(0, 0, 0);
  91110. this._pointB = new BABYLON.Vector3(0, 0, 0);
  91111. this._pointC = new BABYLON.Vector3(0, 0, 0);
  91112. this._lineA = new BABYLON.Vector3(0, 0, 0);
  91113. this._lineB = new BABYLON.Vector3(0, 0, 0);
  91114. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  91115. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  91116. this._options = options ? options : {};
  91117. var optionCount = 0;
  91118. if (this._options.dragAxis) {
  91119. optionCount++;
  91120. }
  91121. if (this._options.dragPlaneNormal) {
  91122. optionCount++;
  91123. }
  91124. if (optionCount > 1) {
  91125. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  91126. }
  91127. }
  91128. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  91129. /**
  91130. * The name of the behavior
  91131. */
  91132. get: function () {
  91133. return "PointerDrag";
  91134. },
  91135. enumerable: true,
  91136. configurable: true
  91137. });
  91138. /**
  91139. * Initializes the behavior
  91140. */
  91141. PointerDragBehavior.prototype.init = function () { };
  91142. /**
  91143. * Attaches the drag behavior the passed in mesh
  91144. * @param ownerNode The mesh that will be dragged around once attached
  91145. */
  91146. PointerDragBehavior.prototype.attach = function (ownerNode) {
  91147. var _this = this;
  91148. this._scene = ownerNode.getScene();
  91149. this._attachedNode = ownerNode;
  91150. // Initialize drag plane to not interfere with existing scene
  91151. if (!PointerDragBehavior._planeScene) {
  91152. if (this._debugMode) {
  91153. PointerDragBehavior._planeScene = this._scene;
  91154. }
  91155. else {
  91156. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  91157. PointerDragBehavior._planeScene.detachControl();
  91158. this._scene.getEngine().scenes.pop();
  91159. this._scene.onDisposeObservable.addOnce(function () {
  91160. PointerDragBehavior._planeScene.dispose();
  91161. PointerDragBehavior._planeScene = null;
  91162. });
  91163. }
  91164. }
  91165. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  91166. // State of the drag
  91167. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  91168. var pickPredicate = function (m) {
  91169. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  91170. };
  91171. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  91172. if (!_this.enabled) {
  91173. return;
  91174. }
  91175. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91176. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  91177. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  91178. }
  91179. }
  91180. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  91181. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  91182. _this.releaseDrag();
  91183. }
  91184. }
  91185. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  91186. var pointerId = pointerInfo.event.pointerId;
  91187. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  91188. if (!_this._lastPointerRay[pointerId]) {
  91189. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  91190. }
  91191. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  91192. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  91193. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  91194. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  91195. _this._moveDrag(pointerInfo.pickInfo.ray);
  91196. }
  91197. }
  91198. }
  91199. });
  91200. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  91201. if (_this._moving && _this.moveAttached) {
  91202. // Slowly move mesh to avoid jitter
  91203. _this._targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  91204. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  91205. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  91206. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  91207. }
  91208. });
  91209. };
  91210. PointerDragBehavior.prototype.releaseDrag = function () {
  91211. this.dragging = false;
  91212. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  91213. this.currentDraggingPointerID = -1;
  91214. this._moving = false;
  91215. // Reattach camera controls
  91216. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  91217. this._scene.activeCamera.attachControl(this._attachedElement, true);
  91218. }
  91219. };
  91220. /**
  91221. * Simulates the start of a pointer drag event on the behavior
  91222. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  91223. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  91224. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  91225. */
  91226. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  91227. if (pointerId === void 0) { pointerId = 1; }
  91228. this._startDrag(pointerId, fromRay, startPickedPoint);
  91229. if (this._lastPointerRay[pointerId]) {
  91230. // if there was a last pointer ray drag the object there
  91231. this._moveDrag(this._lastPointerRay[pointerId]);
  91232. }
  91233. };
  91234. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  91235. if (pointerId === void 0) { pointerId = 1; }
  91236. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  91237. return;
  91238. }
  91239. // Create start ray from the camera to the object
  91240. if (fromRay) {
  91241. this._startDragRay.direction.copyFrom(fromRay.direction);
  91242. this._startDragRay.origin.copyFrom(fromRay.origin);
  91243. }
  91244. else {
  91245. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  91246. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  91247. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  91248. }
  91249. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  91250. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  91251. if (pickedPoint) {
  91252. this.dragging = true;
  91253. this.currentDraggingPointerID = 1;
  91254. this.lastDragPosition.copyFrom(pickedPoint);
  91255. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  91256. this._targetPosition.copyFrom(this._attachedNode.absolutePosition);
  91257. // Detatch camera controls
  91258. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  91259. if (this._scene.activeCamera.inputs.attachedElement) {
  91260. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  91261. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  91262. }
  91263. else {
  91264. this._attachedElement = null;
  91265. }
  91266. }
  91267. }
  91268. };
  91269. PointerDragBehavior.prototype._moveDrag = function (ray) {
  91270. this._moving = true;
  91271. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  91272. if (pickedPoint) {
  91273. if (this.updateDragPlane) {
  91274. this._updateDragPlanePosition(ray, pickedPoint);
  91275. }
  91276. var dragLength = 0;
  91277. // depending on the drag mode option drag accordingly
  91278. if (this._options.dragAxis) {
  91279. // Convert local drag axis to world
  91280. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  91281. // Project delta drag from the drag plane onto the drag axis
  91282. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  91283. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  91284. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  91285. }
  91286. else {
  91287. dragLength = this._dragDelta.length();
  91288. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  91289. }
  91290. this._targetPosition.addInPlace(this._dragDelta);
  91291. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  91292. this.lastDragPosition.copyFrom(pickedPoint);
  91293. }
  91294. };
  91295. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  91296. var _this = this;
  91297. if (!ray) {
  91298. return null;
  91299. }
  91300. // Calculate angle between plane normal and ray
  91301. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  91302. // Correct if ray is casted from oposite side
  91303. if (angle > Math.PI / 2) {
  91304. angle = Math.PI - angle;
  91305. }
  91306. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  91307. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  91308. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  91309. // Invert ray direction along the towards object axis
  91310. this._tmpVector.copyFrom(ray.direction);
  91311. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  91312. this._alternatePickedPoint.normalize();
  91313. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  91314. this._tmpVector.addInPlace(this._alternatePickedPoint);
  91315. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  91316. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  91317. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  91318. this._alternatePickedPoint.addInPlace(this._tmpVector);
  91319. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  91320. return this._alternatePickedPoint;
  91321. }
  91322. else {
  91323. return null;
  91324. }
  91325. }
  91326. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  91327. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  91328. return pickResult.pickedPoint;
  91329. }
  91330. else {
  91331. return null;
  91332. }
  91333. };
  91334. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  91335. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  91336. this._pointA.copyFrom(dragPlanePosition);
  91337. if (this._options.dragAxis) {
  91338. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  91339. // Calculate plane normal in direction of camera but perpendicular to drag axis
  91340. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  91341. ray.origin.subtractToRef(this._pointA, this._pointC);
  91342. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  91343. // Get perpendicular line from direction to camera and drag axis
  91344. this._pointB.subtractToRef(this._pointA, this._lineA);
  91345. this._pointC.subtractToRef(this._pointA, this._lineB);
  91346. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  91347. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  91348. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  91349. this._lookAt.normalize();
  91350. this._dragPlane.position.copyFrom(this._pointA);
  91351. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  91352. this._dragPlane.lookAt(this._lookAt);
  91353. }
  91354. else if (this._options.dragPlaneNormal) {
  91355. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  91356. this._dragPlane.position.copyFrom(this._pointA);
  91357. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  91358. this._dragPlane.lookAt(this._lookAt);
  91359. }
  91360. else {
  91361. this._dragPlane.position.copyFrom(this._pointA);
  91362. this._dragPlane.lookAt(ray.origin);
  91363. }
  91364. this._dragPlane.computeWorldMatrix(true);
  91365. };
  91366. /**
  91367. * Detaches the behavior from the mesh
  91368. */
  91369. PointerDragBehavior.prototype.detach = function () {
  91370. if (this._pointerObserver) {
  91371. this._scene.onPointerObservable.remove(this._pointerObserver);
  91372. }
  91373. if (this._beforeRenderObserver) {
  91374. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  91375. }
  91376. };
  91377. return PointerDragBehavior;
  91378. }());
  91379. BABYLON.PointerDragBehavior = PointerDragBehavior;
  91380. })(BABYLON || (BABYLON = {}));
  91381. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  91382. var BABYLON;
  91383. (function (BABYLON) {
  91384. /**
  91385. * A behavior that when attached to a mesh will allow the mesh to be scaled
  91386. */
  91387. var MultiPointerScaleBehavior = /** @class */ (function () {
  91388. function MultiPointerScaleBehavior() {
  91389. this._startDistance = 0;
  91390. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  91391. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  91392. this._sceneRenderObserver = null;
  91393. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  91394. this._dragBehaviorA.moveAttached = false;
  91395. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  91396. this._dragBehaviorB.moveAttached = false;
  91397. }
  91398. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  91399. /**
  91400. * The name of the behavior
  91401. */
  91402. get: function () {
  91403. return "MultiPointerScale";
  91404. },
  91405. enumerable: true,
  91406. configurable: true
  91407. });
  91408. /**
  91409. * Initializes the behavior
  91410. */
  91411. MultiPointerScaleBehavior.prototype.init = function () { };
  91412. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  91413. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  91414. };
  91415. /**
  91416. * Attaches the scale behavior the passed in mesh
  91417. * @param ownerNode The mesh that will be scaled around once attached
  91418. */
  91419. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  91420. var _this = this;
  91421. this._ownerNode = ownerNode;
  91422. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  91423. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  91424. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91425. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  91426. _this._dragBehaviorA.releaseDrag();
  91427. }
  91428. else {
  91429. _this._initialScale.copyFrom(ownerNode.scaling);
  91430. _this._startDistance = _this._getCurrentDistance();
  91431. }
  91432. }
  91433. });
  91434. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  91435. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91436. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  91437. _this._dragBehaviorB.releaseDrag();
  91438. }
  91439. else {
  91440. _this._initialScale.copyFrom(ownerNode.scaling);
  91441. _this._startDistance = _this._getCurrentDistance();
  91442. }
  91443. }
  91444. });
  91445. // Once both drag behaviors are active scale based on the distance between the two pointers
  91446. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  91447. behavior.onDragObservable.add(function () {
  91448. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91449. var ratio = _this._getCurrentDistance() / _this._startDistance;
  91450. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  91451. }
  91452. });
  91453. });
  91454. ownerNode.addBehavior(this._dragBehaviorA);
  91455. ownerNode.addBehavior(this._dragBehaviorB);
  91456. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  91457. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  91458. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91459. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  91460. if (change.length() > 0.01) {
  91461. ownerNode.scaling.addInPlace(change);
  91462. }
  91463. }
  91464. });
  91465. };
  91466. /**
  91467. * Detaches the behavior from the mesh
  91468. */
  91469. MultiPointerScaleBehavior.prototype.detach = function () {
  91470. var _this = this;
  91471. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  91472. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  91473. behavior.onDragStartObservable.clear();
  91474. behavior.onDragObservable.clear();
  91475. _this._ownerNode.removeBehavior(behavior);
  91476. });
  91477. };
  91478. return MultiPointerScaleBehavior;
  91479. }());
  91480. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  91481. })(BABYLON || (BABYLON = {}));
  91482. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  91483. var BABYLON;
  91484. (function (BABYLON) {
  91485. /**
  91486. * 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
  91487. */
  91488. var SixDofDragBehavior = /** @class */ (function () {
  91489. function SixDofDragBehavior() {
  91490. this._sceneRenderObserver = null;
  91491. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  91492. this._moving = false;
  91493. this._startingOrientation = new BABYLON.Quaternion();
  91494. /**
  91495. * 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)
  91496. */
  91497. this.zDragFactor = 3;
  91498. /**
  91499. * If the behavior is currently in a dragging state
  91500. */
  91501. this.dragging = false;
  91502. /**
  91503. * 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)
  91504. */
  91505. this.dragDeltaRatio = 0.2;
  91506. /**
  91507. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  91508. */
  91509. this.currentDraggingPointerID = -1;
  91510. /**
  91511. * If camera controls should be detached during the drag
  91512. */
  91513. this.detachCameraControls = true;
  91514. }
  91515. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  91516. /**
  91517. * The name of the behavior
  91518. */
  91519. get: function () {
  91520. return "SixDofDrag";
  91521. },
  91522. enumerable: true,
  91523. configurable: true
  91524. });
  91525. /**
  91526. * Initializes the behavior
  91527. */
  91528. SixDofDragBehavior.prototype.init = function () { };
  91529. /**
  91530. * Attaches the scale behavior the passed in mesh
  91531. * @param ownerNode The mesh that will be scaled around once attached
  91532. */
  91533. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  91534. var _this = this;
  91535. this._ownerNode = ownerNode;
  91536. this._scene = this._ownerNode.getScene();
  91537. if (!SixDofDragBehavior._virtualScene) {
  91538. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  91539. this._scene.getEngine().scenes.pop();
  91540. }
  91541. var pickedMesh = null;
  91542. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  91543. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  91544. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  91545. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  91546. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  91547. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  91548. var pickPredicate = function (m) {
  91549. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  91550. };
  91551. var attachedElement = null;
  91552. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  91553. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91554. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  91555. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  91556. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  91557. }
  91558. pickedMesh = _this._ownerNode;
  91559. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  91560. // Set position and orientation of the controller
  91561. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  91562. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  91563. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  91564. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91565. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  91566. if (!pickedMesh.rotationQuaternion) {
  91567. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  91568. }
  91569. var oldParent = pickedMesh.parent;
  91570. pickedMesh.setParent(null);
  91571. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  91572. pickedMesh.setParent(oldParent);
  91573. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  91574. // Update state
  91575. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  91576. _this.dragging = true;
  91577. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  91578. // Detatch camera controls
  91579. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  91580. if (_this._scene.activeCamera.inputs.attachedElement) {
  91581. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  91582. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  91583. }
  91584. else {
  91585. attachedElement = null;
  91586. }
  91587. }
  91588. }
  91589. }
  91590. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  91591. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  91592. _this.dragging = false;
  91593. _this._moving = false;
  91594. _this.currentDraggingPointerID = -1;
  91595. pickedMesh = null;
  91596. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91597. // Reattach camera controls
  91598. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  91599. _this._scene.activeCamera.attachControl(attachedElement, true);
  91600. }
  91601. }
  91602. }
  91603. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  91604. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  91605. var zDragFactor = _this.zDragFactor;
  91606. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  91607. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  91608. zDragFactor = 0;
  91609. }
  91610. // Calculate controller drag distance in controller space
  91611. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  91612. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  91613. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  91614. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  91615. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  91616. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  91617. if (_this._virtualDragMesh.position.z < 0) {
  91618. _this._virtualDragMesh.position.z = 0;
  91619. }
  91620. // Update the controller position
  91621. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  91622. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  91623. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91624. // Move the virtualObjectsPosition into the picked mesh's space if needed
  91625. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  91626. if (pickedMesh.parent) {
  91627. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  91628. }
  91629. if (!_this._moving) {
  91630. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  91631. }
  91632. _this._moving = true;
  91633. }
  91634. }
  91635. });
  91636. var tmpQuaternion = new BABYLON.Quaternion();
  91637. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  91638. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  91639. if (_this.dragging && _this._moving && pickedMesh) {
  91640. // Slowly move mesh to avoid jitter
  91641. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  91642. // Get change in rotation
  91643. tmpQuaternion.copyFrom(_this._startingOrientation);
  91644. tmpQuaternion.x = -tmpQuaternion.x;
  91645. tmpQuaternion.y = -tmpQuaternion.y;
  91646. tmpQuaternion.z = -tmpQuaternion.z;
  91647. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  91648. // Convert change in rotation to only y axis rotation
  91649. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  91650. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  91651. // Slowly move mesh to avoid jitter
  91652. var oldParent = pickedMesh.parent;
  91653. pickedMesh.setParent(null);
  91654. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  91655. pickedMesh.setParent(oldParent);
  91656. }
  91657. });
  91658. };
  91659. /**
  91660. * Detaches the behavior from the mesh
  91661. */
  91662. SixDofDragBehavior.prototype.detach = function () {
  91663. if (this._scene) {
  91664. this._scene.onPointerObservable.remove(this._pointerObserver);
  91665. }
  91666. if (this._ownerNode) {
  91667. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  91668. }
  91669. if (this._virtualOriginMesh) {
  91670. this._virtualOriginMesh.dispose();
  91671. }
  91672. if (this._virtualDragMesh) {
  91673. this._virtualDragMesh.dispose();
  91674. }
  91675. };
  91676. return SixDofDragBehavior;
  91677. }());
  91678. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  91679. })(BABYLON || (BABYLON = {}));
  91680. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  91681. var BABYLON;
  91682. (function (BABYLON) {
  91683. /**
  91684. * @hidden
  91685. */
  91686. var FaceDirectionInfo = /** @class */ (function () {
  91687. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  91688. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  91689. if (diff === void 0) { diff = 0; }
  91690. if (ignore === void 0) { ignore = false; }
  91691. this.direction = direction;
  91692. this.rotatedDirection = rotatedDirection;
  91693. this.diff = diff;
  91694. this.ignore = ignore;
  91695. }
  91696. return FaceDirectionInfo;
  91697. }());
  91698. /**
  91699. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  91700. */
  91701. var AttachToBoxBehavior = /** @class */ (function () {
  91702. /**
  91703. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  91704. * @param ui The transform node that should be attched to the mesh
  91705. */
  91706. function AttachToBoxBehavior(ui) {
  91707. this.ui = ui;
  91708. /**
  91709. * The name of the behavior
  91710. */
  91711. this.name = "AttachToBoxBehavior";
  91712. /**
  91713. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  91714. */
  91715. this.distanceAwayFromFace = 0.15;
  91716. /**
  91717. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  91718. */
  91719. this.distanceAwayFromBottomOfFace = 0.15;
  91720. 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))];
  91721. this._tmpMatrix = new BABYLON.Matrix();
  91722. this._tmpVector = new BABYLON.Vector3();
  91723. this._zeroVector = BABYLON.Vector3.Zero();
  91724. this._lookAtTmpMatrix = new BABYLON.Matrix();
  91725. /* Does nothing */
  91726. }
  91727. /**
  91728. * Initializes the behavior
  91729. */
  91730. AttachToBoxBehavior.prototype.init = function () {
  91731. /* Does nothing */
  91732. };
  91733. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  91734. var _this = this;
  91735. // Go over each face and calculate the angle between the face's normal and targetDirection
  91736. this._faceVectors.forEach(function (v) {
  91737. if (!_this._target.rotationQuaternion) {
  91738. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  91739. }
  91740. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  91741. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  91742. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  91743. });
  91744. // Return the face information of the one with the normal closeset to target direction
  91745. return this._faceVectors.reduce(function (min, p) {
  91746. if (min.ignore) {
  91747. return p;
  91748. }
  91749. else if (p.ignore) {
  91750. return min;
  91751. }
  91752. else {
  91753. return min.diff < p.diff ? min : p;
  91754. }
  91755. }, this._faceVectors[0]);
  91756. };
  91757. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  91758. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  91759. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  91760. this._lookAtTmpMatrix.invert();
  91761. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  91762. };
  91763. /**
  91764. * Attaches the AttachToBoxBehavior to the passed in mesh
  91765. * @param target The mesh that the specified node will be attached to
  91766. */
  91767. AttachToBoxBehavior.prototype.attach = function (target) {
  91768. var _this = this;
  91769. this._target = target;
  91770. this._scene = this._target.getScene();
  91771. // Every frame, update the app bars position
  91772. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  91773. if (!_this._scene.activeCamera) {
  91774. return;
  91775. }
  91776. // Find the face closest to the cameras position
  91777. var cameraPos = _this._scene.activeCamera.position;
  91778. if (_this._scene.activeCamera.devicePosition) {
  91779. cameraPos = _this._scene.activeCamera.devicePosition;
  91780. }
  91781. var facing = _this._closestFace(cameraPos.subtract(target.position));
  91782. if (_this._scene.activeCamera.leftCamera) {
  91783. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  91784. }
  91785. else {
  91786. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  91787. }
  91788. // Get camera up direction
  91789. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  91790. // Ignore faces to not select a parrelel face for the up vector of the UI
  91791. _this._faceVectors.forEach(function (v) {
  91792. if (facing.direction.x && v.direction.x) {
  91793. v.ignore = true;
  91794. }
  91795. if (facing.direction.y && v.direction.y) {
  91796. v.ignore = true;
  91797. }
  91798. if (facing.direction.z && v.direction.z) {
  91799. v.ignore = true;
  91800. }
  91801. });
  91802. var facingUp = _this._closestFace(_this._tmpVector);
  91803. // Unignore faces
  91804. _this._faceVectors.forEach(function (v) {
  91805. v.ignore = false;
  91806. });
  91807. // Position the app bar on that face
  91808. _this.ui.position.copyFrom(target.position);
  91809. if (facing.direction.x) {
  91810. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91811. _this.ui.position.addInPlace(_this._tmpVector);
  91812. }
  91813. if (facing.direction.y) {
  91814. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91815. _this.ui.position.addInPlace(_this._tmpVector);
  91816. }
  91817. if (facing.direction.z) {
  91818. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91819. _this.ui.position.addInPlace(_this._tmpVector);
  91820. }
  91821. // Rotate to be oriented properly to the camera
  91822. if (!_this.ui.rotationQuaternion) {
  91823. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  91824. }
  91825. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  91826. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  91827. // Place ui the correct distance from the bottom of the mesh
  91828. if (facingUp.direction.x) {
  91829. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  91830. }
  91831. if (facingUp.direction.y) {
  91832. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  91833. }
  91834. if (facingUp.direction.z) {
  91835. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  91836. }
  91837. _this.ui.position.addInPlace(_this._tmpVector);
  91838. });
  91839. };
  91840. /**
  91841. * Detaches the behavior from the mesh
  91842. */
  91843. AttachToBoxBehavior.prototype.detach = function () {
  91844. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  91845. };
  91846. return AttachToBoxBehavior;
  91847. }());
  91848. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  91849. })(BABYLON || (BABYLON = {}));
  91850. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  91851. var BABYLON;
  91852. (function (BABYLON) {
  91853. /**
  91854. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  91855. */
  91856. var FadeInOutBehavior = /** @class */ (function () {
  91857. /**
  91858. * Instatiates the FadeInOutBehavior
  91859. */
  91860. function FadeInOutBehavior() {
  91861. var _this = this;
  91862. /**
  91863. * Time in milliseconds to delay before fading in (Default: 0)
  91864. */
  91865. this.delay = 0;
  91866. /**
  91867. * Time in milliseconds for the mesh to fade in (Default: 300)
  91868. */
  91869. this.fadeInTime = 300;
  91870. this._millisecondsPerFrame = 1000 / 60;
  91871. this._hovered = false;
  91872. this._hoverValue = 0;
  91873. this._ownerNode = null;
  91874. this._update = function () {
  91875. if (_this._ownerNode) {
  91876. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  91877. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  91878. if (_this._ownerNode.visibility > 1) {
  91879. _this._setAllVisibility(_this._ownerNode, 1);
  91880. _this._hoverValue = _this.fadeInTime + _this.delay;
  91881. return;
  91882. }
  91883. else if (_this._ownerNode.visibility < 0) {
  91884. _this._setAllVisibility(_this._ownerNode, 0);
  91885. if (_this._hoverValue < 0) {
  91886. _this._hoverValue = 0;
  91887. return;
  91888. }
  91889. }
  91890. setTimeout(_this._update, _this._millisecondsPerFrame);
  91891. }
  91892. };
  91893. }
  91894. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  91895. /**
  91896. * The name of the behavior
  91897. */
  91898. get: function () {
  91899. return "FadeInOut";
  91900. },
  91901. enumerable: true,
  91902. configurable: true
  91903. });
  91904. /**
  91905. * Initializes the behavior
  91906. */
  91907. FadeInOutBehavior.prototype.init = function () {
  91908. };
  91909. /**
  91910. * Attaches the fade behavior on the passed in mesh
  91911. * @param ownerNode The mesh that will be faded in/out once attached
  91912. */
  91913. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  91914. this._ownerNode = ownerNode;
  91915. this._setAllVisibility(this._ownerNode, 0);
  91916. };
  91917. /**
  91918. * Detaches the behavior from the mesh
  91919. */
  91920. FadeInOutBehavior.prototype.detach = function () {
  91921. this._ownerNode = null;
  91922. };
  91923. /**
  91924. * Triggers the mesh to begin fading in or out
  91925. * @param value if the object should fade in or out (true to fade in)
  91926. */
  91927. FadeInOutBehavior.prototype.fadeIn = function (value) {
  91928. this._hovered = value;
  91929. this._update();
  91930. };
  91931. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  91932. var _this = this;
  91933. mesh.visibility = value;
  91934. mesh.getChildMeshes().forEach(function (c) {
  91935. _this._setAllVisibility(c, value);
  91936. });
  91937. };
  91938. return FadeInOutBehavior;
  91939. }());
  91940. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  91941. })(BABYLON || (BABYLON = {}));
  91942. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  91943. var BABYLON;
  91944. (function (BABYLON) {
  91945. /**
  91946. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  91947. */
  91948. var Gizmo = /** @class */ (function () {
  91949. /**
  91950. * Creates a gizmo
  91951. * @param gizmoLayer The utility layer the gizmo will be added to
  91952. */
  91953. function Gizmo(
  91954. /** The utility layer the gizmo will be added to */
  91955. gizmoLayer) {
  91956. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91957. var _this = this;
  91958. this.gizmoLayer = gizmoLayer;
  91959. /**
  91960. * Ratio for the scale of the gizmo (Default: 1)
  91961. */
  91962. this.scaleRatio = 1;
  91963. this._tmpMatrix = new BABYLON.Matrix();
  91964. /**
  91965. * If a custom mesh has been set (Default: false)
  91966. */
  91967. this._customMeshSet = false;
  91968. /**
  91969. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  91970. */
  91971. this.updateGizmoRotationToMatchAttachedMesh = true;
  91972. /**
  91973. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  91974. */
  91975. this.updateGizmoPositionToMatchAttachedMesh = true;
  91976. /**
  91977. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  91978. */
  91979. this._updateScale = true;
  91980. this._interactionsEnabled = true;
  91981. this._tempVector = new BABYLON.Vector3();
  91982. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  91983. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  91984. _this._update();
  91985. });
  91986. this.attachedMesh = null;
  91987. }
  91988. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  91989. /**
  91990. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  91991. * * When set, interactions will be enabled
  91992. */
  91993. get: function () {
  91994. return this._attachedMesh;
  91995. },
  91996. set: function (value) {
  91997. this._attachedMesh = value;
  91998. this._rootMesh.setEnabled(value ? true : false);
  91999. this._attachedMeshChanged(value);
  92000. },
  92001. enumerable: true,
  92002. configurable: true
  92003. });
  92004. /**
  92005. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  92006. * @param mesh The mesh to replace the default mesh of the gizmo
  92007. */
  92008. Gizmo.prototype.setCustomMesh = function (mesh) {
  92009. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  92010. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  92011. }
  92012. this._rootMesh.getChildMeshes().forEach(function (c) {
  92013. c.dispose();
  92014. });
  92015. mesh.parent = this._rootMesh;
  92016. this._customMeshSet = true;
  92017. };
  92018. Gizmo.prototype._attachedMeshChanged = function (value) {
  92019. };
  92020. /**
  92021. * @hidden
  92022. * Updates the gizmo to match the attached mesh's position/rotation
  92023. */
  92024. Gizmo.prototype._update = function () {
  92025. if (this.attachedMesh) {
  92026. if (this.updateGizmoRotationToMatchAttachedMesh) {
  92027. if (!this._rootMesh.rotationQuaternion) {
  92028. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  92029. }
  92030. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  92031. this._tempVector.copyFrom(this.attachedMesh.scaling);
  92032. if (this.attachedMesh.scaling.x < 0) {
  92033. this.attachedMesh.scaling.x *= -1;
  92034. }
  92035. if (this.attachedMesh.scaling.y < 0) {
  92036. this.attachedMesh.scaling.y *= -1;
  92037. }
  92038. if (this.attachedMesh.scaling.z < 0) {
  92039. this.attachedMesh.scaling.z *= -1;
  92040. }
  92041. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  92042. this.attachedMesh.scaling.copyFrom(this._tempVector);
  92043. this.attachedMesh.computeWorldMatrix();
  92044. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  92045. }
  92046. else if (this._rootMesh.rotationQuaternion) {
  92047. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  92048. }
  92049. if (this.updateGizmoPositionToMatchAttachedMesh) {
  92050. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  92051. }
  92052. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  92053. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  92054. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  92055. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  92056. }
  92057. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  92058. var dist = this._tempVector.length() * this.scaleRatio;
  92059. this._rootMesh.scaling.set(dist, dist, dist);
  92060. }
  92061. }
  92062. };
  92063. /**
  92064. * Disposes of the gizmo
  92065. */
  92066. Gizmo.prototype.dispose = function () {
  92067. this._rootMesh.dispose();
  92068. if (this._beforeRenderObserver) {
  92069. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  92070. }
  92071. };
  92072. return Gizmo;
  92073. }());
  92074. BABYLON.Gizmo = Gizmo;
  92075. })(BABYLON || (BABYLON = {}));
  92076. //# sourceMappingURL=babylon.gizmo.js.map
  92077. var BABYLON;
  92078. (function (BABYLON) {
  92079. /**
  92080. * Single axis drag gizmo
  92081. */
  92082. var AxisDragGizmo = /** @class */ (function (_super) {
  92083. __extends(AxisDragGizmo, _super);
  92084. /**
  92085. * Creates an AxisDragGizmo
  92086. * @param gizmoLayer The utility layer the gizmo will be added to
  92087. * @param dragAxis The axis which the gizmo will be able to drag on
  92088. * @param color The color of the gizmo
  92089. */
  92090. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  92091. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92092. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92093. var _this = _super.call(this, gizmoLayer) || this;
  92094. _this._pointerObserver = null;
  92095. /**
  92096. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92097. */
  92098. _this.snapDistance = 0;
  92099. /**
  92100. * Event that fires each time the gizmo snaps to a new location.
  92101. * * snapDistance is the the change in distance
  92102. */
  92103. _this.onSnapObservable = new BABYLON.Observable();
  92104. // Create Material
  92105. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92106. coloredMaterial.disableLighting = true;
  92107. coloredMaterial.emissiveColor = color;
  92108. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92109. hoverMaterial.disableLighting = true;
  92110. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92111. // Build mesh on root node
  92112. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92113. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  92114. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  92115. arrowTail.color = coloredMaterial.emissiveColor;
  92116. arrow.addChild(arrowMesh);
  92117. arrow.addChild(arrowTail);
  92118. // Position arrow pointing in its drag axis
  92119. arrowMesh.scaling.scaleInPlace(0.05);
  92120. arrowMesh.material = coloredMaterial;
  92121. arrowMesh.rotation.x = Math.PI / 2;
  92122. arrowMesh.position.z += 0.3;
  92123. arrowTail.scaling.scaleInPlace(0.26);
  92124. arrowTail.rotation.x = Math.PI / 2;
  92125. arrowTail.material = coloredMaterial;
  92126. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  92127. arrow.scaling.scaleInPlace(1 / 3);
  92128. _this._rootMesh.addChild(arrow);
  92129. var currentSnapDragDistance = 0;
  92130. var tmpVector = new BABYLON.Vector3();
  92131. var tmpSnapEvent = { snapDistance: 0 };
  92132. // Add drag behavior to handle events when the gizmo is dragged
  92133. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92134. _this.dragBehavior.moveAttached = false;
  92135. _this._rootMesh.addBehavior(_this.dragBehavior);
  92136. var localDelta = new BABYLON.Vector3();
  92137. var tmpMatrix = new BABYLON.Matrix();
  92138. _this.dragBehavior.onDragObservable.add(function (event) {
  92139. if (_this.attachedMesh) {
  92140. // Convert delta to local translation if it has a parent
  92141. if (_this.attachedMesh.parent) {
  92142. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  92143. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  92144. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  92145. }
  92146. else {
  92147. localDelta.copyFrom(event.delta);
  92148. }
  92149. // Snapping logic
  92150. if (_this.snapDistance == 0) {
  92151. _this.attachedMesh.position.addInPlace(localDelta);
  92152. }
  92153. else {
  92154. currentSnapDragDistance += event.dragDistance;
  92155. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92156. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  92157. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92158. localDelta.normalizeToRef(tmpVector);
  92159. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  92160. _this.attachedMesh.position.addInPlace(tmpVector);
  92161. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  92162. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92163. }
  92164. }
  92165. }
  92166. });
  92167. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92168. if (_this._customMeshSet) {
  92169. return;
  92170. }
  92171. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92172. var material = isHovered ? hoverMaterial : coloredMaterial;
  92173. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92174. m.material = material;
  92175. if (m.color) {
  92176. m.color = material.emissiveColor;
  92177. }
  92178. });
  92179. });
  92180. return _this;
  92181. }
  92182. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  92183. if (this.dragBehavior) {
  92184. this.dragBehavior.enabled = value ? true : false;
  92185. }
  92186. };
  92187. /**
  92188. * Disposes of the gizmo
  92189. */
  92190. AxisDragGizmo.prototype.dispose = function () {
  92191. this.onSnapObservable.clear();
  92192. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92193. this.dragBehavior.detach();
  92194. _super.prototype.dispose.call(this);
  92195. };
  92196. return AxisDragGizmo;
  92197. }(BABYLON.Gizmo));
  92198. BABYLON.AxisDragGizmo = AxisDragGizmo;
  92199. })(BABYLON || (BABYLON = {}));
  92200. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  92201. var BABYLON;
  92202. (function (BABYLON) {
  92203. /**
  92204. * Single axis scale gizmo
  92205. */
  92206. var AxisScaleGizmo = /** @class */ (function (_super) {
  92207. __extends(AxisScaleGizmo, _super);
  92208. /**
  92209. * Creates an AxisScaleGizmo
  92210. * @param gizmoLayer The utility layer the gizmo will be added to
  92211. * @param dragAxis The axis which the gizmo will be able to scale on
  92212. * @param color The color of the gizmo
  92213. */
  92214. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  92215. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92216. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92217. var _this = _super.call(this, gizmoLayer) || this;
  92218. _this._pointerObserver = null;
  92219. /**
  92220. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92221. */
  92222. _this.snapDistance = 0;
  92223. /**
  92224. * Event that fires each time the gizmo snaps to a new location.
  92225. * * snapDistance is the the change in distance
  92226. */
  92227. _this.onSnapObservable = new BABYLON.Observable();
  92228. /**
  92229. * If the scaling operation should be done on all axis (default: false)
  92230. */
  92231. _this.uniformScaling = false;
  92232. // Create Material
  92233. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92234. _this._coloredMaterial.disableLighting = true;
  92235. _this._coloredMaterial.emissiveColor = color;
  92236. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92237. hoverMaterial.disableLighting = true;
  92238. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92239. // Build mesh on root node
  92240. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92241. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  92242. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  92243. arrowTail.color = _this._coloredMaterial.emissiveColor;
  92244. arrow.addChild(arrowMesh);
  92245. arrow.addChild(arrowTail);
  92246. // Position arrow pointing in its drag axis
  92247. arrowMesh.scaling.scaleInPlace(0.1);
  92248. arrowMesh.material = _this._coloredMaterial;
  92249. arrowMesh.rotation.x = Math.PI / 2;
  92250. arrowMesh.position.z += 0.3;
  92251. arrowTail.scaling.scaleInPlace(0.26);
  92252. arrowTail.rotation.x = Math.PI / 2;
  92253. arrowTail.material = _this._coloredMaterial;
  92254. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  92255. _this._rootMesh.addChild(arrow);
  92256. arrow.scaling.scaleInPlace(1 / 3);
  92257. // Add drag behavior to handle events when the gizmo is dragged
  92258. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92259. _this.dragBehavior.moveAttached = false;
  92260. _this._rootMesh.addBehavior(_this.dragBehavior);
  92261. var currentSnapDragDistance = 0;
  92262. var tmpVector = new BABYLON.Vector3();
  92263. var tmpSnapEvent = { snapDistance: 0 };
  92264. _this.dragBehavior.onDragObservable.add(function (event) {
  92265. if (_this.attachedMesh) {
  92266. // Snapping logic
  92267. var snapped = false;
  92268. var dragSteps = 0;
  92269. if (_this.uniformScaling) {
  92270. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  92271. if (tmpVector.y < 0) {
  92272. tmpVector.scaleInPlace(-1);
  92273. }
  92274. }
  92275. else {
  92276. tmpVector.copyFrom(dragAxis);
  92277. }
  92278. if (_this.snapDistance == 0) {
  92279. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  92280. }
  92281. else {
  92282. currentSnapDragDistance += event.dragDistance;
  92283. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92284. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  92285. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92286. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  92287. snapped = true;
  92288. }
  92289. else {
  92290. tmpVector.scaleInPlace(0);
  92291. }
  92292. }
  92293. _this.attachedMesh.scaling.addInPlace(tmpVector);
  92294. if (snapped) {
  92295. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  92296. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92297. }
  92298. }
  92299. });
  92300. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92301. if (_this._customMeshSet) {
  92302. return;
  92303. }
  92304. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92305. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  92306. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92307. m.material = material;
  92308. if (m.color) {
  92309. m.color = material.emissiveColor;
  92310. }
  92311. });
  92312. });
  92313. return _this;
  92314. }
  92315. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  92316. if (this.dragBehavior) {
  92317. this.dragBehavior.enabled = value ? true : false;
  92318. }
  92319. };
  92320. /**
  92321. * Disposes of the gizmo
  92322. */
  92323. AxisScaleGizmo.prototype.dispose = function () {
  92324. this.onSnapObservable.clear();
  92325. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92326. this.dragBehavior.detach();
  92327. _super.prototype.dispose.call(this);
  92328. };
  92329. /**
  92330. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  92331. * @param mesh The mesh to replace the default mesh of the gizmo
  92332. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  92333. */
  92334. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  92335. var _this = this;
  92336. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  92337. _super.prototype.setCustomMesh.call(this, mesh);
  92338. if (useGizmoMaterial) {
  92339. this._rootMesh.getChildMeshes().forEach(function (m) {
  92340. m.material = _this._coloredMaterial;
  92341. if (m.color) {
  92342. m.color = _this._coloredMaterial.emissiveColor;
  92343. }
  92344. });
  92345. this._customMeshSet = false;
  92346. }
  92347. };
  92348. return AxisScaleGizmo;
  92349. }(BABYLON.Gizmo));
  92350. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  92351. })(BABYLON || (BABYLON = {}));
  92352. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  92353. var BABYLON;
  92354. (function (BABYLON) {
  92355. /**
  92356. * Single plane rotation gizmo
  92357. */
  92358. var PlaneRotationGizmo = /** @class */ (function (_super) {
  92359. __extends(PlaneRotationGizmo, _super);
  92360. /**
  92361. * Creates a PlaneRotationGizmo
  92362. * @param gizmoLayer The utility layer the gizmo will be added to
  92363. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  92364. * @param color The color of the gizmo
  92365. */
  92366. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  92367. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92368. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92369. var _this = _super.call(this, gizmoLayer) || this;
  92370. _this._pointerObserver = null;
  92371. /**
  92372. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  92373. */
  92374. _this.snapDistance = 0;
  92375. /**
  92376. * Event that fires each time the gizmo snaps to a new location.
  92377. * * snapDistance is the the change in distance
  92378. */
  92379. _this.onSnapObservable = new BABYLON.Observable();
  92380. // Create Material
  92381. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92382. coloredMaterial.disableLighting = true;
  92383. coloredMaterial.emissiveColor = color;
  92384. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92385. hoverMaterial.disableLighting = true;
  92386. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92387. // Build mesh on root node
  92388. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92389. // Create circle out of lines
  92390. var tessellation = 20;
  92391. var radius = 0.8;
  92392. var points = new Array();
  92393. for (var i = 0; i < tessellation; i++) {
  92394. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  92395. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  92396. }
  92397. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  92398. rotationMesh.color = coloredMaterial.emissiveColor;
  92399. // Position arrow pointing in its drag axis
  92400. rotationMesh.scaling.scaleInPlace(0.26);
  92401. rotationMesh.material = coloredMaterial;
  92402. rotationMesh.rotation.x = Math.PI / 2;
  92403. parentMesh.addChild(rotationMesh);
  92404. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  92405. _this._rootMesh.addChild(parentMesh);
  92406. parentMesh.scaling.scaleInPlace(1 / 3);
  92407. // Add drag behavior to handle events when the gizmo is dragged
  92408. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  92409. _this.dragBehavior.moveAttached = false;
  92410. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  92411. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  92412. _this._rootMesh.addBehavior(_this.dragBehavior);
  92413. var lastDragPosition = new BABYLON.Vector3();
  92414. _this.dragBehavior.onDragStartObservable.add(function (e) {
  92415. if (_this.attachedMesh) {
  92416. lastDragPosition.copyFrom(e.dragPlanePoint);
  92417. }
  92418. });
  92419. var rotationMatrix = new BABYLON.Matrix();
  92420. var planeNormalTowardsCamera = new BABYLON.Vector3();
  92421. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  92422. var tmpSnapEvent = { snapDistance: 0 };
  92423. var currentSnapDragDistance = 0;
  92424. var tmpMatrix = new BABYLON.Matrix();
  92425. var tmpVector = new BABYLON.Vector3();
  92426. var amountToRotate = new BABYLON.Quaternion();
  92427. _this.dragBehavior.onDragObservable.add(function (event) {
  92428. if (_this.attachedMesh) {
  92429. if (!_this.attachedMesh.rotationQuaternion) {
  92430. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  92431. }
  92432. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  92433. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  92434. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  92435. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  92436. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  92437. var angle = Math.atan2(cross.length(), dot);
  92438. planeNormalTowardsCamera.copyFrom(planeNormal);
  92439. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  92440. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  92441. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  92442. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  92443. }
  92444. // Flip up vector depending on which side the camera is on
  92445. if (gizmoLayer.utilityLayerScene.activeCamera) {
  92446. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  92447. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  92448. planeNormalTowardsCamera.scaleInPlace(-1);
  92449. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  92450. }
  92451. }
  92452. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  92453. if (halfCircleSide)
  92454. angle = -angle;
  92455. // Snapping logic
  92456. var snapped = false;
  92457. if (_this.snapDistance != 0) {
  92458. currentSnapDragDistance += angle;
  92459. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92460. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  92461. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92462. angle = _this.snapDistance * dragSteps;
  92463. snapped = true;
  92464. }
  92465. else {
  92466. angle = 0;
  92467. }
  92468. }
  92469. // If the mesh has a parent, convert needed world rotation to local rotation
  92470. tmpMatrix.reset();
  92471. if (_this.attachedMesh.parent) {
  92472. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  92473. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  92474. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  92475. }
  92476. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  92477. var quaternionCoefficient = Math.sin(angle / 2);
  92478. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  92479. // 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
  92480. if (tmpMatrix.determinant() > 0) {
  92481. amountToRotate.toEulerAnglesToRef(tmpVector);
  92482. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  92483. }
  92484. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  92485. // Rotate selected mesh quaternion over fixed axis
  92486. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  92487. }
  92488. else {
  92489. // Rotate selected mesh quaternion over rotated axis
  92490. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  92491. }
  92492. lastDragPosition.copyFrom(event.dragPlanePoint);
  92493. if (snapped) {
  92494. tmpSnapEvent.snapDistance = angle;
  92495. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92496. }
  92497. }
  92498. });
  92499. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92500. if (_this._customMeshSet) {
  92501. return;
  92502. }
  92503. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92504. var material = isHovered ? hoverMaterial : coloredMaterial;
  92505. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92506. m.material = material;
  92507. if (m.color) {
  92508. m.color = material.emissiveColor;
  92509. }
  92510. });
  92511. });
  92512. return _this;
  92513. }
  92514. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  92515. if (this.dragBehavior) {
  92516. this.dragBehavior.enabled = value ? true : false;
  92517. }
  92518. };
  92519. /**
  92520. * Disposes of the gizmo
  92521. */
  92522. PlaneRotationGizmo.prototype.dispose = function () {
  92523. this.onSnapObservable.clear();
  92524. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92525. this.dragBehavior.detach();
  92526. _super.prototype.dispose.call(this);
  92527. };
  92528. return PlaneRotationGizmo;
  92529. }(BABYLON.Gizmo));
  92530. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  92531. })(BABYLON || (BABYLON = {}));
  92532. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  92533. var BABYLON;
  92534. (function (BABYLON) {
  92535. /**
  92536. * Gizmo that enables dragging a mesh along 3 axis
  92537. */
  92538. var PositionGizmo = /** @class */ (function (_super) {
  92539. __extends(PositionGizmo, _super);
  92540. /**
  92541. * Creates a PositionGizmo
  92542. * @param gizmoLayer The utility layer the gizmo will be added to
  92543. */
  92544. function PositionGizmo(gizmoLayer) {
  92545. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92546. var _this = _super.call(this, gizmoLayer) || this;
  92547. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92548. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92549. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92550. _this.attachedMesh = null;
  92551. return _this;
  92552. }
  92553. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  92554. set: function (mesh) {
  92555. if (this.xGizmo) {
  92556. this.xGizmo.attachedMesh = mesh;
  92557. this.yGizmo.attachedMesh = mesh;
  92558. this.zGizmo.attachedMesh = mesh;
  92559. }
  92560. },
  92561. enumerable: true,
  92562. configurable: true
  92563. });
  92564. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92565. get: function () {
  92566. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92567. },
  92568. set: function (value) {
  92569. if (this.xGizmo) {
  92570. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92571. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92572. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92573. }
  92574. },
  92575. enumerable: true,
  92576. configurable: true
  92577. });
  92578. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  92579. get: function () {
  92580. return this.xGizmo.snapDistance;
  92581. },
  92582. /**
  92583. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92584. */
  92585. set: function (value) {
  92586. if (this.xGizmo) {
  92587. this.xGizmo.snapDistance = value;
  92588. this.yGizmo.snapDistance = value;
  92589. this.zGizmo.snapDistance = value;
  92590. }
  92591. },
  92592. enumerable: true,
  92593. configurable: true
  92594. });
  92595. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  92596. get: function () {
  92597. return this.xGizmo.scaleRatio;
  92598. },
  92599. /**
  92600. * Ratio for the scale of the gizmo (Default: 1)
  92601. */
  92602. set: function (value) {
  92603. if (this.xGizmo) {
  92604. this.xGizmo.scaleRatio = value;
  92605. this.yGizmo.scaleRatio = value;
  92606. this.zGizmo.scaleRatio = value;
  92607. }
  92608. },
  92609. enumerable: true,
  92610. configurable: true
  92611. });
  92612. /**
  92613. * Disposes of the gizmo
  92614. */
  92615. PositionGizmo.prototype.dispose = function () {
  92616. this.xGizmo.dispose();
  92617. this.yGizmo.dispose();
  92618. this.zGizmo.dispose();
  92619. };
  92620. /**
  92621. * CustomMeshes are not supported by this gizmo
  92622. * @param mesh The mesh to replace the default mesh of the gizmo
  92623. */
  92624. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  92625. 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)");
  92626. };
  92627. return PositionGizmo;
  92628. }(BABYLON.Gizmo));
  92629. BABYLON.PositionGizmo = PositionGizmo;
  92630. })(BABYLON || (BABYLON = {}));
  92631. //# sourceMappingURL=babylon.positionGizmo.js.map
  92632. var BABYLON;
  92633. (function (BABYLON) {
  92634. /**
  92635. * Gizmo that enables rotating a mesh along 3 axis
  92636. */
  92637. var RotationGizmo = /** @class */ (function (_super) {
  92638. __extends(RotationGizmo, _super);
  92639. /**
  92640. * Creates a RotationGizmo
  92641. * @param gizmoLayer The utility layer the gizmo will be added to
  92642. */
  92643. function RotationGizmo(gizmoLayer) {
  92644. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92645. var _this = _super.call(this, gizmoLayer) || this;
  92646. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92647. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92648. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92649. _this.attachedMesh = null;
  92650. return _this;
  92651. }
  92652. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  92653. set: function (mesh) {
  92654. if (this.xGizmo) {
  92655. this.xGizmo.attachedMesh = mesh;
  92656. this.yGizmo.attachedMesh = mesh;
  92657. this.zGizmo.attachedMesh = mesh;
  92658. }
  92659. },
  92660. enumerable: true,
  92661. configurable: true
  92662. });
  92663. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92664. get: function () {
  92665. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92666. },
  92667. set: function (value) {
  92668. if (this.xGizmo) {
  92669. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92670. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92671. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92672. }
  92673. },
  92674. enumerable: true,
  92675. configurable: true
  92676. });
  92677. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  92678. get: function () {
  92679. return this.xGizmo.snapDistance;
  92680. },
  92681. /**
  92682. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92683. */
  92684. set: function (value) {
  92685. if (this.xGizmo) {
  92686. this.xGizmo.snapDistance = value;
  92687. this.yGizmo.snapDistance = value;
  92688. this.zGizmo.snapDistance = value;
  92689. }
  92690. },
  92691. enumerable: true,
  92692. configurable: true
  92693. });
  92694. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  92695. get: function () {
  92696. return this.xGizmo.scaleRatio;
  92697. },
  92698. /**
  92699. * Ratio for the scale of the gizmo (Default: 1)
  92700. */
  92701. set: function (value) {
  92702. if (this.xGizmo) {
  92703. this.xGizmo.scaleRatio = value;
  92704. this.yGizmo.scaleRatio = value;
  92705. this.zGizmo.scaleRatio = value;
  92706. }
  92707. },
  92708. enumerable: true,
  92709. configurable: true
  92710. });
  92711. /**
  92712. * Disposes of the gizmo
  92713. */
  92714. RotationGizmo.prototype.dispose = function () {
  92715. this.xGizmo.dispose();
  92716. this.yGizmo.dispose();
  92717. this.zGizmo.dispose();
  92718. };
  92719. /**
  92720. * CustomMeshes are not supported by this gizmo
  92721. * @param mesh The mesh to replace the default mesh of the gizmo
  92722. */
  92723. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  92724. 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)");
  92725. };
  92726. return RotationGizmo;
  92727. }(BABYLON.Gizmo));
  92728. BABYLON.RotationGizmo = RotationGizmo;
  92729. })(BABYLON || (BABYLON = {}));
  92730. //# sourceMappingURL=babylon.rotationGizmo.js.map
  92731. var BABYLON;
  92732. (function (BABYLON) {
  92733. /**
  92734. * Gizmo that enables scaling a mesh along 3 axis
  92735. */
  92736. var ScaleGizmo = /** @class */ (function (_super) {
  92737. __extends(ScaleGizmo, _super);
  92738. /**
  92739. * Creates a ScaleGizmo
  92740. * @param gizmoLayer The utility layer the gizmo will be added to
  92741. */
  92742. function ScaleGizmo(gizmoLayer) {
  92743. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92744. var _this = _super.call(this, gizmoLayer) || this;
  92745. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92746. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92747. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92748. // Create uniform scale gizmo
  92749. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  92750. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  92751. _this._uniformGizmo.uniformScaling = true;
  92752. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  92753. octahedron.scaling.scaleInPlace(0.007);
  92754. _this._uniformGizmo.setCustomMesh(octahedron, true);
  92755. _this.attachedMesh = null;
  92756. return _this;
  92757. }
  92758. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  92759. set: function (mesh) {
  92760. if (this.xGizmo) {
  92761. this.xGizmo.attachedMesh = mesh;
  92762. this.yGizmo.attachedMesh = mesh;
  92763. this.zGizmo.attachedMesh = mesh;
  92764. this._uniformGizmo.attachedMesh = mesh;
  92765. }
  92766. },
  92767. enumerable: true,
  92768. configurable: true
  92769. });
  92770. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92771. get: function () {
  92772. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92773. },
  92774. set: function (value) {
  92775. if (this.xGizmo) {
  92776. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92777. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92778. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92779. }
  92780. },
  92781. enumerable: true,
  92782. configurable: true
  92783. });
  92784. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  92785. get: function () {
  92786. return this.xGizmo.snapDistance;
  92787. },
  92788. /**
  92789. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92790. */
  92791. set: function (value) {
  92792. if (this.xGizmo) {
  92793. this.xGizmo.snapDistance = value;
  92794. this.yGizmo.snapDistance = value;
  92795. this.zGizmo.snapDistance = value;
  92796. this._uniformGizmo.snapDistance = value;
  92797. }
  92798. },
  92799. enumerable: true,
  92800. configurable: true
  92801. });
  92802. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  92803. get: function () {
  92804. return this.xGizmo.scaleRatio;
  92805. },
  92806. /**
  92807. * Ratio for the scale of the gizmo (Default: 1)
  92808. */
  92809. set: function (value) {
  92810. if (this.xGizmo) {
  92811. this.xGizmo.scaleRatio = value;
  92812. this.yGizmo.scaleRatio = value;
  92813. this.zGizmo.scaleRatio = value;
  92814. this._uniformGizmo.scaleRatio = value;
  92815. }
  92816. },
  92817. enumerable: true,
  92818. configurable: true
  92819. });
  92820. /**
  92821. * Disposes of the gizmo
  92822. */
  92823. ScaleGizmo.prototype.dispose = function () {
  92824. this.xGizmo.dispose();
  92825. this.yGizmo.dispose();
  92826. this.zGizmo.dispose();
  92827. this._uniformGizmo.dispose();
  92828. };
  92829. return ScaleGizmo;
  92830. }(BABYLON.Gizmo));
  92831. BABYLON.ScaleGizmo = ScaleGizmo;
  92832. })(BABYLON || (BABYLON = {}));
  92833. //# sourceMappingURL=babylon.scaleGizmo.js.map
  92834. var BABYLON;
  92835. (function (BABYLON) {
  92836. /**
  92837. * Bounding box gizmo
  92838. */
  92839. var BoundingBoxGizmo = /** @class */ (function (_super) {
  92840. __extends(BoundingBoxGizmo, _super);
  92841. /**
  92842. * Creates an BoundingBoxGizmo
  92843. * @param gizmoLayer The utility layer the gizmo will be added to
  92844. * @param color The color of the gizmo
  92845. */
  92846. function BoundingBoxGizmo(color, gizmoLayer) {
  92847. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92848. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  92849. var _this = _super.call(this, gizmoLayer) || this;
  92850. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  92851. _this._renderObserver = null;
  92852. _this._pointerObserver = null;
  92853. _this._scaleDragSpeed = 0.2;
  92854. _this._tmpQuaternion = new BABYLON.Quaternion();
  92855. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  92856. _this._tmpRotationMatrix = new BABYLON.Matrix();
  92857. /**
  92858. * 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)
  92859. */
  92860. _this.ignoreChildren = false;
  92861. /**
  92862. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  92863. */
  92864. _this.rotationSphereSize = 0.1;
  92865. /**
  92866. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  92867. */
  92868. _this.scaleBoxSize = 0.1;
  92869. /**
  92870. * 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)
  92871. */
  92872. _this.fixedDragMeshScreenSize = false;
  92873. /**
  92874. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  92875. */
  92876. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  92877. /**
  92878. * Fired when a rotation sphere or scale box is dragged
  92879. */
  92880. _this.onDragStartObservable = new BABYLON.Observable();
  92881. /**
  92882. * Fired when a scale box is dragged
  92883. */
  92884. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  92885. /**
  92886. * Fired when a scale box drag is ended
  92887. */
  92888. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  92889. /**
  92890. * Fired when a rotation sphere is dragged
  92891. */
  92892. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  92893. /**
  92894. * Fired when a rotation sphere drag is ended
  92895. */
  92896. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  92897. /**
  92898. * 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)
  92899. */
  92900. _this.scalePivot = null;
  92901. _this._existingMeshScale = new BABYLON.Vector3();
  92902. _this._oldPivotPoint = new BABYLON.Vector3();
  92903. _this._pivotTranslation = new BABYLON.Vector3();
  92904. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  92905. _this._updateScale = false;
  92906. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  92907. // Create Materials
  92908. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92909. coloredMaterial.disableLighting = true;
  92910. coloredMaterial.emissiveColor = color;
  92911. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92912. hoverColoredMaterial.disableLighting = true;
  92913. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92914. // Build bounding box out of lines
  92915. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92916. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  92917. var lines = [];
  92918. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  92919. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  92920. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  92921. 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));
  92922. 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));
  92923. 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));
  92924. 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));
  92925. 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));
  92926. 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));
  92927. 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));
  92928. 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));
  92929. 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));
  92930. lines.forEach(function (l) {
  92931. l.color = color;
  92932. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  92933. l.isPickable = false;
  92934. _this._lineBoundingBox.addChild(l);
  92935. });
  92936. _this._rootMesh.addChild(_this._lineBoundingBox);
  92937. // Create rotation spheres
  92938. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92939. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  92940. var _loop_1 = function (i_1) {
  92941. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  92942. sphere.rotationQuaternion = new BABYLON.Quaternion();
  92943. sphere.material = coloredMaterial;
  92944. // Drag behavior
  92945. _dragBehavior = new BABYLON.PointerDragBehavior({});
  92946. _dragBehavior.moveAttached = false;
  92947. _dragBehavior.updateDragPlane = false;
  92948. sphere.addBehavior(_dragBehavior);
  92949. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  92950. var totalTurnAmountOfDrag = 0;
  92951. _dragBehavior.onDragStartObservable.add(function (event) {
  92952. startingTurnDirection.copyFrom(sphere.forward);
  92953. totalTurnAmountOfDrag = 0;
  92954. });
  92955. _dragBehavior.onDragObservable.add(function (event) {
  92956. _this.onRotationSphereDragObservable.notifyObservers({});
  92957. if (_this.attachedMesh) {
  92958. _this.removeAndStorePivotPoint();
  92959. var worldDragDirection = startingTurnDirection;
  92960. // Project the world right on to the drag plane
  92961. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  92962. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  92963. // project drag delta on to the resulting drag axis and rotate based on that
  92964. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  92965. // Make rotation relative to size of mesh.
  92966. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  92967. // Rotate based on axis
  92968. if (!_this.attachedMesh.rotationQuaternion) {
  92969. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  92970. }
  92971. if (!_this._anchorMesh.rotationQuaternion) {
  92972. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  92973. }
  92974. // Do not allow the object to turn more than a full circle
  92975. totalTurnAmountOfDrag += projectDist;
  92976. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  92977. if (i_1 >= 8) {
  92978. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  92979. }
  92980. else if (i_1 >= 4) {
  92981. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  92982. }
  92983. else {
  92984. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  92985. }
  92986. // Rotate around center of bounding box
  92987. _this._anchorMesh.addChild(_this.attachedMesh);
  92988. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  92989. _this._anchorMesh.removeChild(_this.attachedMesh);
  92990. }
  92991. _this.updateBoundingBox();
  92992. _this.restorePivotPoint();
  92993. }
  92994. });
  92995. // Selection/deselection
  92996. _dragBehavior.onDragStartObservable.add(function () {
  92997. _this.onDragStartObservable.notifyObservers({});
  92998. _this._selectNode(sphere);
  92999. });
  93000. _dragBehavior.onDragEndObservable.add(function () {
  93001. _this.onRotationSphereDragEndObservable.notifyObservers({});
  93002. _this._selectNode(null);
  93003. });
  93004. this_1._rotateSpheresParent.addChild(sphere);
  93005. };
  93006. var this_1 = this, _dragBehavior;
  93007. for (var i_1 = 0; i_1 < 12; i_1++) {
  93008. _loop_1(i_1);
  93009. }
  93010. _this._rootMesh.addChild(_this._rotateSpheresParent);
  93011. // Create scale cubes
  93012. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93013. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  93014. for (var i = 0; i < 2; i++) {
  93015. for (var j = 0; j < 2; j++) {
  93016. var _loop_2 = function () {
  93017. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  93018. box.material = coloredMaterial;
  93019. // Dragging logic
  93020. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  93021. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93022. _dragBehavior.moveAttached = false;
  93023. box.addBehavior(_dragBehavior);
  93024. _dragBehavior.onDragObservable.add(function (event) {
  93025. _this.onScaleBoxDragObservable.notifyObservers({});
  93026. if (_this.attachedMesh) {
  93027. _this.removeAndStorePivotPoint();
  93028. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  93029. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  93030. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  93031. _this.updateBoundingBox();
  93032. if (_this.scalePivot) {
  93033. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  93034. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  93035. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  93036. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  93037. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  93038. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  93039. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  93040. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  93041. }
  93042. else {
  93043. // Scale from the position of the opposite corner
  93044. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  93045. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  93046. }
  93047. _this._anchorMesh.addChild(_this.attachedMesh);
  93048. _this._anchorMesh.scaling.addInPlace(deltaScale);
  93049. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  93050. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  93051. }
  93052. _this._anchorMesh.removeChild(_this.attachedMesh);
  93053. _this.restorePivotPoint();
  93054. }
  93055. });
  93056. // Selection/deselection
  93057. _dragBehavior.onDragStartObservable.add(function () {
  93058. _this.onDragStartObservable.notifyObservers({});
  93059. _this._selectNode(box);
  93060. });
  93061. _dragBehavior.onDragEndObservable.add(function () {
  93062. _this.onScaleBoxDragEndObservable.notifyObservers({});
  93063. _this._selectNode(null);
  93064. });
  93065. this_2._scaleBoxesParent.addChild(box);
  93066. };
  93067. var this_2 = this, _dragBehavior;
  93068. for (var k = 0; k < 2; k++) {
  93069. _loop_2();
  93070. }
  93071. }
  93072. }
  93073. _this._rootMesh.addChild(_this._scaleBoxesParent);
  93074. // Hover color change
  93075. var pointerIds = new Array();
  93076. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93077. if (!pointerIds[pointerInfo.event.pointerId]) {
  93078. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  93079. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  93080. pointerIds[pointerInfo.event.pointerId] = mesh;
  93081. mesh.material = hoverColoredMaterial;
  93082. }
  93083. });
  93084. }
  93085. else {
  93086. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  93087. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  93088. delete pointerIds[pointerInfo.event.pointerId];
  93089. }
  93090. }
  93091. });
  93092. // Update bounding box positions
  93093. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  93094. // Only update the bouding box if scaling has changed
  93095. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  93096. _this.updateBoundingBox();
  93097. }
  93098. });
  93099. _this.updateBoundingBox();
  93100. return _this;
  93101. }
  93102. BoundingBoxGizmo.prototype.removeAndStorePivotPoint = function () {
  93103. if (this.attachedMesh) {
  93104. // Save old pivot and set pivot to 0,0,0
  93105. this.attachedMesh.getPivotPointToRef(this._oldPivotPoint);
  93106. if (this._oldPivotPoint.equalsToFloats(0, 0, 0)) {
  93107. return;
  93108. }
  93109. this.attachedMesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  93110. this._oldPivotPoint.subtractToRef(this.attachedMesh.getPivotPoint(), this._pivotTranslation);
  93111. this._tmpVector.copyFromFloats(1, 1, 1);
  93112. this._tmpVector.subtractInPlace(this.attachedMesh.scaling);
  93113. this._tmpVector.multiplyInPlace(this._pivotTranslation);
  93114. this.attachedMesh.position.addInPlace(this._tmpVector);
  93115. }
  93116. };
  93117. BoundingBoxGizmo.prototype.restorePivotPoint = function () {
  93118. if (this.attachedMesh && !this._oldPivotPoint.equalsToFloats(0, 0, 0)) {
  93119. this.attachedMesh.setPivotPoint(this._oldPivotPoint);
  93120. this._oldPivotPoint.subtractToRef(this.attachedMesh.getPivotPoint(), this._pivotTranslation);
  93121. this._tmpVector.copyFromFloats(1, 1, 1);
  93122. this._tmpVector.subtractInPlace(this.attachedMesh.scaling);
  93123. this._tmpVector.multiplyInPlace(this._pivotTranslation);
  93124. this.attachedMesh.position.subtractInPlace(this._tmpVector);
  93125. }
  93126. };
  93127. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  93128. if (value) {
  93129. // Reset anchor mesh to match attached mesh's scale
  93130. // This is needed to avoid invalid box/sphere position on first drag
  93131. this._anchorMesh.addChild(value);
  93132. this._anchorMesh.removeChild(value);
  93133. this.updateBoundingBox();
  93134. }
  93135. };
  93136. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  93137. this._rotateSpheresParent.getChildMeshes()
  93138. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  93139. m.isVisible = (!selectedMesh || m == selectedMesh);
  93140. });
  93141. };
  93142. BoundingBoxGizmo.prototype._recurseComputeWorld = function (node) {
  93143. var _this = this;
  93144. node.computeWorldMatrix(true);
  93145. if (!this.ignoreChildren) {
  93146. node.getDescendants().forEach(function (n) {
  93147. _this._recurseComputeWorld(n);
  93148. });
  93149. }
  93150. };
  93151. /**
  93152. * Updates the bounding box information for the Gizmo
  93153. */
  93154. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  93155. if (this.attachedMesh) {
  93156. this.removeAndStorePivotPoint();
  93157. this._update();
  93158. // Rotate based on axis
  93159. if (!this.attachedMesh.rotationQuaternion) {
  93160. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  93161. }
  93162. if (!this._anchorMesh.rotationQuaternion) {
  93163. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  93164. }
  93165. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  93166. // Store original position and reset mesh to origin before computing the bounding box
  93167. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  93168. this._tmpVector.copyFrom(this.attachedMesh.position);
  93169. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  93170. this.attachedMesh.position.set(0, 0, 0);
  93171. // Update bounding dimensions/positions
  93172. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren);
  93173. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  93174. // Update gizmo to match bounding box scaling and rotation
  93175. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  93176. 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);
  93177. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  93178. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  93179. this._lineBoundingBox.computeWorldMatrix();
  93180. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  93181. // restore position/rotation values
  93182. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  93183. this.attachedMesh.position.copyFrom(this._tmpVector);
  93184. this._recurseComputeWorld(this.attachedMesh);
  93185. }
  93186. // Update rotation sphere locations
  93187. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  93188. for (var i = 0; i < 3; i++) {
  93189. for (var j = 0; j < 2; j++) {
  93190. for (var k = 0; k < 2; k++) {
  93191. var index = ((i * 4) + (j * 2)) + k;
  93192. if (i == 0) {
  93193. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  93194. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93195. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93196. }
  93197. if (i == 1) {
  93198. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  93199. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93200. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93201. }
  93202. if (i == 2) {
  93203. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  93204. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93205. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93206. }
  93207. if (this.fixedDragMeshScreenSize) {
  93208. this._rootMesh.computeWorldMatrix();
  93209. this._rotateSpheresParent.computeWorldMatrix();
  93210. rotateSpheres[index].computeWorldMatrix();
  93211. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  93212. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  93213. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  93214. }
  93215. else {
  93216. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  93217. }
  93218. }
  93219. }
  93220. }
  93221. // Update scale box locations
  93222. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  93223. for (var i = 0; i < 2; i++) {
  93224. for (var j = 0; j < 2; j++) {
  93225. for (var k = 0; k < 2; k++) {
  93226. var index = ((i * 4) + (j * 2)) + k;
  93227. if (scaleBoxes[index]) {
  93228. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  93229. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93230. if (this.fixedDragMeshScreenSize) {
  93231. this._rootMesh.computeWorldMatrix();
  93232. this._scaleBoxesParent.computeWorldMatrix();
  93233. scaleBoxes[index].computeWorldMatrix();
  93234. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  93235. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  93236. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  93237. }
  93238. else {
  93239. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  93240. }
  93241. }
  93242. }
  93243. }
  93244. }
  93245. if (this.attachedMesh) {
  93246. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  93247. this.restorePivotPoint();
  93248. }
  93249. };
  93250. /**
  93251. * Enables rotation on the specified axis and disables rotation on the others
  93252. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  93253. */
  93254. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  93255. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  93256. if (i < 4) {
  93257. m.setEnabled(axis.indexOf("x") != -1);
  93258. }
  93259. else if (i < 8) {
  93260. m.setEnabled(axis.indexOf("y") != -1);
  93261. }
  93262. else {
  93263. m.setEnabled(axis.indexOf("z") != -1);
  93264. }
  93265. });
  93266. };
  93267. /**
  93268. * Disposes of the gizmo
  93269. */
  93270. BoundingBoxGizmo.prototype.dispose = function () {
  93271. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93272. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  93273. this._lineBoundingBox.dispose();
  93274. this._rotateSpheresParent.dispose();
  93275. this._scaleBoxesParent.dispose();
  93276. _super.prototype.dispose.call(this);
  93277. };
  93278. /**
  93279. * 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)
  93280. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  93281. * @returns the bounding box mesh with the passed in mesh as a child
  93282. */
  93283. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  93284. var makeNotPickable = function (root) {
  93285. root.isPickable = false;
  93286. root.getChildMeshes().forEach(function (c) {
  93287. makeNotPickable(c);
  93288. });
  93289. };
  93290. makeNotPickable(mesh);
  93291. // Reset position to get boudning box from origin with no rotation
  93292. if (!mesh.rotationQuaternion) {
  93293. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  93294. }
  93295. var oldPos = mesh.position.clone();
  93296. var oldRot = mesh.rotationQuaternion.clone();
  93297. mesh.rotationQuaternion.set(0, 0, 0, 1);
  93298. mesh.position.set(0, 0, 0);
  93299. // Update bounding dimensions/positions
  93300. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  93301. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  93302. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  93303. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  93304. // Restore original positions
  93305. mesh.addChild(box);
  93306. mesh.rotationQuaternion.copyFrom(oldRot);
  93307. mesh.position.copyFrom(oldPos);
  93308. // Reverse parenting
  93309. mesh.removeChild(box);
  93310. box.addChild(mesh);
  93311. box.visibility = 0;
  93312. return box;
  93313. };
  93314. /**
  93315. * CustomMeshes are not supported by this gizmo
  93316. * @param mesh The mesh to replace the default mesh of the gizmo
  93317. */
  93318. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  93319. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  93320. };
  93321. return BoundingBoxGizmo;
  93322. }(BABYLON.Gizmo));
  93323. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  93324. })(BABYLON || (BABYLON = {}));
  93325. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  93326. var BABYLON;
  93327. (function (BABYLON) {
  93328. /**
  93329. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  93330. */
  93331. var GizmoManager = /** @class */ (function () {
  93332. /**
  93333. * Instatiates a gizmo manager
  93334. * @param scene the scene to overlay the gizmos on top of
  93335. */
  93336. function GizmoManager(scene) {
  93337. var _this = this;
  93338. this.scene = scene;
  93339. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  93340. this._pointerObserver = null;
  93341. this._attachedMesh = null;
  93342. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  93343. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  93344. /**
  93345. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  93346. */
  93347. this.attachableMeshes = null;
  93348. /**
  93349. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  93350. */
  93351. this.usePointerToAttachGizmos = true;
  93352. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  93353. // Instatiate/dispose gizmos based on pointer actions
  93354. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  93355. if (!_this.usePointerToAttachGizmos) {
  93356. return;
  93357. }
  93358. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93359. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  93360. var node = pointerInfo.pickInfo.pickedMesh;
  93361. if (_this.attachableMeshes == null) {
  93362. // Attach to the most parent node
  93363. while (node && node.parent != null) {
  93364. node = node.parent;
  93365. }
  93366. }
  93367. else {
  93368. // Attach to the parent node that is an attachableMesh
  93369. var found = false;
  93370. _this.attachableMeshes.forEach(function (mesh) {
  93371. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  93372. node = mesh;
  93373. found = true;
  93374. }
  93375. });
  93376. if (!found) {
  93377. node = null;
  93378. }
  93379. }
  93380. if (node instanceof BABYLON.AbstractMesh) {
  93381. _this.attachToMesh(node);
  93382. }
  93383. else {
  93384. _this.attachToMesh(null);
  93385. }
  93386. }
  93387. else {
  93388. _this.attachToMesh(null);
  93389. }
  93390. }
  93391. });
  93392. }
  93393. /**
  93394. * Attaches a set of gizmos to the specified mesh
  93395. * @param mesh The mesh the gizmo's should be attached to
  93396. */
  93397. GizmoManager.prototype.attachToMesh = function (mesh) {
  93398. if (this._attachedMesh) {
  93399. this._attachedMesh.removeBehavior(this._dragBehavior);
  93400. }
  93401. this._attachedMesh = mesh;
  93402. for (var key in this.gizmos) {
  93403. var gizmo = (this.gizmos[key]);
  93404. if (gizmo && this._gizmosEnabled[key]) {
  93405. gizmo.attachedMesh = mesh;
  93406. }
  93407. }
  93408. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  93409. this._attachedMesh.addBehavior(this._dragBehavior);
  93410. }
  93411. };
  93412. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  93413. get: function () {
  93414. return this._gizmosEnabled.positionGizmo;
  93415. },
  93416. /**
  93417. * If the position gizmo is enabled
  93418. */
  93419. set: function (value) {
  93420. if (value) {
  93421. if (!this.gizmos.positionGizmo) {
  93422. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  93423. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93424. }
  93425. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  93426. }
  93427. else if (this.gizmos.positionGizmo) {
  93428. this.gizmos.positionGizmo.attachedMesh = null;
  93429. }
  93430. this._gizmosEnabled.positionGizmo = value;
  93431. },
  93432. enumerable: true,
  93433. configurable: true
  93434. });
  93435. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  93436. get: function () {
  93437. return this._gizmosEnabled.rotationGizmo;
  93438. },
  93439. /**
  93440. * If the rotation gizmo is enabled
  93441. */
  93442. set: function (value) {
  93443. if (value) {
  93444. if (!this.gizmos.rotationGizmo) {
  93445. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  93446. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93447. }
  93448. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  93449. }
  93450. else if (this.gizmos.rotationGizmo) {
  93451. this.gizmos.rotationGizmo.attachedMesh = null;
  93452. }
  93453. this._gizmosEnabled.rotationGizmo = value;
  93454. },
  93455. enumerable: true,
  93456. configurable: true
  93457. });
  93458. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  93459. get: function () {
  93460. return this._gizmosEnabled.scaleGizmo;
  93461. },
  93462. /**
  93463. * If the scale gizmo is enabled
  93464. */
  93465. set: function (value) {
  93466. if (value) {
  93467. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  93468. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  93469. }
  93470. else if (this.gizmos.scaleGizmo) {
  93471. this.gizmos.scaleGizmo.attachedMesh = null;
  93472. }
  93473. this._gizmosEnabled.scaleGizmo = value;
  93474. },
  93475. enumerable: true,
  93476. configurable: true
  93477. });
  93478. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  93479. get: function () {
  93480. return this._gizmosEnabled.boundingBoxGizmo;
  93481. },
  93482. /**
  93483. * If the boundingBox gizmo is enabled
  93484. */
  93485. set: function (value) {
  93486. if (value) {
  93487. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  93488. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  93489. if (this._attachedMesh) {
  93490. this._attachedMesh.removeBehavior(this._dragBehavior);
  93491. this._attachedMesh.addBehavior(this._dragBehavior);
  93492. }
  93493. }
  93494. else if (this.gizmos.boundingBoxGizmo) {
  93495. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  93496. }
  93497. this._gizmosEnabled.boundingBoxGizmo = value;
  93498. },
  93499. enumerable: true,
  93500. configurable: true
  93501. });
  93502. /**
  93503. * Disposes of the gizmo manager
  93504. */
  93505. GizmoManager.prototype.dispose = function () {
  93506. this.scene.onPointerObservable.remove(this._pointerObserver);
  93507. for (var key in this.gizmos) {
  93508. var gizmo = (this.gizmos[key]);
  93509. if (gizmo) {
  93510. gizmo.dispose();
  93511. }
  93512. }
  93513. this._dragBehavior.detach();
  93514. };
  93515. return GizmoManager;
  93516. }());
  93517. BABYLON.GizmoManager = GizmoManager;
  93518. })(BABYLON || (BABYLON = {}));
  93519. //# sourceMappingURL=babylon.gizmoManager.js.map
  93520. var BABYLON;
  93521. (function (BABYLON) {
  93522. /**
  93523. * Defines a target to use with MorphTargetManager
  93524. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  93525. */
  93526. var MorphTarget = /** @class */ (function () {
  93527. /**
  93528. * Creates a new MorphTarget
  93529. * @param name defines the name of the target
  93530. * @param influence defines the influence to use
  93531. */
  93532. function MorphTarget(
  93533. /** defines the name of the target */
  93534. name, influence, scene) {
  93535. if (influence === void 0) { influence = 0; }
  93536. if (scene === void 0) { scene = null; }
  93537. this.name = name;
  93538. /**
  93539. * Gets or sets the list of animations
  93540. */
  93541. this.animations = new Array();
  93542. this._positions = null;
  93543. this._normals = null;
  93544. this._tangents = null;
  93545. /**
  93546. * Observable raised when the influence changes
  93547. */
  93548. this.onInfluenceChanged = new BABYLON.Observable();
  93549. this._animationPropertiesOverride = null;
  93550. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93551. this.influence = influence;
  93552. }
  93553. Object.defineProperty(MorphTarget.prototype, "influence", {
  93554. /**
  93555. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  93556. */
  93557. get: function () {
  93558. return this._influence;
  93559. },
  93560. set: function (influence) {
  93561. if (this._influence === influence) {
  93562. return;
  93563. }
  93564. var previous = this._influence;
  93565. this._influence = influence;
  93566. if (this.onInfluenceChanged.hasObservers) {
  93567. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  93568. }
  93569. },
  93570. enumerable: true,
  93571. configurable: true
  93572. });
  93573. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  93574. /**
  93575. * Gets or sets the animation properties override
  93576. */
  93577. get: function () {
  93578. if (!this._animationPropertiesOverride && this._scene) {
  93579. return this._scene.animationPropertiesOverride;
  93580. }
  93581. return this._animationPropertiesOverride;
  93582. },
  93583. set: function (value) {
  93584. this._animationPropertiesOverride = value;
  93585. },
  93586. enumerable: true,
  93587. configurable: true
  93588. });
  93589. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  93590. /**
  93591. * Gets a boolean defining if the target contains position data
  93592. */
  93593. get: function () {
  93594. return !!this._positions;
  93595. },
  93596. enumerable: true,
  93597. configurable: true
  93598. });
  93599. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  93600. /**
  93601. * Gets a boolean defining if the target contains normal data
  93602. */
  93603. get: function () {
  93604. return !!this._normals;
  93605. },
  93606. enumerable: true,
  93607. configurable: true
  93608. });
  93609. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  93610. /**
  93611. * Gets a boolean defining if the target contains tangent data
  93612. */
  93613. get: function () {
  93614. return !!this._tangents;
  93615. },
  93616. enumerable: true,
  93617. configurable: true
  93618. });
  93619. /**
  93620. * Affects position data to this target
  93621. * @param data defines the position data to use
  93622. */
  93623. MorphTarget.prototype.setPositions = function (data) {
  93624. this._positions = data;
  93625. };
  93626. /**
  93627. * Gets the position data stored in this target
  93628. * @returns a FloatArray containing the position data (or null if not present)
  93629. */
  93630. MorphTarget.prototype.getPositions = function () {
  93631. return this._positions;
  93632. };
  93633. /**
  93634. * Affects normal data to this target
  93635. * @param data defines the normal data to use
  93636. */
  93637. MorphTarget.prototype.setNormals = function (data) {
  93638. this._normals = data;
  93639. };
  93640. /**
  93641. * Gets the normal data stored in this target
  93642. * @returns a FloatArray containing the normal data (or null if not present)
  93643. */
  93644. MorphTarget.prototype.getNormals = function () {
  93645. return this._normals;
  93646. };
  93647. /**
  93648. * Affects tangent data to this target
  93649. * @param data defines the tangent data to use
  93650. */
  93651. MorphTarget.prototype.setTangents = function (data) {
  93652. this._tangents = data;
  93653. };
  93654. /**
  93655. * Gets the tangent data stored in this target
  93656. * @returns a FloatArray containing the tangent data (or null if not present)
  93657. */
  93658. MorphTarget.prototype.getTangents = function () {
  93659. return this._tangents;
  93660. };
  93661. /**
  93662. * Serializes the current target into a Serialization object
  93663. * @returns the serialized object
  93664. */
  93665. MorphTarget.prototype.serialize = function () {
  93666. var serializationObject = {};
  93667. serializationObject.name = this.name;
  93668. serializationObject.influence = this.influence;
  93669. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  93670. if (this.hasNormals) {
  93671. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  93672. }
  93673. if (this.hasTangents) {
  93674. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  93675. }
  93676. // Animations
  93677. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  93678. return serializationObject;
  93679. };
  93680. // Statics
  93681. /**
  93682. * Creates a new target from serialized data
  93683. * @param serializationObject defines the serialized data to use
  93684. * @returns a new MorphTarget
  93685. */
  93686. MorphTarget.Parse = function (serializationObject) {
  93687. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  93688. result.setPositions(serializationObject.positions);
  93689. if (serializationObject.normals) {
  93690. result.setNormals(serializationObject.normals);
  93691. }
  93692. if (serializationObject.tangents) {
  93693. result.setTangents(serializationObject.tangents);
  93694. }
  93695. // Animations
  93696. if (serializationObject.animations) {
  93697. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  93698. var parsedAnimation = serializationObject.animations[animationIndex];
  93699. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  93700. }
  93701. }
  93702. return result;
  93703. };
  93704. /**
  93705. * Creates a MorphTarget from mesh data
  93706. * @param mesh defines the source mesh
  93707. * @param name defines the name to use for the new target
  93708. * @param influence defines the influence to attach to the target
  93709. * @returns a new MorphTarget
  93710. */
  93711. MorphTarget.FromMesh = function (mesh, name, influence) {
  93712. if (!name) {
  93713. name = mesh.name;
  93714. }
  93715. var result = new MorphTarget(name, influence, mesh.getScene());
  93716. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  93717. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  93718. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  93719. }
  93720. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  93721. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  93722. }
  93723. return result;
  93724. };
  93725. return MorphTarget;
  93726. }());
  93727. BABYLON.MorphTarget = MorphTarget;
  93728. })(BABYLON || (BABYLON = {}));
  93729. //# sourceMappingURL=babylon.morphTarget.js.map
  93730. var BABYLON;
  93731. (function (BABYLON) {
  93732. /**
  93733. * This class is used to deform meshes using morphing between different targets
  93734. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  93735. */
  93736. var MorphTargetManager = /** @class */ (function () {
  93737. /**
  93738. * Creates a new MorphTargetManager
  93739. * @param scene defines the current scene
  93740. */
  93741. function MorphTargetManager(scene) {
  93742. if (scene === void 0) { scene = null; }
  93743. this._targets = new Array();
  93744. this._targetObservable = new Array();
  93745. this._activeTargets = new BABYLON.SmartArray(16);
  93746. this._supportsNormals = false;
  93747. this._supportsTangents = false;
  93748. this._vertexCount = 0;
  93749. this._uniqueId = 0;
  93750. this._tempInfluences = new Array();
  93751. if (!scene) {
  93752. scene = BABYLON.Engine.LastCreatedScene;
  93753. }
  93754. this._scene = scene;
  93755. if (this._scene) {
  93756. this._scene.morphTargetManagers.push(this);
  93757. this._uniqueId = this._scene.getUniqueId();
  93758. }
  93759. }
  93760. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  93761. /**
  93762. * Gets the unique ID of this manager
  93763. */
  93764. get: function () {
  93765. return this._uniqueId;
  93766. },
  93767. enumerable: true,
  93768. configurable: true
  93769. });
  93770. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  93771. /**
  93772. * Gets the number of vertices handled by this manager
  93773. */
  93774. get: function () {
  93775. return this._vertexCount;
  93776. },
  93777. enumerable: true,
  93778. configurable: true
  93779. });
  93780. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  93781. /**
  93782. * Gets a boolean indicating if this manager supports morphing of normals
  93783. */
  93784. get: function () {
  93785. return this._supportsNormals;
  93786. },
  93787. enumerable: true,
  93788. configurable: true
  93789. });
  93790. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  93791. /**
  93792. * Gets a boolean indicating if this manager supports morphing of tangents
  93793. */
  93794. get: function () {
  93795. return this._supportsTangents;
  93796. },
  93797. enumerable: true,
  93798. configurable: true
  93799. });
  93800. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  93801. /**
  93802. * Gets the number of targets stored in this manager
  93803. */
  93804. get: function () {
  93805. return this._targets.length;
  93806. },
  93807. enumerable: true,
  93808. configurable: true
  93809. });
  93810. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  93811. /**
  93812. * Gets the number of influencers (ie. the number of targets with influences > 0)
  93813. */
  93814. get: function () {
  93815. return this._activeTargets.length;
  93816. },
  93817. enumerable: true,
  93818. configurable: true
  93819. });
  93820. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  93821. /**
  93822. * Gets the list of influences (one per target)
  93823. */
  93824. get: function () {
  93825. return this._influences;
  93826. },
  93827. enumerable: true,
  93828. configurable: true
  93829. });
  93830. /**
  93831. * Gets the active target at specified index. An active target is a target with an influence > 0
  93832. * @param index defines the index to check
  93833. * @returns the requested target
  93834. */
  93835. MorphTargetManager.prototype.getActiveTarget = function (index) {
  93836. return this._activeTargets.data[index];
  93837. };
  93838. /**
  93839. * Gets the target at specified index
  93840. * @param index defines the index to check
  93841. * @returns the requested target
  93842. */
  93843. MorphTargetManager.prototype.getTarget = function (index) {
  93844. return this._targets[index];
  93845. };
  93846. /**
  93847. * Add a new target to this manager
  93848. * @param target defines the target to add
  93849. */
  93850. MorphTargetManager.prototype.addTarget = function (target) {
  93851. var _this = this;
  93852. this._targets.push(target);
  93853. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  93854. _this._syncActiveTargets(needUpdate);
  93855. }));
  93856. this._syncActiveTargets(true);
  93857. };
  93858. /**
  93859. * Removes a target from the manager
  93860. * @param target defines the target to remove
  93861. */
  93862. MorphTargetManager.prototype.removeTarget = function (target) {
  93863. var index = this._targets.indexOf(target);
  93864. if (index >= 0) {
  93865. this._targets.splice(index, 1);
  93866. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  93867. this._syncActiveTargets(true);
  93868. }
  93869. };
  93870. /**
  93871. * Serializes the current manager into a Serialization object
  93872. * @returns the serialized object
  93873. */
  93874. MorphTargetManager.prototype.serialize = function () {
  93875. var serializationObject = {};
  93876. serializationObject.id = this.uniqueId;
  93877. serializationObject.targets = [];
  93878. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  93879. var target = _a[_i];
  93880. serializationObject.targets.push(target.serialize());
  93881. }
  93882. return serializationObject;
  93883. };
  93884. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  93885. var influenceCount = 0;
  93886. this._activeTargets.reset();
  93887. this._supportsNormals = true;
  93888. this._supportsTangents = true;
  93889. this._vertexCount = 0;
  93890. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  93891. var target = _a[_i];
  93892. this._activeTargets.push(target);
  93893. this._tempInfluences[influenceCount++] = target.influence;
  93894. var positions = target.getPositions();
  93895. if (positions) {
  93896. this._supportsNormals = this._supportsNormals && target.hasNormals;
  93897. this._supportsTangents = this._supportsTangents && target.hasTangents;
  93898. var vertexCount = positions.length / 3;
  93899. if (this._vertexCount === 0) {
  93900. this._vertexCount = vertexCount;
  93901. }
  93902. else if (this._vertexCount !== vertexCount) {
  93903. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  93904. return;
  93905. }
  93906. }
  93907. }
  93908. if (!this._influences || this._influences.length !== influenceCount) {
  93909. this._influences = new Float32Array(influenceCount);
  93910. }
  93911. for (var index = 0; index < influenceCount; index++) {
  93912. this._influences[index] = this._tempInfluences[index];
  93913. }
  93914. if (needUpdate) {
  93915. this.synchronize();
  93916. }
  93917. };
  93918. /**
  93919. * Syncrhonize the targets with all the meshes using this morph target manager
  93920. */
  93921. MorphTargetManager.prototype.synchronize = function () {
  93922. if (!this._scene) {
  93923. return;
  93924. }
  93925. // Flag meshes as dirty to resync with the active targets
  93926. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  93927. var mesh = _a[_i];
  93928. if (mesh.morphTargetManager === this) {
  93929. mesh._syncGeometryWithMorphTargetManager();
  93930. }
  93931. }
  93932. };
  93933. // Statics
  93934. /**
  93935. * Creates a new MorphTargetManager from serialized data
  93936. * @param serializationObject defines the serialized data
  93937. * @param scene defines the hosting scene
  93938. * @returns the new MorphTargetManager
  93939. */
  93940. MorphTargetManager.Parse = function (serializationObject, scene) {
  93941. var result = new MorphTargetManager(scene);
  93942. result._uniqueId = serializationObject.id;
  93943. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  93944. var targetData = _a[_i];
  93945. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  93946. }
  93947. return result;
  93948. };
  93949. return MorphTargetManager;
  93950. }());
  93951. BABYLON.MorphTargetManager = MorphTargetManager;
  93952. })(BABYLON || (BABYLON = {}));
  93953. //# sourceMappingURL=babylon.morphTargetManager.js.map
  93954. var BABYLON;
  93955. (function (BABYLON) {
  93956. var Octree = /** @class */ (function () {
  93957. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  93958. if (maxDepth === void 0) { maxDepth = 2; }
  93959. this.maxDepth = maxDepth;
  93960. this.dynamicContent = new Array();
  93961. this._maxBlockCapacity = maxBlockCapacity || 64;
  93962. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  93963. this._creationFunc = creationFunc;
  93964. }
  93965. // Methods
  93966. Octree.prototype.update = function (worldMin, worldMax, entries) {
  93967. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  93968. };
  93969. Octree.prototype.addMesh = function (entry) {
  93970. for (var index = 0; index < this.blocks.length; index++) {
  93971. var block = this.blocks[index];
  93972. block.addEntry(entry);
  93973. }
  93974. };
  93975. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  93976. this._selectionContent.reset();
  93977. for (var index = 0; index < this.blocks.length; index++) {
  93978. var block = this.blocks[index];
  93979. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  93980. }
  93981. if (allowDuplicate) {
  93982. this._selectionContent.concat(this.dynamicContent);
  93983. }
  93984. else {
  93985. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  93986. }
  93987. return this._selectionContent;
  93988. };
  93989. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  93990. this._selectionContent.reset();
  93991. for (var index = 0; index < this.blocks.length; index++) {
  93992. var block = this.blocks[index];
  93993. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  93994. }
  93995. if (allowDuplicate) {
  93996. this._selectionContent.concat(this.dynamicContent);
  93997. }
  93998. else {
  93999. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94000. }
  94001. return this._selectionContent;
  94002. };
  94003. Octree.prototype.intersectsRay = function (ray) {
  94004. this._selectionContent.reset();
  94005. for (var index = 0; index < this.blocks.length; index++) {
  94006. var block = this.blocks[index];
  94007. block.intersectsRay(ray, this._selectionContent);
  94008. }
  94009. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94010. return this._selectionContent;
  94011. };
  94012. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  94013. target.blocks = new Array();
  94014. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  94015. // Segmenting space
  94016. for (var x = 0; x < 2; x++) {
  94017. for (var y = 0; y < 2; y++) {
  94018. for (var z = 0; z < 2; z++) {
  94019. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  94020. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  94021. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  94022. block.addEntries(entries);
  94023. target.blocks.push(block);
  94024. }
  94025. }
  94026. }
  94027. };
  94028. Octree.CreationFuncForMeshes = function (entry, block) {
  94029. var boundingInfo = entry.getBoundingInfo();
  94030. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  94031. block.entries.push(entry);
  94032. }
  94033. };
  94034. Octree.CreationFuncForSubMeshes = function (entry, block) {
  94035. var boundingInfo = entry.getBoundingInfo();
  94036. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  94037. block.entries.push(entry);
  94038. }
  94039. };
  94040. return Octree;
  94041. }());
  94042. BABYLON.Octree = Octree;
  94043. })(BABYLON || (BABYLON = {}));
  94044. //# sourceMappingURL=babylon.octree.js.map
  94045. var BABYLON;
  94046. (function (BABYLON) {
  94047. var OctreeBlock = /** @class */ (function () {
  94048. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  94049. this.entries = new Array();
  94050. this._boundingVectors = new Array();
  94051. this._capacity = capacity;
  94052. this._depth = depth;
  94053. this._maxDepth = maxDepth;
  94054. this._creationFunc = creationFunc;
  94055. this._minPoint = minPoint;
  94056. this._maxPoint = maxPoint;
  94057. this._boundingVectors.push(minPoint.clone());
  94058. this._boundingVectors.push(maxPoint.clone());
  94059. this._boundingVectors.push(minPoint.clone());
  94060. this._boundingVectors[2].x = maxPoint.x;
  94061. this._boundingVectors.push(minPoint.clone());
  94062. this._boundingVectors[3].y = maxPoint.y;
  94063. this._boundingVectors.push(minPoint.clone());
  94064. this._boundingVectors[4].z = maxPoint.z;
  94065. this._boundingVectors.push(maxPoint.clone());
  94066. this._boundingVectors[5].z = minPoint.z;
  94067. this._boundingVectors.push(maxPoint.clone());
  94068. this._boundingVectors[6].x = minPoint.x;
  94069. this._boundingVectors.push(maxPoint.clone());
  94070. this._boundingVectors[7].y = minPoint.y;
  94071. }
  94072. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  94073. // Property
  94074. get: function () {
  94075. return this._capacity;
  94076. },
  94077. enumerable: true,
  94078. configurable: true
  94079. });
  94080. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  94081. get: function () {
  94082. return this._minPoint;
  94083. },
  94084. enumerable: true,
  94085. configurable: true
  94086. });
  94087. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  94088. get: function () {
  94089. return this._maxPoint;
  94090. },
  94091. enumerable: true,
  94092. configurable: true
  94093. });
  94094. // Methods
  94095. OctreeBlock.prototype.addEntry = function (entry) {
  94096. if (this.blocks) {
  94097. for (var index = 0; index < this.blocks.length; index++) {
  94098. var block = this.blocks[index];
  94099. block.addEntry(entry);
  94100. }
  94101. return;
  94102. }
  94103. this._creationFunc(entry, this);
  94104. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  94105. this.createInnerBlocks();
  94106. }
  94107. };
  94108. OctreeBlock.prototype.addEntries = function (entries) {
  94109. for (var index = 0; index < entries.length; index++) {
  94110. var mesh = entries[index];
  94111. this.addEntry(mesh);
  94112. }
  94113. };
  94114. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  94115. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  94116. if (this.blocks) {
  94117. for (var index = 0; index < this.blocks.length; index++) {
  94118. var block = this.blocks[index];
  94119. block.select(frustumPlanes, selection, allowDuplicate);
  94120. }
  94121. return;
  94122. }
  94123. if (allowDuplicate) {
  94124. selection.concat(this.entries);
  94125. }
  94126. else {
  94127. selection.concatWithNoDuplicate(this.entries);
  94128. }
  94129. }
  94130. };
  94131. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  94132. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  94133. if (this.blocks) {
  94134. for (var index = 0; index < this.blocks.length; index++) {
  94135. var block = this.blocks[index];
  94136. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  94137. }
  94138. return;
  94139. }
  94140. if (allowDuplicate) {
  94141. selection.concat(this.entries);
  94142. }
  94143. else {
  94144. selection.concatWithNoDuplicate(this.entries);
  94145. }
  94146. }
  94147. };
  94148. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  94149. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  94150. if (this.blocks) {
  94151. for (var index = 0; index < this.blocks.length; index++) {
  94152. var block = this.blocks[index];
  94153. block.intersectsRay(ray, selection);
  94154. }
  94155. return;
  94156. }
  94157. selection.concatWithNoDuplicate(this.entries);
  94158. }
  94159. };
  94160. OctreeBlock.prototype.createInnerBlocks = function () {
  94161. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  94162. };
  94163. return OctreeBlock;
  94164. }());
  94165. BABYLON.OctreeBlock = OctreeBlock;
  94166. })(BABYLON || (BABYLON = {}));
  94167. //# sourceMappingURL=babylon.octreeBlock.js.map
  94168. var BABYLON;
  94169. (function (BABYLON) {
  94170. /**
  94171. * Postprocess used to generate anaglyphic rendering
  94172. */
  94173. var AnaglyphPostProcess = /** @class */ (function (_super) {
  94174. __extends(AnaglyphPostProcess, _super);
  94175. /**
  94176. * Creates a new AnaglyphPostProcess
  94177. * @param name defines postprocess name
  94178. * @param options defines creation options or target ratio scale
  94179. * @param rigCameras defines cameras using this postprocess
  94180. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  94181. * @param engine defines hosting engine
  94182. * @param reusable defines if the postprocess will be reused multiple times per frame
  94183. */
  94184. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  94185. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  94186. _this._passedProcess = rigCameras[0]._rigPostProcess;
  94187. _this.onApplyObservable.add(function (effect) {
  94188. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  94189. });
  94190. return _this;
  94191. }
  94192. return AnaglyphPostProcess;
  94193. }(BABYLON.PostProcess));
  94194. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  94195. })(BABYLON || (BABYLON = {}));
  94196. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  94197. var BABYLON;
  94198. (function (BABYLON) {
  94199. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  94200. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94201. });
  94202. /**
  94203. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  94204. */
  94205. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  94206. __extends(AnaglyphArcRotateCamera, _super);
  94207. /**
  94208. * Creates a new AnaglyphArcRotateCamera
  94209. * @param name defines camera name
  94210. * @param alpha defines alpha angle (in radians)
  94211. * @param beta defines beta angle (in radians)
  94212. * @param radius defines radius
  94213. * @param target defines camera target
  94214. * @param interaxialDistance defines distance between each color axis
  94215. * @param scene defines the hosting scene
  94216. */
  94217. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  94218. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  94219. _this.interaxialDistance = interaxialDistance;
  94220. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94221. return _this;
  94222. }
  94223. /**
  94224. * Gets camera class name
  94225. * @returns AnaglyphArcRotateCamera
  94226. */
  94227. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  94228. return "AnaglyphArcRotateCamera";
  94229. };
  94230. return AnaglyphArcRotateCamera;
  94231. }(BABYLON.ArcRotateCamera));
  94232. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  94233. })(BABYLON || (BABYLON = {}));
  94234. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  94235. var BABYLON;
  94236. (function (BABYLON) {
  94237. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  94238. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94239. });
  94240. /**
  94241. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  94242. */
  94243. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  94244. __extends(AnaglyphFreeCamera, _super);
  94245. /**
  94246. * Creates a new AnaglyphFreeCamera
  94247. * @param name defines camera name
  94248. * @param position defines initial position
  94249. * @param interaxialDistance defines distance between each color axis
  94250. * @param scene defines the hosting scene
  94251. */
  94252. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  94253. var _this = _super.call(this, name, position, scene) || this;
  94254. _this.interaxialDistance = interaxialDistance;
  94255. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94256. return _this;
  94257. }
  94258. /**
  94259. * Gets camera class name
  94260. * @returns AnaglyphFreeCamera
  94261. */
  94262. AnaglyphFreeCamera.prototype.getClassName = function () {
  94263. return "AnaglyphFreeCamera";
  94264. };
  94265. return AnaglyphFreeCamera;
  94266. }(BABYLON.FreeCamera));
  94267. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  94268. })(BABYLON || (BABYLON = {}));
  94269. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  94270. var BABYLON;
  94271. (function (BABYLON) {
  94272. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  94273. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94274. });
  94275. /**
  94276. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  94277. */
  94278. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  94279. __extends(AnaglyphGamepadCamera, _super);
  94280. /**
  94281. * Creates a new AnaglyphGamepadCamera
  94282. * @param name defines camera name
  94283. * @param position defines initial position
  94284. * @param interaxialDistance defines distance between each color axis
  94285. * @param scene defines the hosting scene
  94286. */
  94287. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  94288. var _this = _super.call(this, name, position, scene) || this;
  94289. _this.interaxialDistance = interaxialDistance;
  94290. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94291. return _this;
  94292. }
  94293. /**
  94294. * Gets camera class name
  94295. * @returns AnaglyphGamepadCamera
  94296. */
  94297. AnaglyphGamepadCamera.prototype.getClassName = function () {
  94298. return "AnaglyphGamepadCamera";
  94299. };
  94300. return AnaglyphGamepadCamera;
  94301. }(BABYLON.GamepadCamera));
  94302. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  94303. })(BABYLON || (BABYLON = {}));
  94304. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  94305. var BABYLON;
  94306. (function (BABYLON) {
  94307. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  94308. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94309. });
  94310. /**
  94311. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  94312. */
  94313. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  94314. __extends(AnaglyphUniversalCamera, _super);
  94315. /**
  94316. * Creates a new AnaglyphUniversalCamera
  94317. * @param name defines camera name
  94318. * @param position defines initial position
  94319. * @param interaxialDistance defines distance between each color axis
  94320. * @param scene defines the hosting scene
  94321. */
  94322. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  94323. var _this = _super.call(this, name, position, scene) || this;
  94324. _this.interaxialDistance = interaxialDistance;
  94325. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94326. return _this;
  94327. }
  94328. /**
  94329. * Gets camera class name
  94330. * @returns AnaglyphUniversalCamera
  94331. */
  94332. AnaglyphUniversalCamera.prototype.getClassName = function () {
  94333. return "AnaglyphUniversalCamera";
  94334. };
  94335. return AnaglyphUniversalCamera;
  94336. }(BABYLON.UniversalCamera));
  94337. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  94338. })(BABYLON || (BABYLON = {}));
  94339. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  94340. var BABYLON;
  94341. (function (BABYLON) {
  94342. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  94343. __extends(StereoscopicInterlacePostProcess, _super);
  94344. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  94345. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  94346. _this._passedProcess = rigCameras[0]._rigPostProcess;
  94347. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  94348. _this.onSizeChangedObservable.add(function () {
  94349. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  94350. });
  94351. _this.onApplyObservable.add(function (effect) {
  94352. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  94353. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  94354. });
  94355. return _this;
  94356. }
  94357. return StereoscopicInterlacePostProcess;
  94358. }(BABYLON.PostProcess));
  94359. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  94360. })(BABYLON || (BABYLON = {}));
  94361. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  94362. var BABYLON;
  94363. (function (BABYLON) {
  94364. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  94365. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94366. });
  94367. /**
  94368. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  94369. */
  94370. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  94371. __extends(StereoscopicArcRotateCamera, _super);
  94372. /**
  94373. * Creates a new StereoscopicArcRotateCamera
  94374. * @param name defines camera name
  94375. * @param alpha defines alpha angle (in radians)
  94376. * @param beta defines beta angle (in radians)
  94377. * @param radius defines radius
  94378. * @param target defines camera target
  94379. * @param interaxialDistance defines distance between each color axis
  94380. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94381. * @param scene defines the hosting scene
  94382. */
  94383. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  94384. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  94385. _this.interaxialDistance = interaxialDistance;
  94386. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94387. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94388. return _this;
  94389. }
  94390. /**
  94391. * Gets camera class name
  94392. * @returns StereoscopicArcRotateCamera
  94393. */
  94394. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  94395. return "StereoscopicArcRotateCamera";
  94396. };
  94397. return StereoscopicArcRotateCamera;
  94398. }(BABYLON.ArcRotateCamera));
  94399. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  94400. })(BABYLON || (BABYLON = {}));
  94401. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  94402. var BABYLON;
  94403. (function (BABYLON) {
  94404. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  94405. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94406. });
  94407. /**
  94408. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  94409. */
  94410. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  94411. __extends(StereoscopicFreeCamera, _super);
  94412. /**
  94413. * Creates a new StereoscopicFreeCamera
  94414. * @param name defines camera name
  94415. * @param position defines initial position
  94416. * @param interaxialDistance defines distance between each color axis
  94417. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94418. * @param scene defines the hosting scene
  94419. */
  94420. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94421. var _this = _super.call(this, name, position, scene) || this;
  94422. _this.interaxialDistance = interaxialDistance;
  94423. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94424. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94425. return _this;
  94426. }
  94427. /**
  94428. * Gets camera class name
  94429. * @returns StereoscopicFreeCamera
  94430. */
  94431. StereoscopicFreeCamera.prototype.getClassName = function () {
  94432. return "StereoscopicFreeCamera";
  94433. };
  94434. return StereoscopicFreeCamera;
  94435. }(BABYLON.FreeCamera));
  94436. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  94437. })(BABYLON || (BABYLON = {}));
  94438. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  94439. var BABYLON;
  94440. (function (BABYLON) {
  94441. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  94442. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94443. });
  94444. /**
  94445. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  94446. */
  94447. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  94448. __extends(StereoscopicGamepadCamera, _super);
  94449. /**
  94450. * Creates a new StereoscopicGamepadCamera
  94451. * @param name defines camera name
  94452. * @param position defines initial position
  94453. * @param interaxialDistance defines distance between each color axis
  94454. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94455. * @param scene defines the hosting scene
  94456. */
  94457. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94458. var _this = _super.call(this, name, position, scene) || this;
  94459. _this.interaxialDistance = interaxialDistance;
  94460. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94461. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94462. return _this;
  94463. }
  94464. /**
  94465. * Gets camera class name
  94466. * @returns StereoscopicGamepadCamera
  94467. */
  94468. StereoscopicGamepadCamera.prototype.getClassName = function () {
  94469. return "StereoscopicGamepadCamera";
  94470. };
  94471. return StereoscopicGamepadCamera;
  94472. }(BABYLON.GamepadCamera));
  94473. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  94474. })(BABYLON || (BABYLON = {}));
  94475. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  94476. var BABYLON;
  94477. (function (BABYLON) {
  94478. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  94479. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94480. });
  94481. /**
  94482. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  94483. */
  94484. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  94485. __extends(StereoscopicUniversalCamera, _super);
  94486. /**
  94487. * Creates a new StereoscopicUniversalCamera
  94488. * @param name defines camera name
  94489. * @param position defines initial position
  94490. * @param interaxialDistance defines distance between each color axis
  94491. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94492. * @param scene defines the hosting scene
  94493. */
  94494. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94495. var _this = _super.call(this, name, position, scene) || this;
  94496. _this.interaxialDistance = interaxialDistance;
  94497. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94498. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94499. return _this;
  94500. }
  94501. /**
  94502. * Gets camera class name
  94503. * @returns StereoscopicUniversalCamera
  94504. */
  94505. StereoscopicUniversalCamera.prototype.getClassName = function () {
  94506. return "StereoscopicUniversalCamera";
  94507. };
  94508. return StereoscopicUniversalCamera;
  94509. }(BABYLON.UniversalCamera));
  94510. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  94511. })(BABYLON || (BABYLON = {}));
  94512. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  94513. var BABYLON;
  94514. (function (BABYLON) {
  94515. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  94516. __extends(VRDistortionCorrectionPostProcess, _super);
  94517. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  94518. var _this = _super.call(this, name, "vrDistortionCorrection", [
  94519. 'LensCenter',
  94520. 'Scale',
  94521. 'ScaleIn',
  94522. 'HmdWarpParam'
  94523. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  94524. _this._isRightEye = isRightEye;
  94525. _this._distortionFactors = vrMetrics.distortionK;
  94526. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  94527. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  94528. _this.adaptScaleToCurrentViewport = true;
  94529. _this.onSizeChangedObservable.add(function () {
  94530. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  94531. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  94532. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  94533. });
  94534. _this.onApplyObservable.add(function (effect) {
  94535. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  94536. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  94537. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  94538. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  94539. });
  94540. return _this;
  94541. }
  94542. return VRDistortionCorrectionPostProcess;
  94543. }(BABYLON.PostProcess));
  94544. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  94545. })(BABYLON || (BABYLON = {}));
  94546. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  94547. var BABYLON;
  94548. (function (BABYLON) {
  94549. /**
  94550. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  94551. * Screen rotation is taken into account.
  94552. */
  94553. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  94554. function FreeCameraDeviceOrientationInput() {
  94555. var _this = this;
  94556. this._screenOrientationAngle = 0;
  94557. this._screenQuaternion = new BABYLON.Quaternion();
  94558. this._alpha = 0;
  94559. this._beta = 0;
  94560. this._gamma = 0;
  94561. this._orientationChanged = function () {
  94562. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  94563. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  94564. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  94565. };
  94566. this._deviceOrientation = function (evt) {
  94567. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  94568. _this._beta = evt.beta !== null ? evt.beta : 0;
  94569. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  94570. };
  94571. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  94572. this._orientationChanged();
  94573. }
  94574. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  94575. get: function () {
  94576. return this._camera;
  94577. },
  94578. set: function (camera) {
  94579. this._camera = camera;
  94580. if (this._camera != null && !this._camera.rotationQuaternion) {
  94581. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  94582. }
  94583. },
  94584. enumerable: true,
  94585. configurable: true
  94586. });
  94587. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  94588. window.addEventListener("orientationchange", this._orientationChanged);
  94589. window.addEventListener("deviceorientation", this._deviceOrientation);
  94590. //In certain cases, the attach control is called AFTER orientation was changed,
  94591. //So this is needed.
  94592. this._orientationChanged();
  94593. };
  94594. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  94595. window.removeEventListener("orientationchange", this._orientationChanged);
  94596. window.removeEventListener("deviceorientation", this._deviceOrientation);
  94597. };
  94598. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  94599. //if no device orientation provided, don't update the rotation.
  94600. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  94601. if (!this._alpha)
  94602. return;
  94603. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  94604. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  94605. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  94606. //Mirror on XY Plane
  94607. this._camera.rotationQuaternion.z *= -1;
  94608. this._camera.rotationQuaternion.w *= -1;
  94609. };
  94610. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  94611. return "FreeCameraDeviceOrientationInput";
  94612. };
  94613. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  94614. return "deviceOrientation";
  94615. };
  94616. return FreeCameraDeviceOrientationInput;
  94617. }());
  94618. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  94619. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  94620. })(BABYLON || (BABYLON = {}));
  94621. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  94622. var BABYLON;
  94623. (function (BABYLON) {
  94624. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  94625. function ArcRotateCameraVRDeviceOrientationInput() {
  94626. this.alphaCorrection = 1;
  94627. this.betaCorrection = 1;
  94628. this.gammaCorrection = 1;
  94629. this._alpha = 0;
  94630. this._gamma = 0;
  94631. this._dirty = false;
  94632. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  94633. }
  94634. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  94635. this.camera.attachControl(element, noPreventDefault);
  94636. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  94637. };
  94638. /** @hidden */
  94639. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  94640. if (evt.alpha !== null) {
  94641. this._alpha = +evt.alpha | 0;
  94642. }
  94643. if (evt.gamma !== null) {
  94644. this._gamma = +evt.gamma | 0;
  94645. }
  94646. this._dirty = true;
  94647. };
  94648. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  94649. if (this._dirty) {
  94650. this._dirty = false;
  94651. if (this._gamma < 0) {
  94652. this._gamma = 180 + this._gamma;
  94653. }
  94654. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  94655. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  94656. }
  94657. };
  94658. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  94659. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  94660. };
  94661. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  94662. return "ArcRotateCameraVRDeviceOrientationInput";
  94663. };
  94664. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  94665. return "VRDeviceOrientation";
  94666. };
  94667. return ArcRotateCameraVRDeviceOrientationInput;
  94668. }());
  94669. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  94670. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  94671. })(BABYLON || (BABYLON = {}));
  94672. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  94673. var BABYLON;
  94674. (function (BABYLON) {
  94675. var VRCameraMetrics = /** @class */ (function () {
  94676. function VRCameraMetrics() {
  94677. this.compensateDistortion = true;
  94678. }
  94679. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  94680. get: function () {
  94681. return this.hResolution / (2 * this.vResolution);
  94682. },
  94683. enumerable: true,
  94684. configurable: true
  94685. });
  94686. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  94687. get: function () {
  94688. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  94689. },
  94690. enumerable: true,
  94691. configurable: true
  94692. });
  94693. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  94694. get: function () {
  94695. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  94696. var h = (4 * meters) / this.hScreenSize;
  94697. return BABYLON.Matrix.Translation(h, 0, 0);
  94698. },
  94699. enumerable: true,
  94700. configurable: true
  94701. });
  94702. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  94703. get: function () {
  94704. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  94705. var h = (4 * meters) / this.hScreenSize;
  94706. return BABYLON.Matrix.Translation(-h, 0, 0);
  94707. },
  94708. enumerable: true,
  94709. configurable: true
  94710. });
  94711. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  94712. get: function () {
  94713. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  94714. },
  94715. enumerable: true,
  94716. configurable: true
  94717. });
  94718. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  94719. get: function () {
  94720. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  94721. },
  94722. enumerable: true,
  94723. configurable: true
  94724. });
  94725. VRCameraMetrics.GetDefault = function () {
  94726. var result = new VRCameraMetrics();
  94727. result.hResolution = 1280;
  94728. result.vResolution = 800;
  94729. result.hScreenSize = 0.149759993;
  94730. result.vScreenSize = 0.0935999975;
  94731. result.vScreenCenter = 0.0467999987;
  94732. result.eyeToScreenDistance = 0.0410000011;
  94733. result.lensSeparationDistance = 0.0635000020;
  94734. result.interpupillaryDistance = 0.0640000030;
  94735. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  94736. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  94737. result.postProcessScaleFactor = 1.714605507808412;
  94738. result.lensCenterOffset = 0.151976421;
  94739. return result;
  94740. };
  94741. return VRCameraMetrics;
  94742. }());
  94743. BABYLON.VRCameraMetrics = VRCameraMetrics;
  94744. })(BABYLON || (BABYLON = {}));
  94745. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  94746. var BABYLON;
  94747. (function (BABYLON) {
  94748. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  94749. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  94750. });
  94751. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  94752. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  94753. });
  94754. /**
  94755. * This represents a WebVR camera.
  94756. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  94757. * @example http://doc.babylonjs.com/how_to/webvr_camera
  94758. */
  94759. var WebVRFreeCamera = /** @class */ (function (_super) {
  94760. __extends(WebVRFreeCamera, _super);
  94761. /**
  94762. * Instantiates a WebVRFreeCamera.
  94763. * @param name The name of the WebVRFreeCamera
  94764. * @param position The starting anchor position for the camera
  94765. * @param scene The scene the camera belongs to
  94766. * @param webVROptions a set of customizable options for the webVRCamera
  94767. */
  94768. function WebVRFreeCamera(name, position, scene, webVROptions) {
  94769. if (webVROptions === void 0) { webVROptions = {}; }
  94770. var _this = _super.call(this, name, position, scene) || this;
  94771. _this.webVROptions = webVROptions;
  94772. /**
  94773. * @hidden
  94774. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  94775. */
  94776. _this._vrDevice = null;
  94777. /**
  94778. * The rawPose of the vrDevice.
  94779. */
  94780. _this.rawPose = null;
  94781. _this._specsVersion = "1.1";
  94782. _this._attached = false;
  94783. _this._descendants = [];
  94784. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  94785. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  94786. /** @hidden */
  94787. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  94788. _this._standingMatrix = null;
  94789. /**
  94790. * Represents device position in babylon space.
  94791. */
  94792. _this.devicePosition = BABYLON.Vector3.Zero();
  94793. /**
  94794. * Represents device rotation in babylon space.
  94795. */
  94796. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  94797. /**
  94798. * The scale of the device to be used when translating from device space to babylon space.
  94799. */
  94800. _this.deviceScaleFactor = 1;
  94801. _this._deviceToWorld = BABYLON.Matrix.Identity();
  94802. _this._worldToDevice = BABYLON.Matrix.Identity();
  94803. /**
  94804. * References to the webVR controllers for the vrDevice.
  94805. */
  94806. _this.controllers = [];
  94807. /**
  94808. * Emits an event when a controller is attached.
  94809. */
  94810. _this.onControllersAttachedObservable = new BABYLON.Observable();
  94811. /**
  94812. * Emits an event when a controller's mesh has been loaded;
  94813. */
  94814. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  94815. /**
  94816. * Emits an event when the HMD's pose has been updated.
  94817. */
  94818. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  94819. _this._poseSet = false;
  94820. /**
  94821. * If the rig cameras be used as parent instead of this camera.
  94822. */
  94823. _this.rigParenting = true;
  94824. _this._defaultHeight = undefined;
  94825. _this._htmlElementAttached = null;
  94826. _this._detachIfAttached = function () {
  94827. var vrDisplay = _this.getEngine().getVRDevice();
  94828. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  94829. _this.detachControl(_this._htmlElementAttached);
  94830. }
  94831. };
  94832. _this._workingVector = BABYLON.Vector3.Zero();
  94833. _this._oneVector = BABYLON.Vector3.One();
  94834. _this._workingMatrix = BABYLON.Matrix.Identity();
  94835. _this._cache.position = BABYLON.Vector3.Zero();
  94836. if (webVROptions.defaultHeight) {
  94837. _this._defaultHeight = webVROptions.defaultHeight;
  94838. _this.position.y = _this._defaultHeight;
  94839. }
  94840. _this.minZ = 0.1;
  94841. //legacy support - the compensation boolean was removed.
  94842. if (arguments.length === 5) {
  94843. _this.webVROptions = arguments[4];
  94844. }
  94845. // default webVR options
  94846. if (_this.webVROptions.trackPosition == undefined) {
  94847. _this.webVROptions.trackPosition = true;
  94848. }
  94849. if (_this.webVROptions.controllerMeshes == undefined) {
  94850. _this.webVROptions.controllerMeshes = true;
  94851. }
  94852. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  94853. _this.webVROptions.defaultLightingOnControllers = true;
  94854. }
  94855. _this.rotationQuaternion = new BABYLON.Quaternion();
  94856. if (_this.webVROptions && _this.webVROptions.positionScale) {
  94857. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  94858. }
  94859. //enable VR
  94860. var engine = _this.getEngine();
  94861. _this._onVREnabled = function (success) { if (success) {
  94862. _this.initControllers();
  94863. } };
  94864. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  94865. engine.initWebVR().add(function (event) {
  94866. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  94867. return;
  94868. }
  94869. _this._vrDevice = event.vrDisplay;
  94870. //reset the rig parameters.
  94871. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  94872. if (_this._attached) {
  94873. _this.getEngine().enableVR();
  94874. }
  94875. });
  94876. if (typeof (VRFrameData) !== "undefined")
  94877. _this._frameData = new VRFrameData();
  94878. /**
  94879. * The idea behind the following lines:
  94880. * objects that have the camera as parent should actually have the rig cameras as a parent.
  94881. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  94882. * the second will not show it correctly.
  94883. *
  94884. * To solve this - each object that has the camera as parent will be added to a protected array.
  94885. * When the rig camera renders, it will take this array and set all of those to be its children.
  94886. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  94887. * Amazing!
  94888. */
  94889. scene.onBeforeCameraRenderObservable.add(function (camera) {
  94890. if (camera.parent === _this && _this.rigParenting) {
  94891. _this._descendants = _this.getDescendants(true, function (n) {
  94892. // don't take the cameras or the controllers!
  94893. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  94894. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  94895. return !isController && !isRigCamera;
  94896. });
  94897. _this._descendants.forEach(function (node) {
  94898. node.parent = camera;
  94899. });
  94900. }
  94901. });
  94902. scene.onAfterCameraRenderObservable.add(function (camera) {
  94903. if (camera.parent === _this && _this.rigParenting) {
  94904. _this._descendants.forEach(function (node) {
  94905. node.parent = _this;
  94906. });
  94907. }
  94908. });
  94909. return _this;
  94910. }
  94911. /**
  94912. * Gets the device distance from the ground in meters.
  94913. * @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.
  94914. */
  94915. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  94916. if (this._standingMatrix) {
  94917. // Add standing matrix offset to get real offset from ground in room
  94918. this._standingMatrix.getTranslationToRef(this._workingVector);
  94919. return this._deviceRoomPosition.y + this._workingVector.y;
  94920. }
  94921. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  94922. return this._defaultHeight || 0;
  94923. };
  94924. /**
  94925. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  94926. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  94927. */
  94928. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  94929. var _this = this;
  94930. if (callback === void 0) { callback = function (bool) { }; }
  94931. // Use standing matrix if available
  94932. this.getEngine().initWebVRAsync().then(function (result) {
  94933. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  94934. callback(false);
  94935. }
  94936. else {
  94937. _this._standingMatrix = new BABYLON.Matrix();
  94938. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  94939. if (!_this.getScene().useRightHandedSystem) {
  94940. [2, 6, 8, 9, 14].forEach(function (num) {
  94941. if (_this._standingMatrix) {
  94942. _this._standingMatrix.m[num] *= -1;
  94943. }
  94944. });
  94945. }
  94946. callback(true);
  94947. }
  94948. });
  94949. };
  94950. /**
  94951. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  94952. * @returns A promise with a boolean set to if the standing matrix is supported.
  94953. */
  94954. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  94955. var _this = this;
  94956. return new Promise(function (res, rej) {
  94957. _this.useStandingMatrix(function (supported) {
  94958. res(supported);
  94959. });
  94960. });
  94961. };
  94962. /**
  94963. * Disposes the camera
  94964. */
  94965. WebVRFreeCamera.prototype.dispose = function () {
  94966. this._detachIfAttached();
  94967. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  94968. _super.prototype.dispose.call(this);
  94969. };
  94970. /**
  94971. * Gets a vrController by name.
  94972. * @param name The name of the controller to retreive
  94973. * @returns the controller matching the name specified or null if not found
  94974. */
  94975. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  94976. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  94977. var gp = _a[_i];
  94978. if (gp.hand === name) {
  94979. return gp;
  94980. }
  94981. }
  94982. return null;
  94983. };
  94984. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  94985. /**
  94986. * The controller corrisponding to the users left hand.
  94987. */
  94988. get: function () {
  94989. if (!this._leftController) {
  94990. this._leftController = this.getControllerByName("left");
  94991. }
  94992. return this._leftController;
  94993. },
  94994. enumerable: true,
  94995. configurable: true
  94996. });
  94997. ;
  94998. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  94999. /**
  95000. * The controller corrisponding to the users right hand.
  95001. */
  95002. get: function () {
  95003. if (!this._rightController) {
  95004. this._rightController = this.getControllerByName("right");
  95005. }
  95006. return this._rightController;
  95007. },
  95008. enumerable: true,
  95009. configurable: true
  95010. });
  95011. ;
  95012. /**
  95013. * Casts a ray forward from the vrCamera's gaze.
  95014. * @param length Length of the ray (default: 100)
  95015. * @returns the ray corrisponding to the gaze
  95016. */
  95017. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  95018. if (length === void 0) { length = 100; }
  95019. if (this.leftCamera) {
  95020. // Use left eye to avoid computation to compute center on every call
  95021. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  95022. }
  95023. else {
  95024. return _super.prototype.getForwardRay.call(this, length);
  95025. }
  95026. };
  95027. /**
  95028. * @hidden
  95029. * Updates the camera based on device's frame data
  95030. */
  95031. WebVRFreeCamera.prototype._checkInputs = function () {
  95032. if (this._vrDevice && this._vrDevice.isPresenting) {
  95033. this._vrDevice.getFrameData(this._frameData);
  95034. this.updateFromDevice(this._frameData.pose);
  95035. }
  95036. _super.prototype._checkInputs.call(this);
  95037. };
  95038. /**
  95039. * Updates the poseControlled values based on the input device pose.
  95040. * @param poseData Pose coming from the device
  95041. */
  95042. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  95043. if (poseData && poseData.orientation) {
  95044. this.rawPose = poseData;
  95045. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  95046. if (this.getScene().useRightHandedSystem) {
  95047. this._deviceRoomRotationQuaternion.z *= -1;
  95048. this._deviceRoomRotationQuaternion.w *= -1;
  95049. }
  95050. if (this.webVROptions.trackPosition && this.rawPose.position) {
  95051. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  95052. if (this.getScene().useRightHandedSystem) {
  95053. this._deviceRoomPosition.z *= -1;
  95054. }
  95055. }
  95056. this._poseSet = true;
  95057. }
  95058. };
  95059. /**
  95060. * WebVR's attach control will start broadcasting frames to the device.
  95061. * Note that in certain browsers (chrome for example) this function must be called
  95062. * within a user-interaction callback. Example:
  95063. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  95064. *
  95065. * @param element html element to attach the vrDevice to
  95066. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  95067. */
  95068. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  95069. _super.prototype.attachControl.call(this, element, noPreventDefault);
  95070. this._attached = true;
  95071. this._htmlElementAttached = element;
  95072. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  95073. if (this._vrDevice) {
  95074. this.getEngine().enableVR();
  95075. }
  95076. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  95077. };
  95078. /**
  95079. * Detaches the camera from the html element and disables VR
  95080. *
  95081. * @param element html element to detach from
  95082. */
  95083. WebVRFreeCamera.prototype.detachControl = function (element) {
  95084. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  95085. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  95086. _super.prototype.detachControl.call(this, element);
  95087. this._attached = false;
  95088. this.getEngine().disableVR();
  95089. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  95090. };
  95091. /**
  95092. * @returns the name of this class
  95093. */
  95094. WebVRFreeCamera.prototype.getClassName = function () {
  95095. return "WebVRFreeCamera";
  95096. };
  95097. /**
  95098. * Calls resetPose on the vrDisplay
  95099. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  95100. */
  95101. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  95102. //uses the vrDisplay's "resetPose()".
  95103. //pitch and roll won't be affected.
  95104. this._vrDevice.resetPose();
  95105. };
  95106. /**
  95107. * @hidden
  95108. * Updates the rig cameras (left and right eye)
  95109. */
  95110. WebVRFreeCamera.prototype._updateRigCameras = function () {
  95111. var camLeft = this._rigCameras[0];
  95112. var camRight = this._rigCameras[1];
  95113. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  95114. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  95115. camLeft.position.copyFrom(this._deviceRoomPosition);
  95116. camRight.position.copyFrom(this._deviceRoomPosition);
  95117. };
  95118. /**
  95119. * @hidden
  95120. * Updates the cached values of the camera
  95121. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  95122. */
  95123. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  95124. var _this = this;
  95125. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  95126. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  95127. if (!this.updateCacheCalled) {
  95128. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  95129. this.updateCacheCalled = true;
  95130. this.update();
  95131. }
  95132. // Set working vector to the device position in room space rotated by the new rotation
  95133. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  95134. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  95135. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  95136. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  95137. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  95138. // Add translation from anchor position
  95139. this._deviceToWorld.getTranslationToRef(this._workingVector);
  95140. this._workingVector.addInPlace(this.position);
  95141. this._workingVector.subtractInPlace(this._cache.position);
  95142. this._deviceToWorld.setTranslation(this._workingVector);
  95143. // Set an inverted matrix to be used when updating the camera
  95144. this._deviceToWorld.invertToRef(this._worldToDevice);
  95145. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  95146. this.controllers.forEach(function (controller) {
  95147. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  95148. controller.update();
  95149. });
  95150. }
  95151. if (!ignoreParentClass) {
  95152. _super.prototype._updateCache.call(this);
  95153. }
  95154. this.updateCacheCalled = false;
  95155. };
  95156. /**
  95157. * Updates the current device position and rotation in the babylon world
  95158. */
  95159. WebVRFreeCamera.prototype.update = function () {
  95160. // Get current device position in babylon world
  95161. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  95162. // Get current device rotation in babylon world
  95163. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  95164. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  95165. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  95166. if (this._poseSet) {
  95167. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  95168. }
  95169. _super.prototype.update.call(this);
  95170. };
  95171. /**
  95172. * @hidden
  95173. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  95174. * @returns an identity matrix
  95175. */
  95176. WebVRFreeCamera.prototype._getViewMatrix = function () {
  95177. return BABYLON.Matrix.Identity();
  95178. };
  95179. /**
  95180. * This function is called by the two RIG cameras.
  95181. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  95182. */
  95183. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  95184. var _this = this;
  95185. // Update the parent camera prior to using a child camera to avoid desynchronization
  95186. var parentCamera = this._cameraRigParams["parentCamera"];
  95187. parentCamera._updateCache();
  95188. //WebVR 1.1
  95189. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  95190. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  95191. if (!this.getScene().useRightHandedSystem) {
  95192. [2, 6, 8, 9, 14].forEach(function (num) {
  95193. _this._webvrViewMatrix.m[num] *= -1;
  95194. });
  95195. }
  95196. // update the camera rotation matrix
  95197. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  95198. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  95199. // Computing target and final matrix
  95200. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  95201. // should the view matrix be updated with scale and position offset?
  95202. if (parentCamera.deviceScaleFactor !== 1) {
  95203. this._webvrViewMatrix.invert();
  95204. // scale the position, if set
  95205. if (parentCamera.deviceScaleFactor) {
  95206. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  95207. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  95208. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  95209. }
  95210. this._webvrViewMatrix.invert();
  95211. }
  95212. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  95213. // Compute global position
  95214. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  95215. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  95216. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  95217. this._workingMatrix.getTranslationToRef(this._globalPosition);
  95218. this._markSyncedWithParent();
  95219. return this._webvrViewMatrix;
  95220. };
  95221. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  95222. var _this = this;
  95223. var parentCamera = this.parent;
  95224. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  95225. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  95226. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  95227. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  95228. //babylon compatible matrix
  95229. if (!this.getScene().useRightHandedSystem) {
  95230. [8, 9, 10, 11].forEach(function (num) {
  95231. _this._projectionMatrix.m[num] *= -1;
  95232. });
  95233. }
  95234. return this._projectionMatrix;
  95235. };
  95236. /**
  95237. * Initializes the controllers and their meshes
  95238. */
  95239. WebVRFreeCamera.prototype.initControllers = function () {
  95240. var _this = this;
  95241. this.controllers = [];
  95242. var manager = this.getScene().gamepadManager;
  95243. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  95244. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  95245. var webVrController = gamepad;
  95246. if (webVrController.defaultModel) {
  95247. webVrController.defaultModel.setEnabled(false);
  95248. }
  95249. if (webVrController.hand === "right") {
  95250. _this._rightController = null;
  95251. }
  95252. if (webVrController.hand === "left") {
  95253. _this._leftController = null;
  95254. }
  95255. var controllerIndex = _this.controllers.indexOf(webVrController);
  95256. if (controllerIndex !== -1) {
  95257. _this.controllers.splice(controllerIndex, 1);
  95258. }
  95259. }
  95260. });
  95261. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  95262. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  95263. var webVrController_1 = gamepad;
  95264. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  95265. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  95266. if (_this.webVROptions.controllerMeshes) {
  95267. if (webVrController_1.defaultModel) {
  95268. webVrController_1.defaultModel.setEnabled(true);
  95269. }
  95270. else {
  95271. // Load the meshes
  95272. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  95273. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  95274. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  95275. if (_this.webVROptions.defaultLightingOnControllers) {
  95276. if (!_this._lightOnControllers) {
  95277. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  95278. }
  95279. var activateLightOnSubMeshes_1 = function (mesh, light) {
  95280. var children = mesh.getChildren();
  95281. if (children.length !== 0) {
  95282. children.forEach(function (mesh) {
  95283. light.includedOnlyMeshes.push(mesh);
  95284. activateLightOnSubMeshes_1(mesh, light);
  95285. });
  95286. }
  95287. };
  95288. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  95289. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  95290. }
  95291. });
  95292. }
  95293. }
  95294. webVrController_1.attachToPoseControlledCamera(_this);
  95295. // since this is async - sanity check. Is the controller already stored?
  95296. if (_this.controllers.indexOf(webVrController_1) === -1) {
  95297. //add to the controllers array
  95298. _this.controllers.push(webVrController_1);
  95299. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  95300. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  95301. // So we're overriding setting left & right manually to be sure
  95302. var firstViveWandDetected = false;
  95303. for (var i = 0; i < _this.controllers.length; i++) {
  95304. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  95305. if (!firstViveWandDetected) {
  95306. firstViveWandDetected = true;
  95307. _this.controllers[i].hand = "left";
  95308. }
  95309. else {
  95310. _this.controllers[i].hand = "right";
  95311. }
  95312. }
  95313. }
  95314. //did we find enough controllers? Great! let the developer know.
  95315. if (_this.controllers.length >= 2) {
  95316. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  95317. }
  95318. }
  95319. }
  95320. });
  95321. };
  95322. return WebVRFreeCamera;
  95323. }(BABYLON.FreeCamera));
  95324. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  95325. })(BABYLON || (BABYLON = {}));
  95326. //# sourceMappingURL=babylon.webVRCamera.js.map
  95327. var BABYLON;
  95328. (function (BABYLON) {
  95329. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  95330. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  95331. });
  95332. // We're mainly based on the logic defined into the FreeCamera code
  95333. /**
  95334. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  95335. * being tilted forward or back and left or right.
  95336. */
  95337. var DeviceOrientationCamera = /** @class */ (function (_super) {
  95338. __extends(DeviceOrientationCamera, _super);
  95339. /**
  95340. * Creates a new device orientation camera
  95341. * @param name The name of the camera
  95342. * @param position The start position camera
  95343. * @param scene The scene the camera belongs to
  95344. */
  95345. function DeviceOrientationCamera(name, position, scene) {
  95346. var _this = _super.call(this, name, position, scene) || this;
  95347. _this._quaternionCache = new BABYLON.Quaternion();
  95348. _this.inputs.addDeviceOrientation();
  95349. return _this;
  95350. }
  95351. /**
  95352. * Gets the current instance class name ("DeviceOrientationCamera").
  95353. * This helps avoiding instanceof at run time.
  95354. * @returns the class name
  95355. */
  95356. DeviceOrientationCamera.prototype.getClassName = function () {
  95357. return "DeviceOrientationCamera";
  95358. };
  95359. /**
  95360. * @hidden
  95361. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  95362. */
  95363. DeviceOrientationCamera.prototype._checkInputs = function () {
  95364. _super.prototype._checkInputs.call(this);
  95365. this._quaternionCache.copyFrom(this.rotationQuaternion);
  95366. if (this._initialQuaternion) {
  95367. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  95368. }
  95369. };
  95370. /**
  95371. * Reset the camera to its default orientation on the specified axis only.
  95372. * @param axis The axis to reset
  95373. */
  95374. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  95375. var _this = this;
  95376. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  95377. //can only work if this camera has a rotation quaternion already.
  95378. if (!this.rotationQuaternion)
  95379. return;
  95380. if (!this._initialQuaternion) {
  95381. this._initialQuaternion = new BABYLON.Quaternion();
  95382. }
  95383. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  95384. ['x', 'y', 'z'].forEach(function (axisName) {
  95385. if (!axis[axisName]) {
  95386. _this._initialQuaternion[axisName] = 0;
  95387. }
  95388. else {
  95389. _this._initialQuaternion[axisName] *= -1;
  95390. }
  95391. });
  95392. this._initialQuaternion.normalize();
  95393. //force rotation update
  95394. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  95395. };
  95396. return DeviceOrientationCamera;
  95397. }(BABYLON.FreeCamera));
  95398. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  95399. })(BABYLON || (BABYLON = {}));
  95400. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  95401. var BABYLON;
  95402. (function (BABYLON) {
  95403. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  95404. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  95405. });
  95406. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  95407. __extends(VRDeviceOrientationFreeCamera, _super);
  95408. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  95409. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95410. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95411. var _this = _super.call(this, name, position, scene) || this;
  95412. vrCameraMetrics.compensateDistortion = compensateDistortion;
  95413. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  95414. return _this;
  95415. }
  95416. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  95417. return "VRDeviceOrientationFreeCamera";
  95418. };
  95419. return VRDeviceOrientationFreeCamera;
  95420. }(BABYLON.DeviceOrientationCamera));
  95421. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  95422. })(BABYLON || (BABYLON = {}));
  95423. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  95424. var BABYLON;
  95425. (function (BABYLON) {
  95426. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  95427. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  95428. });
  95429. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  95430. __extends(VRDeviceOrientationArcRotateCamera, _super);
  95431. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  95432. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95433. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95434. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95435. vrCameraMetrics.compensateDistortion = compensateDistortion;
  95436. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  95437. _this.inputs.addVRDeviceOrientation();
  95438. return _this;
  95439. }
  95440. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  95441. return "VRDeviceOrientationArcRotateCamera";
  95442. };
  95443. return VRDeviceOrientationArcRotateCamera;
  95444. }(BABYLON.ArcRotateCamera));
  95445. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  95446. })(BABYLON || (BABYLON = {}));
  95447. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  95448. var BABYLON;
  95449. (function (BABYLON) {
  95450. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  95451. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  95452. });
  95453. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  95454. __extends(VRDeviceOrientationGamepadCamera, _super);
  95455. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  95456. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95457. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95458. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  95459. _this.inputs.addGamepad();
  95460. return _this;
  95461. }
  95462. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  95463. return "VRDeviceOrientationGamepadCamera";
  95464. };
  95465. return VRDeviceOrientationGamepadCamera;
  95466. }(BABYLON.VRDeviceOrientationFreeCamera));
  95467. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  95468. })(BABYLON || (BABYLON = {}));
  95469. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  95470. var BABYLON;
  95471. (function (BABYLON) {
  95472. var VRExperienceHelperGazer = /** @class */ (function () {
  95473. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  95474. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  95475. this.scene = scene;
  95476. /** @hidden */
  95477. this._pointerDownOnMeshAsked = false;
  95478. /** @hidden */
  95479. this._isActionableMesh = false;
  95480. /** @hidden */
  95481. this._teleportationRequestInitiated = false;
  95482. /** @hidden */
  95483. this._teleportationBackRequestInitiated = false;
  95484. /** @hidden */
  95485. this._rotationRightAsked = false;
  95486. /** @hidden */
  95487. this._rotationLeftAsked = false;
  95488. /** @hidden */
  95489. this._dpadPressed = true;
  95490. /** @hidden */
  95491. this._activePointer = false;
  95492. this._id = VRExperienceHelperGazer._idCounter++;
  95493. // Gaze tracker
  95494. if (!gazeTrackerToClone) {
  95495. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  95496. this._gazeTracker.bakeCurrentTransformIntoVertices();
  95497. this._gazeTracker.isPickable = false;
  95498. this._gazeTracker.isVisible = false;
  95499. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  95500. targetMat.specularColor = BABYLON.Color3.Black();
  95501. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  95502. targetMat.backFaceCulling = false;
  95503. this._gazeTracker.material = targetMat;
  95504. }
  95505. else {
  95506. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  95507. }
  95508. }
  95509. /** @hidden */
  95510. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  95511. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  95512. };
  95513. /** @hidden */
  95514. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  95515. this._pointerDownOnMeshAsked = true;
  95516. if (this._currentHit) {
  95517. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  95518. }
  95519. };
  95520. /** @hidden */
  95521. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  95522. if (this._currentHit) {
  95523. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  95524. }
  95525. this._pointerDownOnMeshAsked = false;
  95526. };
  95527. /** @hidden */
  95528. VRExperienceHelperGazer.prototype._activatePointer = function () {
  95529. this._activePointer = true;
  95530. };
  95531. /** @hidden */
  95532. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  95533. this._activePointer = false;
  95534. };
  95535. /** @hidden */
  95536. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  95537. if (distance === void 0) { distance = 100; }
  95538. };
  95539. VRExperienceHelperGazer.prototype.dispose = function () {
  95540. this._interactionsEnabled = false;
  95541. this._teleportationEnabled = false;
  95542. if (this._gazeTracker) {
  95543. this._gazeTracker.dispose();
  95544. }
  95545. };
  95546. VRExperienceHelperGazer._idCounter = 0;
  95547. return VRExperienceHelperGazer;
  95548. }());
  95549. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  95550. __extends(VRExperienceHelperControllerGazer, _super);
  95551. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  95552. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  95553. _this.webVRController = webVRController;
  95554. // Laser pointer
  95555. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  95556. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  95557. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  95558. laserPointerMaterial.alpha = 0.6;
  95559. _this._laserPointer.material = laserPointerMaterial;
  95560. _this._laserPointer.rotation.x = Math.PI / 2;
  95561. _this._laserPointer.position.z = -0.5;
  95562. _this._laserPointer.isVisible = false;
  95563. _this._laserPointer.isPickable = false;
  95564. if (!webVRController.mesh) {
  95565. // Create an empty mesh that is used prior to loading the high quality model
  95566. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  95567. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  95568. preloadPointerPose.rotation.x = -0.7;
  95569. preloadMesh.addChild(preloadPointerPose);
  95570. webVRController.attachToMesh(preloadMesh);
  95571. }
  95572. _this._setLaserPointerParent(webVRController.mesh);
  95573. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  95574. _this._setLaserPointerParent(mesh);
  95575. });
  95576. return _this;
  95577. }
  95578. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  95579. return this.webVRController.getForwardRay(length);
  95580. };
  95581. /** @hidden */
  95582. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  95583. _super.prototype._activatePointer.call(this);
  95584. this._laserPointer.isVisible = true;
  95585. };
  95586. /** @hidden */
  95587. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  95588. _super.prototype._deactivatePointer.call(this);
  95589. this._laserPointer.isVisible = false;
  95590. };
  95591. /** @hidden */
  95592. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  95593. this._laserPointer.material.emissiveColor = color;
  95594. };
  95595. /** @hidden */
  95596. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  95597. var makeNotPick = function (root) {
  95598. root.isPickable = false;
  95599. root.getChildMeshes().forEach(function (c) {
  95600. makeNotPick(c);
  95601. });
  95602. };
  95603. makeNotPick(mesh);
  95604. var childMeshes = mesh.getChildMeshes();
  95605. this.webVRController._pointingPoseNode = null;
  95606. for (var i = 0; i < childMeshes.length; i++) {
  95607. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  95608. mesh = childMeshes[i];
  95609. this.webVRController._pointingPoseNode = mesh;
  95610. break;
  95611. }
  95612. }
  95613. this._laserPointer.parent = mesh;
  95614. };
  95615. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  95616. if (distance === void 0) { distance = 100; }
  95617. this._laserPointer.scaling.y = distance;
  95618. this._laserPointer.position.z = -distance / 2;
  95619. };
  95620. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  95621. _super.prototype.dispose.call(this);
  95622. this._laserPointer.dispose();
  95623. if (this._meshAttachedObserver) {
  95624. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  95625. }
  95626. };
  95627. return VRExperienceHelperControllerGazer;
  95628. }(VRExperienceHelperGazer));
  95629. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  95630. __extends(VRExperienceHelperCameraGazer, _super);
  95631. function VRExperienceHelperCameraGazer(getCamera, scene) {
  95632. var _this = _super.call(this, scene) || this;
  95633. _this.getCamera = getCamera;
  95634. return _this;
  95635. }
  95636. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  95637. var camera = this.getCamera();
  95638. if (camera) {
  95639. return camera.getForwardRay(length);
  95640. }
  95641. else {
  95642. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  95643. }
  95644. };
  95645. return VRExperienceHelperCameraGazer;
  95646. }(VRExperienceHelperGazer));
  95647. /**
  95648. * Helps to quickly add VR support to an existing scene.
  95649. * See http://doc.babylonjs.com/how_to/webvr_helper
  95650. */
  95651. var VRExperienceHelper = /** @class */ (function () {
  95652. /**
  95653. * Instantiates a VRExperienceHelper.
  95654. * Helps to quickly add VR support to an existing scene.
  95655. * @param scene The scene the VRExperienceHelper belongs to.
  95656. * @param webVROptions Options to modify the vr experience helper's behavior.
  95657. */
  95658. function VRExperienceHelper(scene,
  95659. /** Options to modify the vr experience helper's behavior. */
  95660. webVROptions) {
  95661. if (webVROptions === void 0) { webVROptions = {}; }
  95662. var _this = this;
  95663. this.webVROptions = webVROptions;
  95664. // Can the system support WebVR, even if a headset isn't plugged in?
  95665. this._webVRsupported = false;
  95666. // If WebVR is supported, is a headset plugged in and are we ready to present?
  95667. this._webVRready = false;
  95668. // Are we waiting for the requestPresent callback to complete?
  95669. this._webVRrequesting = false;
  95670. // Are we presenting to the headset right now? (this is the vrDevice state)
  95671. this._webVRpresenting = false;
  95672. // Are we presenting in the fullscreen fallback?
  95673. this._fullscreenVRpresenting = false;
  95674. /**
  95675. * Observable raised when entering VR.
  95676. */
  95677. this.onEnteringVRObservable = new BABYLON.Observable();
  95678. /**
  95679. * Observable raised when exiting VR.
  95680. */
  95681. this.onExitingVRObservable = new BABYLON.Observable();
  95682. /**
  95683. * Observable raised when controller mesh is loaded.
  95684. */
  95685. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  95686. this._useCustomVRButton = false;
  95687. this._teleportationRequested = false;
  95688. this._teleportActive = false;
  95689. this._floorMeshesCollection = [];
  95690. this._rotationAllowed = true;
  95691. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  95692. this._isDefaultTeleportationTarget = true;
  95693. this._teleportationFillColor = "#444444";
  95694. this._teleportationBorderColor = "#FFFFFF";
  95695. this._rotationAngle = 0;
  95696. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  95697. this._padSensibilityUp = 0.65;
  95698. this._padSensibilityDown = 0.35;
  95699. this._leftController = null;
  95700. this._rightController = null;
  95701. /**
  95702. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  95703. */
  95704. this.onNewMeshSelected = new BABYLON.Observable();
  95705. /**
  95706. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  95707. */
  95708. this.onNewMeshPicked = new BABYLON.Observable();
  95709. /**
  95710. * Observable raised before camera teleportation
  95711. */
  95712. this.onBeforeCameraTeleport = new BABYLON.Observable();
  95713. /**
  95714. * Observable raised after camera teleportation
  95715. */
  95716. this.onAfterCameraTeleport = new BABYLON.Observable();
  95717. /**
  95718. * Observable raised when current selected mesh gets unselected
  95719. */
  95720. this.onSelectedMeshUnselected = new BABYLON.Observable();
  95721. /**
  95722. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  95723. */
  95724. this.teleportationEnabled = true;
  95725. this._teleportationInitialized = false;
  95726. this._interactionsEnabled = false;
  95727. this._interactionsRequested = false;
  95728. this._displayGaze = true;
  95729. this._displayLaserPointer = true;
  95730. /**
  95731. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  95732. */
  95733. this.updateGazeTrackerScale = true;
  95734. this._onResize = function () {
  95735. _this.moveButtonToBottomRight();
  95736. if (_this._fullscreenVRpresenting && _this._webVRready) {
  95737. _this.exitVR();
  95738. }
  95739. };
  95740. this._onFullscreenChange = function () {
  95741. if (document.fullscreen !== undefined) {
  95742. _this._fullscreenVRpresenting = document.fullscreen;
  95743. }
  95744. else if (document.mozFullScreen !== undefined) {
  95745. _this._fullscreenVRpresenting = document.mozFullScreen;
  95746. }
  95747. else if (document.webkitIsFullScreen !== undefined) {
  95748. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  95749. }
  95750. else if (document.msIsFullScreen !== undefined) {
  95751. _this._fullscreenVRpresenting = document.msIsFullScreen;
  95752. }
  95753. else if (document.msFullscreenElement !== undefined) {
  95754. _this._fullscreenVRpresenting = document.msFullscreenElement;
  95755. }
  95756. if (!_this._fullscreenVRpresenting && _this._canvas) {
  95757. _this.exitVR();
  95758. if (!_this._useCustomVRButton) {
  95759. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  95760. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  95761. }
  95762. }
  95763. };
  95764. this.beforeRender = function () {
  95765. if (_this._leftController && _this._leftController._activePointer) {
  95766. _this._castRayAndSelectObject(_this._leftController);
  95767. }
  95768. if (_this._rightController && _this._rightController._activePointer) {
  95769. _this._castRayAndSelectObject(_this._rightController);
  95770. }
  95771. if (_this._noControllerIsActive) {
  95772. _this._castRayAndSelectObject(_this._cameraGazer);
  95773. }
  95774. else {
  95775. _this._cameraGazer._gazeTracker.isVisible = false;
  95776. }
  95777. };
  95778. this._onNewGamepadConnected = function (gamepad) {
  95779. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  95780. if (gamepad.leftStick) {
  95781. gamepad.onleftstickchanged(function (stickValues) {
  95782. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  95783. // Listening to classic/xbox gamepad only if no VR controller is active
  95784. if ((!_this._leftController && !_this._rightController) ||
  95785. ((_this._leftController && !_this._leftController._activePointer) &&
  95786. (_this._rightController && !_this._rightController._activePointer))) {
  95787. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  95788. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  95789. }
  95790. }
  95791. });
  95792. }
  95793. if (gamepad.rightStick) {
  95794. gamepad.onrightstickchanged(function (stickValues) {
  95795. if (_this._teleportationInitialized) {
  95796. _this._checkRotate(stickValues, _this._cameraGazer);
  95797. }
  95798. });
  95799. }
  95800. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  95801. gamepad.onbuttondown(function (buttonPressed) {
  95802. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  95803. _this._cameraGazer._selectionPointerDown();
  95804. }
  95805. });
  95806. gamepad.onbuttonup(function (buttonPressed) {
  95807. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  95808. _this._cameraGazer._selectionPointerUp();
  95809. }
  95810. });
  95811. }
  95812. }
  95813. else {
  95814. var webVRController = gamepad;
  95815. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  95816. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  95817. _this._rightController = controller;
  95818. }
  95819. else {
  95820. _this._leftController = controller;
  95821. }
  95822. _this._tryEnableInteractionOnController(controller);
  95823. }
  95824. };
  95825. // 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
  95826. this._tryEnableInteractionOnController = function (controller) {
  95827. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  95828. _this._enableInteractionOnController(controller);
  95829. }
  95830. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  95831. _this._enableTeleportationOnController(controller);
  95832. }
  95833. };
  95834. this._onNewGamepadDisconnected = function (gamepad) {
  95835. if (gamepad instanceof BABYLON.WebVRController) {
  95836. if (gamepad.hand === "left" && _this._leftController != null) {
  95837. _this._leftController.dispose();
  95838. _this._leftController = null;
  95839. }
  95840. if (gamepad.hand === "right" && _this._rightController != null) {
  95841. _this._rightController.dispose();
  95842. _this._rightController = null;
  95843. }
  95844. }
  95845. };
  95846. this._workingVector = BABYLON.Vector3.Zero();
  95847. this._workingQuaternion = BABYLON.Quaternion.Identity();
  95848. this._workingMatrix = BABYLON.Matrix.Identity();
  95849. this._scene = scene;
  95850. this._canvas = scene.getEngine().getRenderingCanvas();
  95851. // Parse options
  95852. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  95853. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  95854. }
  95855. if (webVROptions.createDeviceOrientationCamera === undefined) {
  95856. webVROptions.createDeviceOrientationCamera = true;
  95857. }
  95858. if (webVROptions.laserToggle === undefined) {
  95859. webVROptions.laserToggle = true;
  95860. }
  95861. if (webVROptions.defaultHeight === undefined) {
  95862. webVROptions.defaultHeight = 1.7;
  95863. }
  95864. if (webVROptions.useCustomVRButton) {
  95865. this._useCustomVRButton = true;
  95866. if (webVROptions.customVRButton) {
  95867. this._btnVR = webVROptions.customVRButton;
  95868. }
  95869. }
  95870. if (webVROptions.rayLength) {
  95871. this._rayLength = webVROptions.rayLength;
  95872. }
  95873. this._defaultHeight = webVROptions.defaultHeight;
  95874. if (webVROptions.positionScale) {
  95875. this._rayLength *= webVROptions.positionScale;
  95876. this._defaultHeight *= webVROptions.positionScale;
  95877. }
  95878. this._hasEnteredVR = false;
  95879. // Set position
  95880. if (this._scene.activeCamera) {
  95881. this._position = this._scene.activeCamera.position.clone();
  95882. }
  95883. else {
  95884. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  95885. }
  95886. // Set non-vr camera
  95887. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  95888. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  95889. // Copy data from existing camera
  95890. if (this._scene.activeCamera) {
  95891. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  95892. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  95893. // Set rotation from previous camera
  95894. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  95895. var targetCamera = this._scene.activeCamera;
  95896. if (targetCamera.rotationQuaternion) {
  95897. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  95898. }
  95899. else {
  95900. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  95901. }
  95902. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  95903. }
  95904. }
  95905. this._scene.activeCamera = this._deviceOrientationCamera;
  95906. if (this._canvas) {
  95907. this._scene.activeCamera.attachControl(this._canvas);
  95908. }
  95909. }
  95910. else {
  95911. this._existingCamera = this._scene.activeCamera;
  95912. }
  95913. // Create VR cameras
  95914. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  95915. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  95916. }
  95917. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  95918. this._webVRCamera.useStandingMatrix();
  95919. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  95920. // Create default button
  95921. if (!this._useCustomVRButton) {
  95922. this._btnVR = document.createElement("BUTTON");
  95923. this._btnVR.className = "babylonVRicon";
  95924. this._btnVR.id = "babylonVRiconbtn";
  95925. this._btnVR.title = "Click to switch to VR";
  95926. 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) }";
  95927. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  95928. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  95929. // css += ".babylonVRicon.vrdisplaysupported { }";
  95930. // css += ".babylonVRicon.vrdisplayready { }";
  95931. // css += ".babylonVRicon.vrdisplayrequesting { }";
  95932. var style = document.createElement('style');
  95933. style.appendChild(document.createTextNode(css));
  95934. document.getElementsByTagName('head')[0].appendChild(style);
  95935. this.moveButtonToBottomRight();
  95936. }
  95937. // VR button click event
  95938. if (this._btnVR) {
  95939. this._btnVR.addEventListener("click", function () {
  95940. if (!_this.isInVRMode) {
  95941. _this.enterVR();
  95942. }
  95943. else {
  95944. _this.exitVR();
  95945. }
  95946. });
  95947. }
  95948. // Window events
  95949. window.addEventListener("resize", this._onResize);
  95950. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  95951. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  95952. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  95953. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  95954. document.onmsfullscreenchange = this._onFullscreenChange;
  95955. // Display vr button when headset is connected
  95956. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  95957. this.displayVRButton();
  95958. }
  95959. else {
  95960. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  95961. if (e.vrDisplay) {
  95962. _this.displayVRButton();
  95963. }
  95964. });
  95965. }
  95966. // Exiting VR mode using 'ESC' key on desktop
  95967. this._onKeyDown = function (event) {
  95968. if (event.keyCode === 27 && _this.isInVRMode) {
  95969. _this.exitVR();
  95970. }
  95971. };
  95972. document.addEventListener("keydown", this._onKeyDown);
  95973. // Exiting VR mode double tapping the touch screen
  95974. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  95975. if (_this.isInVRMode) {
  95976. _this.exitVR();
  95977. if (_this._fullscreenVRpresenting) {
  95978. _this._scene.getEngine().switchFullscreen(true);
  95979. }
  95980. }
  95981. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  95982. // Listen for WebVR display changes
  95983. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  95984. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  95985. this._onVRRequestPresentStart = function () {
  95986. _this._webVRrequesting = true;
  95987. _this.updateButtonVisibility();
  95988. };
  95989. this._onVRRequestPresentComplete = function (success) {
  95990. _this._webVRrequesting = false;
  95991. _this.updateButtonVisibility();
  95992. };
  95993. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  95994. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  95995. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  95996. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  95997. scene.onDisposeObservable.add(function () {
  95998. _this.dispose();
  95999. });
  96000. // Gamepad connection events
  96001. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  96002. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  96003. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  96004. this.updateButtonVisibility();
  96005. //create easing functions
  96006. this._circleEase = new BABYLON.CircleEase();
  96007. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  96008. if (this.webVROptions.floorMeshes) {
  96009. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  96010. }
  96011. }
  96012. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  96013. /** Return this.onEnteringVRObservable
  96014. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  96015. */
  96016. get: function () {
  96017. return this.onEnteringVRObservable;
  96018. },
  96019. enumerable: true,
  96020. configurable: true
  96021. });
  96022. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  96023. /** Return this.onExitingVRObservable
  96024. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  96025. */
  96026. get: function () {
  96027. return this.onExitingVRObservable;
  96028. },
  96029. enumerable: true,
  96030. configurable: true
  96031. });
  96032. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  96033. /** Return this.onControllerMeshLoadedObservable
  96034. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  96035. */
  96036. get: function () {
  96037. return this.onControllerMeshLoadedObservable;
  96038. },
  96039. enumerable: true,
  96040. configurable: true
  96041. });
  96042. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  96043. /**
  96044. * The mesh used to display where the user is going to teleport.
  96045. */
  96046. get: function () {
  96047. return this._teleportationTarget;
  96048. },
  96049. /**
  96050. * Sets the mesh to be used to display where the user is going to teleport.
  96051. */
  96052. set: function (value) {
  96053. if (value) {
  96054. value.name = "teleportationTarget";
  96055. this._isDefaultTeleportationTarget = false;
  96056. this._teleportationTarget = value;
  96057. }
  96058. },
  96059. enumerable: true,
  96060. configurable: true
  96061. });
  96062. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  96063. /**
  96064. * 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
  96065. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  96066. * See http://doc.babylonjs.com/resources/baking_transformations
  96067. */
  96068. get: function () {
  96069. return this._cameraGazer._gazeTracker;
  96070. },
  96071. set: function (value) {
  96072. if (value) {
  96073. // Dispose of existing meshes
  96074. if (this._cameraGazer._gazeTracker) {
  96075. this._cameraGazer._gazeTracker.dispose();
  96076. }
  96077. if (this._leftController && this._leftController._gazeTracker) {
  96078. this._leftController._gazeTracker.dispose();
  96079. }
  96080. if (this._rightController && this._rightController._gazeTracker) {
  96081. this._rightController._gazeTracker.dispose();
  96082. }
  96083. // Set and create gaze trackers on head and controllers
  96084. this._cameraGazer._gazeTracker = value;
  96085. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  96086. this._cameraGazer._gazeTracker.isPickable = false;
  96087. this._cameraGazer._gazeTracker.isVisible = false;
  96088. this._cameraGazer._gazeTracker.name = "gazeTracker";
  96089. if (this._leftController) {
  96090. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  96091. }
  96092. if (this._rightController) {
  96093. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  96094. }
  96095. }
  96096. },
  96097. enumerable: true,
  96098. configurable: true
  96099. });
  96100. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  96101. /**
  96102. * The gaze tracking mesh corresponding to the left controller
  96103. */
  96104. get: function () {
  96105. if (this._leftController) {
  96106. return this._leftController._gazeTracker;
  96107. }
  96108. return null;
  96109. },
  96110. enumerable: true,
  96111. configurable: true
  96112. });
  96113. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  96114. /**
  96115. * The gaze tracking mesh corresponding to the right controller
  96116. */
  96117. get: function () {
  96118. if (this._rightController) {
  96119. return this._rightController._gazeTracker;
  96120. }
  96121. return null;
  96122. },
  96123. enumerable: true,
  96124. configurable: true
  96125. });
  96126. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  96127. /**
  96128. * If the ray of the gaze should be displayed.
  96129. */
  96130. get: function () {
  96131. return this._displayGaze;
  96132. },
  96133. /**
  96134. * Sets if the ray of the gaze should be displayed.
  96135. */
  96136. set: function (value) {
  96137. this._displayGaze = value;
  96138. if (!value) {
  96139. this._cameraGazer._gazeTracker.isVisible = false;
  96140. if (this._leftController) {
  96141. this._leftController._gazeTracker.isVisible = false;
  96142. }
  96143. if (this._rightController) {
  96144. this._rightController._gazeTracker.isVisible = false;
  96145. }
  96146. }
  96147. },
  96148. enumerable: true,
  96149. configurable: true
  96150. });
  96151. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  96152. /**
  96153. * If the ray of the LaserPointer should be displayed.
  96154. */
  96155. get: function () {
  96156. return this._displayLaserPointer;
  96157. },
  96158. /**
  96159. * Sets if the ray of the LaserPointer should be displayed.
  96160. */
  96161. set: function (value) {
  96162. this._displayLaserPointer = value;
  96163. if (!value) {
  96164. if (this._rightController) {
  96165. this._rightController._deactivatePointer();
  96166. this._rightController._gazeTracker.isVisible = false;
  96167. }
  96168. if (this._leftController) {
  96169. this._leftController._deactivatePointer();
  96170. this._leftController._gazeTracker.isVisible = false;
  96171. }
  96172. }
  96173. else {
  96174. if (this._rightController) {
  96175. this._rightController._activatePointer();
  96176. }
  96177. if (this._leftController) {
  96178. this._leftController._activatePointer();
  96179. }
  96180. }
  96181. },
  96182. enumerable: true,
  96183. configurable: true
  96184. });
  96185. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  96186. /**
  96187. * The deviceOrientationCamera used as the camera when not in VR.
  96188. */
  96189. get: function () {
  96190. return this._deviceOrientationCamera;
  96191. },
  96192. enumerable: true,
  96193. configurable: true
  96194. });
  96195. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  96196. /**
  96197. * Based on the current WebVR support, returns the current VR camera used.
  96198. */
  96199. get: function () {
  96200. if (this._webVRready) {
  96201. return this._webVRCamera;
  96202. }
  96203. else {
  96204. return this._scene.activeCamera;
  96205. }
  96206. },
  96207. enumerable: true,
  96208. configurable: true
  96209. });
  96210. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  96211. /**
  96212. * The webVRCamera which is used when in VR.
  96213. */
  96214. get: function () {
  96215. return this._webVRCamera;
  96216. },
  96217. enumerable: true,
  96218. configurable: true
  96219. });
  96220. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  96221. /**
  96222. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  96223. */
  96224. get: function () {
  96225. return this._vrDeviceOrientationCamera;
  96226. },
  96227. enumerable: true,
  96228. configurable: true
  96229. });
  96230. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  96231. get: function () {
  96232. var result = this._cameraGazer._teleportationRequestInitiated
  96233. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  96234. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  96235. return result;
  96236. },
  96237. enumerable: true,
  96238. configurable: true
  96239. });
  96240. // Raised when one of the controller has loaded successfully its associated default mesh
  96241. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  96242. if (this._leftController && this._leftController.webVRController == webVRController) {
  96243. if (webVRController.mesh) {
  96244. this._leftController._setLaserPointerParent(webVRController.mesh);
  96245. }
  96246. }
  96247. if (this._rightController && this._rightController.webVRController == webVRController) {
  96248. if (webVRController.mesh) {
  96249. this._rightController._setLaserPointerParent(webVRController.mesh);
  96250. }
  96251. }
  96252. try {
  96253. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  96254. }
  96255. catch (err) {
  96256. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  96257. }
  96258. };
  96259. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  96260. /**
  96261. * Gets a value indicating if we are currently in VR mode.
  96262. */
  96263. get: function () {
  96264. return this._webVRpresenting || this._fullscreenVRpresenting;
  96265. },
  96266. enumerable: true,
  96267. configurable: true
  96268. });
  96269. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  96270. var vrDisplay = this._scene.getEngine().getVRDevice();
  96271. if (vrDisplay) {
  96272. var wasPresenting = this._webVRpresenting;
  96273. this._webVRpresenting = vrDisplay.isPresenting;
  96274. if (wasPresenting && !this._webVRpresenting)
  96275. this.exitVR();
  96276. }
  96277. else {
  96278. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  96279. }
  96280. this.updateButtonVisibility();
  96281. };
  96282. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  96283. this._webVRsupported = eventArgs.vrSupported;
  96284. this._webVRready = !!eventArgs.vrDisplay;
  96285. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  96286. this.updateButtonVisibility();
  96287. };
  96288. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  96289. if (this._canvas && !this._useCustomVRButton) {
  96290. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  96291. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  96292. }
  96293. };
  96294. VRExperienceHelper.prototype.displayVRButton = function () {
  96295. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  96296. document.body.appendChild(this._btnVR);
  96297. this._btnVRDisplayed = true;
  96298. }
  96299. };
  96300. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  96301. if (!this._btnVR || this._useCustomVRButton) {
  96302. return;
  96303. }
  96304. this._btnVR.className = "babylonVRicon";
  96305. if (this.isInVRMode) {
  96306. this._btnVR.className += " vrdisplaypresenting";
  96307. }
  96308. else {
  96309. if (this._webVRready)
  96310. this._btnVR.className += " vrdisplayready";
  96311. if (this._webVRsupported)
  96312. this._btnVR.className += " vrdisplaysupported";
  96313. if (this._webVRrequesting)
  96314. this._btnVR.className += " vrdisplayrequesting";
  96315. }
  96316. };
  96317. /**
  96318. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  96319. * Otherwise, will use the fullscreen API.
  96320. */
  96321. VRExperienceHelper.prototype.enterVR = function () {
  96322. if (this.onEnteringVRObservable) {
  96323. try {
  96324. this.onEnteringVRObservable.notifyObservers(this);
  96325. }
  96326. catch (err) {
  96327. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  96328. }
  96329. }
  96330. if (this._scene.activeCamera) {
  96331. this._position = this._scene.activeCamera.position.clone();
  96332. // make sure that we return to the last active camera
  96333. this._existingCamera = this._scene.activeCamera;
  96334. }
  96335. if (this._webVRrequesting)
  96336. return;
  96337. // If WebVR is supported and a headset is connected
  96338. if (this._webVRready) {
  96339. if (!this._webVRpresenting) {
  96340. this._webVRCamera.position = this._position;
  96341. this._scene.activeCamera = this._webVRCamera;
  96342. }
  96343. }
  96344. else if (this._vrDeviceOrientationCamera) {
  96345. this._vrDeviceOrientationCamera.position = this._position;
  96346. if (this._scene.activeCamera) {
  96347. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  96348. }
  96349. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  96350. this._scene.getEngine().switchFullscreen(true);
  96351. this.updateButtonVisibility();
  96352. }
  96353. if (this._scene.activeCamera && this._canvas) {
  96354. this._scene.activeCamera.attachControl(this._canvas);
  96355. }
  96356. if (this._interactionsEnabled) {
  96357. this._scene.registerBeforeRender(this.beforeRender);
  96358. }
  96359. this._hasEnteredVR = true;
  96360. };
  96361. /**
  96362. * Attempt to exit VR, or fullscreen.
  96363. */
  96364. VRExperienceHelper.prototype.exitVR = function () {
  96365. if (this._hasEnteredVR) {
  96366. if (this.onExitingVRObservable) {
  96367. try {
  96368. this.onExitingVRObservable.notifyObservers(this);
  96369. }
  96370. catch (err) {
  96371. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  96372. }
  96373. }
  96374. if (this._webVRpresenting) {
  96375. this._scene.getEngine().disableVR();
  96376. }
  96377. if (this._scene.activeCamera) {
  96378. this._position = this._scene.activeCamera.position.clone();
  96379. }
  96380. if (this._deviceOrientationCamera) {
  96381. this._deviceOrientationCamera.position = this._position;
  96382. this._scene.activeCamera = this._deviceOrientationCamera;
  96383. if (this._canvas) {
  96384. this._scene.activeCamera.attachControl(this._canvas);
  96385. }
  96386. }
  96387. else if (this._existingCamera) {
  96388. this._existingCamera.position = this._position;
  96389. this._scene.activeCamera = this._existingCamera;
  96390. }
  96391. this.updateButtonVisibility();
  96392. if (this._interactionsEnabled) {
  96393. this._scene.unregisterBeforeRender(this.beforeRender);
  96394. this._cameraGazer._gazeTracker.isVisible = false;
  96395. if (this._leftController) {
  96396. this._leftController._gazeTracker.isVisible = false;
  96397. }
  96398. if (this._rightController) {
  96399. this._rightController._gazeTracker.isVisible = false;
  96400. }
  96401. }
  96402. // resize to update width and height when exiting vr exits fullscreen
  96403. this._scene.getEngine().resize();
  96404. this._hasEnteredVR = false;
  96405. }
  96406. };
  96407. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  96408. /**
  96409. * The position of the vr experience helper.
  96410. */
  96411. get: function () {
  96412. return this._position;
  96413. },
  96414. /**
  96415. * Sets the position of the vr experience helper.
  96416. */
  96417. set: function (value) {
  96418. this._position = value;
  96419. if (this._scene.activeCamera) {
  96420. this._scene.activeCamera.position = value;
  96421. }
  96422. },
  96423. enumerable: true,
  96424. configurable: true
  96425. });
  96426. /**
  96427. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  96428. */
  96429. VRExperienceHelper.prototype.enableInteractions = function () {
  96430. var _this = this;
  96431. if (!this._interactionsEnabled) {
  96432. this._interactionsRequested = true;
  96433. if (this._leftController) {
  96434. this._enableInteractionOnController(this._leftController);
  96435. }
  96436. if (this._rightController) {
  96437. this._enableInteractionOnController(this._rightController);
  96438. }
  96439. this.raySelectionPredicate = function (mesh) {
  96440. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  96441. };
  96442. this.meshSelectionPredicate = function (mesh) {
  96443. return true;
  96444. };
  96445. this._raySelectionPredicate = function (mesh) {
  96446. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  96447. && mesh.name.indexOf("teleportationTarget") === -1
  96448. && mesh.name.indexOf("torusTeleportation") === -1)) {
  96449. return _this.raySelectionPredicate(mesh);
  96450. }
  96451. return false;
  96452. };
  96453. this._interactionsEnabled = true;
  96454. }
  96455. };
  96456. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  96457. get: function () {
  96458. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  96459. },
  96460. enumerable: true,
  96461. configurable: true
  96462. });
  96463. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  96464. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  96465. if (this._floorMeshesCollection[i].id === mesh.id) {
  96466. return true;
  96467. }
  96468. }
  96469. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  96470. return true;
  96471. }
  96472. return false;
  96473. };
  96474. /**
  96475. * Adds a floor mesh to be used for teleportation.
  96476. * @param floorMesh the mesh to be used for teleportation.
  96477. */
  96478. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  96479. if (!this._floorMeshesCollection) {
  96480. return;
  96481. }
  96482. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  96483. return;
  96484. }
  96485. this._floorMeshesCollection.push(floorMesh);
  96486. };
  96487. /**
  96488. * Removes a floor mesh from being used for teleportation.
  96489. * @param floorMesh the mesh to be removed.
  96490. */
  96491. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  96492. if (!this._floorMeshesCollection) {
  96493. return;
  96494. }
  96495. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  96496. if (meshIndex !== -1) {
  96497. this._floorMeshesCollection.splice(meshIndex, 1);
  96498. }
  96499. };
  96500. /**
  96501. * Enables interactions and teleportation using the VR controllers and gaze.
  96502. * @param vrTeleportationOptions options to modify teleportation behavior.
  96503. */
  96504. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  96505. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  96506. if (!this._teleportationInitialized) {
  96507. this._teleportationRequested = true;
  96508. this.enableInteractions();
  96509. if (vrTeleportationOptions.floorMeshName) {
  96510. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  96511. }
  96512. if (vrTeleportationOptions.floorMeshes) {
  96513. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  96514. }
  96515. if (this._leftController != null) {
  96516. this._enableTeleportationOnController(this._leftController);
  96517. }
  96518. if (this._rightController != null) {
  96519. this._enableTeleportationOnController(this._rightController);
  96520. }
  96521. // Creates an image processing post process for the vignette not relying
  96522. // on the main scene configuration for image processing to reduce setup and spaces
  96523. // (gamma/linear) conflicts.
  96524. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  96525. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  96526. imageProcessingConfiguration.vignetteEnabled = true;
  96527. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  96528. this._webVRCamera.detachPostProcess(this._postProcessMove);
  96529. this._teleportationInitialized = true;
  96530. if (this._isDefaultTeleportationTarget) {
  96531. this._createTeleportationCircles();
  96532. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  96533. }
  96534. }
  96535. };
  96536. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  96537. var _this = this;
  96538. var controllerMesh = controller.webVRController.mesh;
  96539. if (controllerMesh) {
  96540. controller._interactionsEnabled = true;
  96541. controller._activatePointer();
  96542. if (this.webVROptions.laserToggle) {
  96543. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  96544. // Enabling / disabling laserPointer
  96545. if (_this._displayLaserPointer && stateObject.value === 1) {
  96546. if (controller._activePointer) {
  96547. controller._deactivatePointer();
  96548. }
  96549. else {
  96550. controller._activatePointer();
  96551. }
  96552. if (_this.displayGaze) {
  96553. controller._gazeTracker.isVisible = controller._activePointer;
  96554. }
  96555. }
  96556. });
  96557. }
  96558. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  96559. var gazer = controller;
  96560. if (_this._noControllerIsActive) {
  96561. gazer = _this._cameraGazer;
  96562. }
  96563. if (!gazer._pointerDownOnMeshAsked) {
  96564. if (stateObject.value > _this._padSensibilityUp) {
  96565. gazer._selectionPointerDown();
  96566. }
  96567. }
  96568. else if (stateObject.value < _this._padSensibilityDown) {
  96569. gazer._selectionPointerUp();
  96570. }
  96571. });
  96572. }
  96573. };
  96574. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  96575. // Dont teleport if another gaze already requested teleportation
  96576. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  96577. return;
  96578. }
  96579. if (!gazer._teleportationRequestInitiated) {
  96580. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  96581. gazer._activatePointer();
  96582. gazer._teleportationRequestInitiated = true;
  96583. }
  96584. }
  96585. else {
  96586. // Listening to the proper controller values changes to confirm teleportation
  96587. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  96588. if (this._teleportActive) {
  96589. this._teleportCamera(this._haloCenter);
  96590. }
  96591. gazer._teleportationRequestInitiated = false;
  96592. }
  96593. }
  96594. };
  96595. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  96596. // Only rotate when user is not currently selecting a teleportation location
  96597. if (gazer._teleportationRequestInitiated) {
  96598. return;
  96599. }
  96600. if (!gazer._rotationLeftAsked) {
  96601. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  96602. gazer._rotationLeftAsked = true;
  96603. if (this._rotationAllowed) {
  96604. this._rotateCamera(false);
  96605. }
  96606. }
  96607. }
  96608. else {
  96609. if (stateObject.x > -this._padSensibilityDown) {
  96610. gazer._rotationLeftAsked = false;
  96611. }
  96612. }
  96613. if (!gazer._rotationRightAsked) {
  96614. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  96615. gazer._rotationRightAsked = true;
  96616. if (this._rotationAllowed) {
  96617. this._rotateCamera(true);
  96618. }
  96619. }
  96620. }
  96621. else {
  96622. if (stateObject.x < this._padSensibilityDown) {
  96623. gazer._rotationRightAsked = false;
  96624. }
  96625. }
  96626. };
  96627. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  96628. // Only teleport backwards when user is not currently selecting a teleportation location
  96629. if (gazer._teleportationRequestInitiated) {
  96630. return;
  96631. }
  96632. // Teleport backwards
  96633. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  96634. if (!gazer._teleportationBackRequestInitiated) {
  96635. if (!this.currentVRCamera) {
  96636. return;
  96637. }
  96638. // Get rotation and position of the current camera
  96639. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  96640. var position = this.currentVRCamera.position;
  96641. // If the camera has device position, use that instead
  96642. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  96643. rotation = this.currentVRCamera.deviceRotationQuaternion;
  96644. position = this.currentVRCamera.devicePosition;
  96645. }
  96646. // Get matrix with only the y rotation of the device rotation
  96647. rotation.toEulerAnglesToRef(this._workingVector);
  96648. this._workingVector.z = 0;
  96649. this._workingVector.x = 0;
  96650. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  96651. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  96652. // Rotate backwards ray by device rotation to cast at the ground behind the user
  96653. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  96654. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  96655. var ray = new BABYLON.Ray(position, this._workingVector);
  96656. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  96657. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  96658. this._teleportCamera(hit.pickedPoint);
  96659. }
  96660. gazer._teleportationBackRequestInitiated = true;
  96661. }
  96662. }
  96663. else {
  96664. gazer._teleportationBackRequestInitiated = false;
  96665. }
  96666. };
  96667. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  96668. var _this = this;
  96669. var controllerMesh = controller.webVRController.mesh;
  96670. if (controllerMesh) {
  96671. if (!controller._interactionsEnabled) {
  96672. this._enableInteractionOnController(controller);
  96673. }
  96674. controller._interactionsEnabled = true;
  96675. controller._teleportationEnabled = true;
  96676. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  96677. controller._dpadPressed = false;
  96678. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  96679. controller._dpadPressed = stateObject.pressed;
  96680. if (!controller._dpadPressed) {
  96681. controller._rotationLeftAsked = false;
  96682. controller._rotationRightAsked = false;
  96683. controller._teleportationBackRequestInitiated = false;
  96684. }
  96685. });
  96686. }
  96687. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  96688. if (_this.teleportationEnabled) {
  96689. _this._checkTeleportBackwards(stateObject, controller);
  96690. _this._checkTeleportWithRay(stateObject, controller);
  96691. }
  96692. _this._checkRotate(stateObject, controller);
  96693. });
  96694. }
  96695. };
  96696. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  96697. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  96698. this._teleportationTarget.isPickable = false;
  96699. var length = 512;
  96700. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  96701. dynamicTexture.hasAlpha = true;
  96702. var context = dynamicTexture.getContext();
  96703. var centerX = length / 2;
  96704. var centerY = length / 2;
  96705. var radius = 200;
  96706. context.beginPath();
  96707. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  96708. context.fillStyle = this._teleportationFillColor;
  96709. context.fill();
  96710. context.lineWidth = 10;
  96711. context.strokeStyle = this._teleportationBorderColor;
  96712. context.stroke();
  96713. context.closePath();
  96714. dynamicTexture.update();
  96715. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  96716. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  96717. this._teleportationTarget.material = teleportationCircleMaterial;
  96718. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  96719. torus.isPickable = false;
  96720. torus.parent = this._teleportationTarget;
  96721. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  96722. var keys = [];
  96723. keys.push({
  96724. frame: 0,
  96725. value: 0
  96726. });
  96727. keys.push({
  96728. frame: 30,
  96729. value: 0.4
  96730. });
  96731. keys.push({
  96732. frame: 60,
  96733. value: 0
  96734. });
  96735. animationInnerCircle.setKeys(keys);
  96736. var easingFunction = new BABYLON.SineEase();
  96737. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  96738. animationInnerCircle.setEasingFunction(easingFunction);
  96739. torus.animations = [];
  96740. torus.animations.push(animationInnerCircle);
  96741. this._scene.beginAnimation(torus, 0, 60, true);
  96742. this._hideTeleportationTarget();
  96743. };
  96744. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  96745. this._teleportActive = true;
  96746. if (this._teleportationInitialized) {
  96747. this._teleportationTarget.isVisible = true;
  96748. if (this._isDefaultTeleportationTarget) {
  96749. this._teleportationTarget.getChildren()[0].isVisible = true;
  96750. }
  96751. }
  96752. };
  96753. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  96754. this._teleportActive = false;
  96755. if (this._teleportationInitialized) {
  96756. this._teleportationTarget.isVisible = false;
  96757. if (this._isDefaultTeleportationTarget) {
  96758. this._teleportationTarget.getChildren()[0].isVisible = false;
  96759. }
  96760. }
  96761. };
  96762. VRExperienceHelper.prototype._rotateCamera = function (right) {
  96763. var _this = this;
  96764. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  96765. return;
  96766. }
  96767. if (right) {
  96768. this._rotationAngle++;
  96769. }
  96770. else {
  96771. this._rotationAngle--;
  96772. }
  96773. this.currentVRCamera.animations = [];
  96774. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  96775. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96776. var animationRotationKeys = [];
  96777. animationRotationKeys.push({
  96778. frame: 0,
  96779. value: this.currentVRCamera.rotationQuaternion
  96780. });
  96781. animationRotationKeys.push({
  96782. frame: 6,
  96783. value: target
  96784. });
  96785. animationRotation.setKeys(animationRotationKeys);
  96786. animationRotation.setEasingFunction(this._circleEase);
  96787. this.currentVRCamera.animations.push(animationRotation);
  96788. this._postProcessMove.animations = [];
  96789. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96790. var vignetteWeightKeys = [];
  96791. vignetteWeightKeys.push({
  96792. frame: 0,
  96793. value: 0
  96794. });
  96795. vignetteWeightKeys.push({
  96796. frame: 3,
  96797. value: 4
  96798. });
  96799. vignetteWeightKeys.push({
  96800. frame: 6,
  96801. value: 0
  96802. });
  96803. animationPP.setKeys(vignetteWeightKeys);
  96804. animationPP.setEasingFunction(this._circleEase);
  96805. this._postProcessMove.animations.push(animationPP);
  96806. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96807. var vignetteStretchKeys = [];
  96808. vignetteStretchKeys.push({
  96809. frame: 0,
  96810. value: 0
  96811. });
  96812. vignetteStretchKeys.push({
  96813. frame: 3,
  96814. value: 10
  96815. });
  96816. vignetteStretchKeys.push({
  96817. frame: 6,
  96818. value: 0
  96819. });
  96820. animationPP2.setKeys(vignetteStretchKeys);
  96821. animationPP2.setEasingFunction(this._circleEase);
  96822. this._postProcessMove.animations.push(animationPP2);
  96823. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  96824. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  96825. this._postProcessMove.samples = 4;
  96826. this._webVRCamera.attachPostProcess(this._postProcessMove);
  96827. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  96828. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  96829. });
  96830. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  96831. };
  96832. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  96833. if (hit.pickedPoint) {
  96834. if (gazer._teleportationRequestInitiated) {
  96835. this._displayTeleportationTarget();
  96836. this._haloCenter.copyFrom(hit.pickedPoint);
  96837. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  96838. }
  96839. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  96840. if (pickNormal) {
  96841. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  96842. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  96843. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  96844. }
  96845. this._teleportationTarget.position.y += 0.1;
  96846. }
  96847. };
  96848. VRExperienceHelper.prototype._teleportCamera = function (location) {
  96849. var _this = this;
  96850. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  96851. return;
  96852. }
  96853. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  96854. // offset of the headset from the anchor.
  96855. if (this.webVRCamera.leftCamera) {
  96856. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  96857. this._workingVector.subtractInPlace(this.webVRCamera.position);
  96858. location.subtractToRef(this._workingVector, this._workingVector);
  96859. }
  96860. else {
  96861. this._workingVector.copyFrom(location);
  96862. }
  96863. // Add height to account for user's height offset
  96864. if (this.isInVRMode) {
  96865. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  96866. }
  96867. else {
  96868. this._workingVector.y += this._defaultHeight;
  96869. }
  96870. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  96871. // Create animation from the camera's position to the new location
  96872. this.currentVRCamera.animations = [];
  96873. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96874. var animationCameraTeleportationKeys = [{
  96875. frame: 0,
  96876. value: this.currentVRCamera.position
  96877. },
  96878. {
  96879. frame: 11,
  96880. value: this._workingVector
  96881. }
  96882. ];
  96883. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  96884. animationCameraTeleportation.setEasingFunction(this._circleEase);
  96885. this.currentVRCamera.animations.push(animationCameraTeleportation);
  96886. this._postProcessMove.animations = [];
  96887. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96888. var vignetteWeightKeys = [];
  96889. vignetteWeightKeys.push({
  96890. frame: 0,
  96891. value: 0
  96892. });
  96893. vignetteWeightKeys.push({
  96894. frame: 5,
  96895. value: 8
  96896. });
  96897. vignetteWeightKeys.push({
  96898. frame: 11,
  96899. value: 0
  96900. });
  96901. animationPP.setKeys(vignetteWeightKeys);
  96902. this._postProcessMove.animations.push(animationPP);
  96903. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96904. var vignetteStretchKeys = [];
  96905. vignetteStretchKeys.push({
  96906. frame: 0,
  96907. value: 0
  96908. });
  96909. vignetteStretchKeys.push({
  96910. frame: 5,
  96911. value: 10
  96912. });
  96913. vignetteStretchKeys.push({
  96914. frame: 11,
  96915. value: 0
  96916. });
  96917. animationPP2.setKeys(vignetteStretchKeys);
  96918. this._postProcessMove.animations.push(animationPP2);
  96919. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  96920. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  96921. this._webVRCamera.attachPostProcess(this._postProcessMove);
  96922. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  96923. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  96924. });
  96925. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  96926. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  96927. });
  96928. this._hideTeleportationTarget();
  96929. };
  96930. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  96931. if (normal) {
  96932. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  96933. if (angle < Math.PI / 2) {
  96934. normal.scaleInPlace(-1);
  96935. }
  96936. }
  96937. return normal;
  96938. };
  96939. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  96940. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  96941. return;
  96942. }
  96943. var ray = gazer._getForwardRay(this._rayLength);
  96944. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  96945. if (hit) {
  96946. // Populate the contrllers mesh that can be used for drag/drop
  96947. if (gazer._laserPointer) {
  96948. hit.originMesh = gazer._laserPointer.parent;
  96949. }
  96950. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  96951. }
  96952. gazer._currentHit = hit;
  96953. // Moving the gazeTracker on the mesh face targetted
  96954. if (hit && hit.pickedPoint) {
  96955. if (this._displayGaze) {
  96956. var multiplier = 1;
  96957. gazer._gazeTracker.isVisible = true;
  96958. if (gazer._isActionableMesh) {
  96959. multiplier = 3;
  96960. }
  96961. if (this.updateGazeTrackerScale) {
  96962. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  96963. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  96964. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  96965. }
  96966. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  96967. // To avoid z-fighting
  96968. var deltaFighting = 0.002;
  96969. if (pickNormal) {
  96970. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  96971. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  96972. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  96973. }
  96974. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  96975. if (gazer._gazeTracker.position.x < 0) {
  96976. gazer._gazeTracker.position.x += deltaFighting;
  96977. }
  96978. else {
  96979. gazer._gazeTracker.position.x -= deltaFighting;
  96980. }
  96981. if (gazer._gazeTracker.position.y < 0) {
  96982. gazer._gazeTracker.position.y += deltaFighting;
  96983. }
  96984. else {
  96985. gazer._gazeTracker.position.y -= deltaFighting;
  96986. }
  96987. if (gazer._gazeTracker.position.z < 0) {
  96988. gazer._gazeTracker.position.z += deltaFighting;
  96989. }
  96990. else {
  96991. gazer._gazeTracker.position.z -= deltaFighting;
  96992. }
  96993. }
  96994. // Changing the size of the laser pointer based on the distance from the targetted point
  96995. gazer._updatePointerDistance(hit.distance);
  96996. }
  96997. else {
  96998. gazer._updatePointerDistance();
  96999. gazer._gazeTracker.isVisible = false;
  97000. }
  97001. if (hit && hit.pickedMesh) {
  97002. // The object selected is the floor, we're in a teleportation scenario
  97003. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  97004. // Moving the teleportation area to this targetted point
  97005. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  97006. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  97007. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97008. }
  97009. gazer._currentMeshSelected = null;
  97010. if (gazer._teleportationRequestInitiated) {
  97011. this._moveTeleportationSelectorTo(hit, gazer, ray);
  97012. }
  97013. return;
  97014. }
  97015. // If not, we're in a selection scenario
  97016. //this._teleportationAllowed = false;
  97017. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  97018. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  97019. this.onNewMeshPicked.notifyObservers(hit);
  97020. gazer._currentMeshSelected = hit.pickedMesh;
  97021. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  97022. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  97023. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  97024. gazer._isActionableMesh = true;
  97025. }
  97026. else {
  97027. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97028. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97029. gazer._isActionableMesh = false;
  97030. }
  97031. try {
  97032. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  97033. }
  97034. catch (err) {
  97035. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  97036. }
  97037. }
  97038. else {
  97039. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97040. gazer._currentMeshSelected = null;
  97041. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97042. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97043. }
  97044. }
  97045. }
  97046. else {
  97047. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97048. gazer._currentMeshSelected = null;
  97049. //this._teleportationAllowed = false;
  97050. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97051. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97052. }
  97053. };
  97054. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  97055. if (mesh) {
  97056. this.onSelectedMeshUnselected.notifyObservers(mesh);
  97057. }
  97058. };
  97059. /**
  97060. * Sets the color of the laser ray from the vr controllers.
  97061. * @param color new color for the ray.
  97062. */
  97063. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  97064. if (this._leftController) {
  97065. this._leftController._setLaserPointerColor(color);
  97066. }
  97067. if (this._rightController) {
  97068. this._rightController._setLaserPointerColor(color);
  97069. }
  97070. };
  97071. /**
  97072. * Sets the color of the ray from the vr headsets gaze.
  97073. * @param color new color for the ray.
  97074. */
  97075. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  97076. if (!this._cameraGazer._gazeTracker.material) {
  97077. return;
  97078. }
  97079. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  97080. if (this._leftController) {
  97081. this._leftController._gazeTracker.material.emissiveColor = color;
  97082. }
  97083. if (this._rightController) {
  97084. this._rightController._gazeTracker.material.emissiveColor = color;
  97085. }
  97086. };
  97087. /**
  97088. * Exits VR and disposes of the vr experience helper
  97089. */
  97090. VRExperienceHelper.prototype.dispose = function () {
  97091. if (this.isInVRMode) {
  97092. this.exitVR();
  97093. }
  97094. if (this._postProcessMove) {
  97095. this._postProcessMove.dispose();
  97096. }
  97097. if (this._webVRCamera) {
  97098. this._webVRCamera.dispose();
  97099. }
  97100. if (this._vrDeviceOrientationCamera) {
  97101. this._vrDeviceOrientationCamera.dispose();
  97102. }
  97103. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  97104. document.body.removeChild(this._btnVR);
  97105. }
  97106. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  97107. this._deviceOrientationCamera.dispose();
  97108. }
  97109. if (this._cameraGazer) {
  97110. this._cameraGazer.dispose();
  97111. }
  97112. if (this._leftController) {
  97113. this._leftController.dispose();
  97114. }
  97115. if (this._rightController) {
  97116. this._rightController.dispose();
  97117. }
  97118. if (this._teleportationTarget) {
  97119. this._teleportationTarget.dispose();
  97120. }
  97121. this._floorMeshesCollection = [];
  97122. document.removeEventListener("keydown", this._onKeyDown);
  97123. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97124. window.removeEventListener("resize", this._onResize);
  97125. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  97126. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  97127. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  97128. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  97129. document.onmsfullscreenchange = null;
  97130. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  97131. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  97132. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  97133. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97134. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  97135. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  97136. this._scene.unregisterBeforeRender(this.beforeRender);
  97137. };
  97138. /**
  97139. * Gets the name of the VRExperienceHelper class
  97140. * @returns "VRExperienceHelper"
  97141. */
  97142. VRExperienceHelper.prototype.getClassName = function () {
  97143. return "VRExperienceHelper";
  97144. };
  97145. return VRExperienceHelper;
  97146. }());
  97147. BABYLON.VRExperienceHelper = VRExperienceHelper;
  97148. })(BABYLON || (BABYLON = {}));
  97149. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  97150. // Mainly based on these 2 articles :
  97151. // 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
  97152. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  97153. var BABYLON;
  97154. (function (BABYLON) {
  97155. /**
  97156. * Defines the potential axis of a Joystick
  97157. */
  97158. var JoystickAxis;
  97159. (function (JoystickAxis) {
  97160. /** X axis */
  97161. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  97162. /** Y axis */
  97163. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  97164. /** Z axis */
  97165. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  97166. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  97167. /**
  97168. * Class used to define virtual joystick (used in touch mode)
  97169. */
  97170. var VirtualJoystick = /** @class */ (function () {
  97171. /**
  97172. * Creates a new virtual joystick
  97173. * @param leftJoystick defines that the joystick is for left hand (false by default)
  97174. */
  97175. function VirtualJoystick(leftJoystick) {
  97176. var _this = this;
  97177. if (leftJoystick) {
  97178. this._leftJoystick = true;
  97179. }
  97180. else {
  97181. this._leftJoystick = false;
  97182. }
  97183. VirtualJoystick._globalJoystickIndex++;
  97184. // By default left & right arrow keys are moving the X
  97185. // and up & down keys are moving the Y
  97186. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  97187. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  97188. this.reverseLeftRight = false;
  97189. this.reverseUpDown = false;
  97190. // collections of pointers
  97191. this._touches = new BABYLON.StringDictionary();
  97192. this.deltaPosition = BABYLON.Vector3.Zero();
  97193. this._joystickSensibility = 25;
  97194. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  97195. this._onResize = function (evt) {
  97196. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  97197. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  97198. if (VirtualJoystick.vjCanvas) {
  97199. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  97200. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  97201. }
  97202. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  97203. };
  97204. // injecting a canvas element on top of the canvas 3D game
  97205. if (!VirtualJoystick.vjCanvas) {
  97206. window.addEventListener("resize", this._onResize, false);
  97207. VirtualJoystick.vjCanvas = document.createElement("canvas");
  97208. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  97209. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  97210. VirtualJoystick.vjCanvas.width = window.innerWidth;
  97211. VirtualJoystick.vjCanvas.height = window.innerHeight;
  97212. VirtualJoystick.vjCanvas.style.width = "100%";
  97213. VirtualJoystick.vjCanvas.style.height = "100%";
  97214. VirtualJoystick.vjCanvas.style.position = "absolute";
  97215. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  97216. VirtualJoystick.vjCanvas.style.top = "0px";
  97217. VirtualJoystick.vjCanvas.style.left = "0px";
  97218. VirtualJoystick.vjCanvas.style.zIndex = "5";
  97219. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  97220. // Support for jQuery PEP polyfill
  97221. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  97222. var context = VirtualJoystick.vjCanvas.getContext('2d');
  97223. if (!context) {
  97224. throw new Error("Unable to create canvas for virtual joystick");
  97225. }
  97226. VirtualJoystick.vjCanvasContext = context;
  97227. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  97228. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  97229. document.body.appendChild(VirtualJoystick.vjCanvas);
  97230. }
  97231. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  97232. this.pressed = false;
  97233. // default joystick color
  97234. this._joystickColor = "cyan";
  97235. this._joystickPointerID = -1;
  97236. // current joystick position
  97237. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  97238. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  97239. // origin joystick position
  97240. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  97241. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  97242. this._onPointerDownHandlerRef = function (evt) {
  97243. _this._onPointerDown(evt);
  97244. };
  97245. this._onPointerMoveHandlerRef = function (evt) {
  97246. _this._onPointerMove(evt);
  97247. };
  97248. this._onPointerUpHandlerRef = function (evt) {
  97249. _this._onPointerUp(evt);
  97250. };
  97251. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  97252. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  97253. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  97254. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  97255. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  97256. evt.preventDefault(); // Disables system menu
  97257. }, false);
  97258. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  97259. }
  97260. /**
  97261. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  97262. * @param newJoystickSensibility defines the new sensibility
  97263. */
  97264. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  97265. this._joystickSensibility = newJoystickSensibility;
  97266. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  97267. };
  97268. VirtualJoystick.prototype._onPointerDown = function (e) {
  97269. var positionOnScreenCondition;
  97270. e.preventDefault();
  97271. if (this._leftJoystick === true) {
  97272. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  97273. }
  97274. else {
  97275. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  97276. }
  97277. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  97278. // First contact will be dedicated to the virtual joystick
  97279. this._joystickPointerID = e.pointerId;
  97280. this._joystickPointerStartPos.x = e.clientX;
  97281. this._joystickPointerStartPos.y = e.clientY;
  97282. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  97283. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  97284. this._deltaJoystickVector.x = 0;
  97285. this._deltaJoystickVector.y = 0;
  97286. this.pressed = true;
  97287. this._touches.add(e.pointerId.toString(), e);
  97288. }
  97289. else {
  97290. // You can only trigger the action buttons with a joystick declared
  97291. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  97292. this._action();
  97293. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  97294. }
  97295. }
  97296. };
  97297. VirtualJoystick.prototype._onPointerMove = function (e) {
  97298. // If the current pointer is the one associated to the joystick (first touch contact)
  97299. if (this._joystickPointerID == e.pointerId) {
  97300. this._joystickPointerPos.x = e.clientX;
  97301. this._joystickPointerPos.y = e.clientY;
  97302. this._deltaJoystickVector = this._joystickPointerPos.clone();
  97303. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  97304. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  97305. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  97306. switch (this._axisTargetedByLeftAndRight) {
  97307. case JoystickAxis.X:
  97308. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  97309. break;
  97310. case JoystickAxis.Y:
  97311. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  97312. break;
  97313. case JoystickAxis.Z:
  97314. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  97315. break;
  97316. }
  97317. var directionUpDown = this.reverseUpDown ? 1 : -1;
  97318. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  97319. switch (this._axisTargetedByUpAndDown) {
  97320. case JoystickAxis.X:
  97321. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  97322. break;
  97323. case JoystickAxis.Y:
  97324. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  97325. break;
  97326. case JoystickAxis.Z:
  97327. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  97328. break;
  97329. }
  97330. }
  97331. else {
  97332. var data = this._touches.get(e.pointerId.toString());
  97333. if (data) {
  97334. data.x = e.clientX;
  97335. data.y = e.clientY;
  97336. }
  97337. }
  97338. };
  97339. VirtualJoystick.prototype._onPointerUp = function (e) {
  97340. if (this._joystickPointerID == e.pointerId) {
  97341. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  97342. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  97343. this._joystickPointerID = -1;
  97344. this.pressed = false;
  97345. }
  97346. else {
  97347. var touch = this._touches.get(e.pointerId.toString());
  97348. if (touch) {
  97349. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  97350. }
  97351. }
  97352. this._deltaJoystickVector.x = 0;
  97353. this._deltaJoystickVector.y = 0;
  97354. this._touches.remove(e.pointerId.toString());
  97355. };
  97356. /**
  97357. * Change the color of the virtual joystick
  97358. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  97359. */
  97360. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  97361. this._joystickColor = newColor;
  97362. };
  97363. /**
  97364. * Defines a callback to call when the joystick is touched
  97365. * @param action defines the callback
  97366. */
  97367. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  97368. this._action = action;
  97369. };
  97370. /**
  97371. * Defines which axis you'd like to control for left & right
  97372. * @param axis defines the axis to use
  97373. */
  97374. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  97375. switch (axis) {
  97376. case JoystickAxis.X:
  97377. case JoystickAxis.Y:
  97378. case JoystickAxis.Z:
  97379. this._axisTargetedByLeftAndRight = axis;
  97380. break;
  97381. default:
  97382. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  97383. break;
  97384. }
  97385. };
  97386. /**
  97387. * Defines which axis you'd like to control for up & down
  97388. * @param axis defines the axis to use
  97389. */
  97390. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  97391. switch (axis) {
  97392. case JoystickAxis.X:
  97393. case JoystickAxis.Y:
  97394. case JoystickAxis.Z:
  97395. this._axisTargetedByUpAndDown = axis;
  97396. break;
  97397. default:
  97398. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  97399. break;
  97400. }
  97401. };
  97402. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  97403. var _this = this;
  97404. if (this.pressed) {
  97405. this._touches.forEach(function (key, touch) {
  97406. if (touch.pointerId === _this._joystickPointerID) {
  97407. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  97408. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  97409. VirtualJoystick.vjCanvasContext.beginPath();
  97410. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  97411. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97412. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  97413. VirtualJoystick.vjCanvasContext.stroke();
  97414. VirtualJoystick.vjCanvasContext.closePath();
  97415. VirtualJoystick.vjCanvasContext.beginPath();
  97416. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97417. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  97418. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  97419. VirtualJoystick.vjCanvasContext.stroke();
  97420. VirtualJoystick.vjCanvasContext.closePath();
  97421. VirtualJoystick.vjCanvasContext.beginPath();
  97422. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97423. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  97424. VirtualJoystick.vjCanvasContext.stroke();
  97425. VirtualJoystick.vjCanvasContext.closePath();
  97426. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  97427. }
  97428. else {
  97429. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  97430. VirtualJoystick.vjCanvasContext.beginPath();
  97431. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  97432. VirtualJoystick.vjCanvasContext.beginPath();
  97433. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  97434. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  97435. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  97436. VirtualJoystick.vjCanvasContext.stroke();
  97437. VirtualJoystick.vjCanvasContext.closePath();
  97438. touch.prevX = touch.x;
  97439. touch.prevY = touch.y;
  97440. }
  97441. ;
  97442. });
  97443. }
  97444. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  97445. };
  97446. /**
  97447. * Release internal HTML canvas
  97448. */
  97449. VirtualJoystick.prototype.releaseCanvas = function () {
  97450. if (VirtualJoystick.vjCanvas) {
  97451. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  97452. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  97453. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  97454. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  97455. window.removeEventListener("resize", this._onResize);
  97456. document.body.removeChild(VirtualJoystick.vjCanvas);
  97457. VirtualJoystick.vjCanvas = null;
  97458. }
  97459. };
  97460. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  97461. VirtualJoystick._globalJoystickIndex = 0;
  97462. return VirtualJoystick;
  97463. }());
  97464. BABYLON.VirtualJoystick = VirtualJoystick;
  97465. })(BABYLON || (BABYLON = {}));
  97466. //# sourceMappingURL=babylon.virtualJoystick.js.map
  97467. var BABYLON;
  97468. (function (BABYLON) {
  97469. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  97470. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  97471. });
  97472. // We're mainly based on the logic defined into the FreeCamera code
  97473. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  97474. __extends(VirtualJoysticksCamera, _super);
  97475. function VirtualJoysticksCamera(name, position, scene) {
  97476. var _this = _super.call(this, name, position, scene) || this;
  97477. _this.inputs.addVirtualJoystick();
  97478. return _this;
  97479. }
  97480. VirtualJoysticksCamera.prototype.getClassName = function () {
  97481. return "VirtualJoysticksCamera";
  97482. };
  97483. return VirtualJoysticksCamera;
  97484. }(BABYLON.FreeCamera));
  97485. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  97486. })(BABYLON || (BABYLON = {}));
  97487. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  97488. var BABYLON;
  97489. (function (BABYLON) {
  97490. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  97491. function FreeCameraVirtualJoystickInput() {
  97492. }
  97493. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  97494. return this._leftjoystick;
  97495. };
  97496. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  97497. return this._rightjoystick;
  97498. };
  97499. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  97500. if (this._leftjoystick) {
  97501. var camera = this.camera;
  97502. var speed = camera._computeLocalCameraSpeed() * 50;
  97503. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  97504. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  97505. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  97506. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  97507. if (!this._leftjoystick.pressed) {
  97508. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  97509. }
  97510. if (!this._rightjoystick.pressed) {
  97511. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  97512. }
  97513. }
  97514. };
  97515. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  97516. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  97517. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  97518. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  97519. this._leftjoystick.setJoystickSensibility(0.15);
  97520. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  97521. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  97522. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  97523. this._rightjoystick.reverseUpDown = true;
  97524. this._rightjoystick.setJoystickSensibility(0.05);
  97525. this._rightjoystick.setJoystickColor("yellow");
  97526. };
  97527. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  97528. this._leftjoystick.releaseCanvas();
  97529. this._rightjoystick.releaseCanvas();
  97530. };
  97531. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  97532. return "FreeCameraVirtualJoystickInput";
  97533. };
  97534. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  97535. return "virtualJoystick";
  97536. };
  97537. return FreeCameraVirtualJoystickInput;
  97538. }());
  97539. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  97540. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  97541. })(BABYLON || (BABYLON = {}));
  97542. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  97543. var BABYLON;
  97544. (function (BABYLON) {
  97545. var SimplificationSettings = /** @class */ (function () {
  97546. function SimplificationSettings(quality, distance, optimizeMesh) {
  97547. this.quality = quality;
  97548. this.distance = distance;
  97549. this.optimizeMesh = optimizeMesh;
  97550. }
  97551. return SimplificationSettings;
  97552. }());
  97553. BABYLON.SimplificationSettings = SimplificationSettings;
  97554. var SimplificationQueue = /** @class */ (function () {
  97555. function SimplificationQueue() {
  97556. this.running = false;
  97557. this._simplificationArray = [];
  97558. }
  97559. SimplificationQueue.prototype.addTask = function (task) {
  97560. this._simplificationArray.push(task);
  97561. };
  97562. SimplificationQueue.prototype.executeNext = function () {
  97563. var task = this._simplificationArray.pop();
  97564. if (task) {
  97565. this.running = true;
  97566. this.runSimplification(task);
  97567. }
  97568. else {
  97569. this.running = false;
  97570. }
  97571. };
  97572. SimplificationQueue.prototype.runSimplification = function (task) {
  97573. var _this = this;
  97574. if (task.parallelProcessing) {
  97575. //parallel simplifier
  97576. task.settings.forEach(function (setting) {
  97577. var simplifier = _this.getSimplifier(task);
  97578. simplifier.simplify(setting, function (newMesh) {
  97579. task.mesh.addLODLevel(setting.distance, newMesh);
  97580. newMesh.isVisible = true;
  97581. //check if it is the last
  97582. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  97583. //all done, run the success callback.
  97584. task.successCallback();
  97585. }
  97586. _this.executeNext();
  97587. });
  97588. });
  97589. }
  97590. else {
  97591. //single simplifier.
  97592. var simplifier = this.getSimplifier(task);
  97593. var runDecimation = function (setting, callback) {
  97594. simplifier.simplify(setting, function (newMesh) {
  97595. task.mesh.addLODLevel(setting.distance, newMesh);
  97596. newMesh.isVisible = true;
  97597. //run the next quality level
  97598. callback();
  97599. });
  97600. };
  97601. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  97602. runDecimation(task.settings[loop.index], function () {
  97603. loop.executeNext();
  97604. });
  97605. }, function () {
  97606. //execution ended, run the success callback.
  97607. if (task.successCallback) {
  97608. task.successCallback();
  97609. }
  97610. _this.executeNext();
  97611. });
  97612. }
  97613. };
  97614. SimplificationQueue.prototype.getSimplifier = function (task) {
  97615. switch (task.simplificationType) {
  97616. case SimplificationType.QUADRATIC:
  97617. default:
  97618. return new QuadraticErrorSimplification(task.mesh);
  97619. }
  97620. };
  97621. return SimplificationQueue;
  97622. }());
  97623. BABYLON.SimplificationQueue = SimplificationQueue;
  97624. /**
  97625. * The implemented types of simplification
  97626. * At the moment only Quadratic Error Decimation is implemented
  97627. */
  97628. var SimplificationType;
  97629. (function (SimplificationType) {
  97630. /** Quadratic error decimation */
  97631. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  97632. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  97633. var DecimationTriangle = /** @class */ (function () {
  97634. function DecimationTriangle(vertices) {
  97635. this.vertices = vertices;
  97636. this.error = new Array(4);
  97637. this.deleted = false;
  97638. this.isDirty = false;
  97639. this.deletePending = false;
  97640. this.borderFactor = 0;
  97641. }
  97642. return DecimationTriangle;
  97643. }());
  97644. BABYLON.DecimationTriangle = DecimationTriangle;
  97645. var DecimationVertex = /** @class */ (function () {
  97646. function DecimationVertex(position, id) {
  97647. this.position = position;
  97648. this.id = id;
  97649. this.isBorder = true;
  97650. this.q = new QuadraticMatrix();
  97651. this.triangleCount = 0;
  97652. this.triangleStart = 0;
  97653. this.originalOffsets = [];
  97654. }
  97655. DecimationVertex.prototype.updatePosition = function (newPosition) {
  97656. this.position.copyFrom(newPosition);
  97657. };
  97658. return DecimationVertex;
  97659. }());
  97660. BABYLON.DecimationVertex = DecimationVertex;
  97661. var QuadraticMatrix = /** @class */ (function () {
  97662. function QuadraticMatrix(data) {
  97663. this.data = new Array(10);
  97664. for (var i = 0; i < 10; ++i) {
  97665. if (data && data[i]) {
  97666. this.data[i] = data[i];
  97667. }
  97668. else {
  97669. this.data[i] = 0;
  97670. }
  97671. }
  97672. }
  97673. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  97674. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  97675. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  97676. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  97677. return det;
  97678. };
  97679. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  97680. for (var i = 0; i < 10; ++i) {
  97681. this.data[i] += matrix.data[i];
  97682. }
  97683. };
  97684. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  97685. for (var i = 0; i < 10; ++i) {
  97686. this.data[i] += data[i];
  97687. }
  97688. };
  97689. QuadraticMatrix.prototype.add = function (matrix) {
  97690. var m = new QuadraticMatrix();
  97691. for (var i = 0; i < 10; ++i) {
  97692. m.data[i] = this.data[i] + matrix.data[i];
  97693. }
  97694. return m;
  97695. };
  97696. QuadraticMatrix.FromData = function (a, b, c, d) {
  97697. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  97698. };
  97699. //returning an array to avoid garbage collection
  97700. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  97701. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  97702. };
  97703. return QuadraticMatrix;
  97704. }());
  97705. BABYLON.QuadraticMatrix = QuadraticMatrix;
  97706. var Reference = /** @class */ (function () {
  97707. function Reference(vertexId, triangleId) {
  97708. this.vertexId = vertexId;
  97709. this.triangleId = triangleId;
  97710. }
  97711. return Reference;
  97712. }());
  97713. BABYLON.Reference = Reference;
  97714. /**
  97715. * An implementation of the Quadratic Error simplification algorithm.
  97716. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  97717. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  97718. * @author RaananW
  97719. */
  97720. var QuadraticErrorSimplification = /** @class */ (function () {
  97721. function QuadraticErrorSimplification(_mesh) {
  97722. this._mesh = _mesh;
  97723. this.syncIterations = 5000;
  97724. this.aggressiveness = 7;
  97725. this.decimationIterations = 100;
  97726. this.boundingBoxEpsilon = BABYLON.Epsilon;
  97727. }
  97728. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  97729. var _this = this;
  97730. this.initDecimatedMesh();
  97731. //iterating through the submeshes array, one after the other.
  97732. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  97733. _this.initWithMesh(loop.index, function () {
  97734. _this.runDecimation(settings, loop.index, function () {
  97735. loop.executeNext();
  97736. });
  97737. }, settings.optimizeMesh);
  97738. }, function () {
  97739. setTimeout(function () {
  97740. successCallback(_this._reconstructedMesh);
  97741. }, 0);
  97742. });
  97743. };
  97744. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  97745. var _this = this;
  97746. var targetCount = ~~(this.triangles.length * settings.quality);
  97747. var deletedTriangles = 0;
  97748. var triangleCount = this.triangles.length;
  97749. var iterationFunction = function (iteration, callback) {
  97750. setTimeout(function () {
  97751. if (iteration % 5 === 0) {
  97752. _this.updateMesh(iteration === 0);
  97753. }
  97754. for (var i = 0; i < _this.triangles.length; ++i) {
  97755. _this.triangles[i].isDirty = false;
  97756. }
  97757. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  97758. var trianglesIterator = function (i) {
  97759. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  97760. var t = _this.triangles[tIdx];
  97761. if (!t)
  97762. return;
  97763. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  97764. return;
  97765. }
  97766. for (var j = 0; j < 3; ++j) {
  97767. if (t.error[j] < threshold) {
  97768. var deleted0 = [];
  97769. var deleted1 = [];
  97770. var v0 = t.vertices[j];
  97771. var v1 = t.vertices[(j + 1) % 3];
  97772. if (v0.isBorder || v1.isBorder)
  97773. continue;
  97774. var p = BABYLON.Vector3.Zero();
  97775. var n = BABYLON.Vector3.Zero();
  97776. var uv = BABYLON.Vector2.Zero();
  97777. var color = new BABYLON.Color4(0, 0, 0, 1);
  97778. _this.calculateError(v0, v1, p, n, uv, color);
  97779. var delTr = new Array();
  97780. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  97781. continue;
  97782. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  97783. continue;
  97784. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  97785. continue;
  97786. var uniqueArray = new Array();
  97787. delTr.forEach(function (deletedT) {
  97788. if (uniqueArray.indexOf(deletedT) === -1) {
  97789. deletedT.deletePending = true;
  97790. uniqueArray.push(deletedT);
  97791. }
  97792. });
  97793. if (uniqueArray.length % 2 !== 0) {
  97794. continue;
  97795. }
  97796. v0.q = v1.q.add(v0.q);
  97797. v0.updatePosition(p);
  97798. var tStart = _this.references.length;
  97799. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  97800. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  97801. var tCount = _this.references.length - tStart;
  97802. if (tCount <= v0.triangleCount) {
  97803. if (tCount) {
  97804. for (var c = 0; c < tCount; c++) {
  97805. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  97806. }
  97807. }
  97808. }
  97809. else {
  97810. v0.triangleStart = tStart;
  97811. }
  97812. v0.triangleCount = tCount;
  97813. break;
  97814. }
  97815. }
  97816. };
  97817. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  97818. }, 0);
  97819. };
  97820. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  97821. if (triangleCount - deletedTriangles <= targetCount)
  97822. loop.breakLoop();
  97823. else {
  97824. iterationFunction(loop.index, function () {
  97825. loop.executeNext();
  97826. });
  97827. }
  97828. }, function () {
  97829. setTimeout(function () {
  97830. //reconstruct this part of the mesh
  97831. _this.reconstructMesh(submeshIndex);
  97832. successCallback();
  97833. }, 0);
  97834. });
  97835. };
  97836. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  97837. var _this = this;
  97838. this.vertices = [];
  97839. this.triangles = [];
  97840. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  97841. var indices = this._mesh.getIndices();
  97842. var submesh = this._mesh.subMeshes[submeshIndex];
  97843. var findInVertices = function (positionToSearch) {
  97844. if (optimizeMesh) {
  97845. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  97846. if (_this.vertices[ii].position.equals(positionToSearch)) {
  97847. return _this.vertices[ii];
  97848. }
  97849. }
  97850. }
  97851. return null;
  97852. };
  97853. var vertexReferences = [];
  97854. var vertexInit = function (i) {
  97855. if (!positionData) {
  97856. return;
  97857. }
  97858. var offset = i + submesh.verticesStart;
  97859. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  97860. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  97861. vertex.originalOffsets.push(offset);
  97862. if (vertex.id === _this.vertices.length) {
  97863. _this.vertices.push(vertex);
  97864. }
  97865. vertexReferences.push(vertex.id);
  97866. };
  97867. //var totalVertices = mesh.getTotalVertices();
  97868. var totalVertices = submesh.verticesCount;
  97869. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  97870. var indicesInit = function (i) {
  97871. if (!indices) {
  97872. return;
  97873. }
  97874. var offset = (submesh.indexStart / 3) + i;
  97875. var pos = (offset * 3);
  97876. var i0 = indices[pos + 0];
  97877. var i1 = indices[pos + 1];
  97878. var i2 = indices[pos + 2];
  97879. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  97880. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  97881. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  97882. var triangle = new DecimationTriangle([v0, v1, v2]);
  97883. triangle.originalOffset = pos;
  97884. _this.triangles.push(triangle);
  97885. };
  97886. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  97887. _this.init(callback);
  97888. });
  97889. });
  97890. };
  97891. QuadraticErrorSimplification.prototype.init = function (callback) {
  97892. var _this = this;
  97893. var triangleInit1 = function (i) {
  97894. var t = _this.triangles[i];
  97895. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  97896. for (var j = 0; j < 3; j++) {
  97897. 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))));
  97898. }
  97899. };
  97900. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  97901. var triangleInit2 = function (i) {
  97902. var t = _this.triangles[i];
  97903. for (var j = 0; j < 3; ++j) {
  97904. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  97905. }
  97906. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  97907. };
  97908. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  97909. callback();
  97910. });
  97911. });
  97912. };
  97913. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  97914. var newTriangles = [];
  97915. var i;
  97916. for (i = 0; i < this.vertices.length; ++i) {
  97917. this.vertices[i].triangleCount = 0;
  97918. }
  97919. var t;
  97920. var j;
  97921. for (i = 0; i < this.triangles.length; ++i) {
  97922. if (!this.triangles[i].deleted) {
  97923. t = this.triangles[i];
  97924. for (j = 0; j < 3; ++j) {
  97925. t.vertices[j].triangleCount = 1;
  97926. }
  97927. newTriangles.push(t);
  97928. }
  97929. }
  97930. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  97931. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  97932. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  97933. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  97934. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  97935. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  97936. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  97937. var vertexCount = 0;
  97938. for (i = 0; i < this.vertices.length; ++i) {
  97939. var vertex = this.vertices[i];
  97940. vertex.id = vertexCount;
  97941. if (vertex.triangleCount) {
  97942. vertex.originalOffsets.forEach(function (originalOffset) {
  97943. if (!normalData) {
  97944. return;
  97945. }
  97946. newPositionData.push(vertex.position.x);
  97947. newPositionData.push(vertex.position.y);
  97948. newPositionData.push(vertex.position.z);
  97949. newNormalData.push(normalData[originalOffset * 3]);
  97950. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  97951. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  97952. if (uvs && uvs.length) {
  97953. newUVsData.push(uvs[(originalOffset * 2)]);
  97954. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  97955. }
  97956. else if (colorsData && colorsData.length) {
  97957. newColorsData.push(colorsData[(originalOffset * 4)]);
  97958. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  97959. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  97960. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  97961. }
  97962. ++vertexCount;
  97963. });
  97964. }
  97965. }
  97966. var startingIndex = this._reconstructedMesh.getTotalIndices();
  97967. var startingVertex = this._reconstructedMesh.getTotalVertices();
  97968. var submeshesArray = this._reconstructedMesh.subMeshes;
  97969. this._reconstructedMesh.subMeshes = [];
  97970. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  97971. var originalIndices = this._mesh.getIndices();
  97972. for (i = 0; i < newTriangles.length; ++i) {
  97973. t = newTriangles[i]; //now get the new referencing point for each vertex
  97974. [0, 1, 2].forEach(function (idx) {
  97975. var id = originalIndices[t.originalOffset + idx];
  97976. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  97977. if (offset < 0)
  97978. offset = 0;
  97979. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  97980. });
  97981. }
  97982. //overwriting the old vertex buffers and indices.
  97983. this._reconstructedMesh.setIndices(newIndicesArray);
  97984. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  97985. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  97986. if (newUVsData.length > 0)
  97987. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  97988. if (newColorsData.length > 0)
  97989. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  97990. //create submesh
  97991. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  97992. if (submeshIndex > 0) {
  97993. this._reconstructedMesh.subMeshes = [];
  97994. submeshesArray.forEach(function (submesh) {
  97995. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  97996. });
  97997. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  97998. }
  97999. };
  98000. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  98001. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  98002. this._reconstructedMesh.material = this._mesh.material;
  98003. this._reconstructedMesh.parent = this._mesh.parent;
  98004. this._reconstructedMesh.isVisible = false;
  98005. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  98006. };
  98007. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  98008. for (var i = 0; i < vertex1.triangleCount; ++i) {
  98009. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  98010. if (t.deleted)
  98011. continue;
  98012. var s = this.references[vertex1.triangleStart + i].vertexId;
  98013. var v1 = t.vertices[(s + 1) % 3];
  98014. var v2 = t.vertices[(s + 2) % 3];
  98015. if ((v1 === vertex2 || v2 === vertex2)) {
  98016. deletedArray[i] = true;
  98017. delTr.push(t);
  98018. continue;
  98019. }
  98020. var d1 = v1.position.subtract(point);
  98021. d1 = d1.normalize();
  98022. var d2 = v2.position.subtract(point);
  98023. d2 = d2.normalize();
  98024. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  98025. return true;
  98026. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  98027. deletedArray[i] = false;
  98028. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  98029. return true;
  98030. }
  98031. return false;
  98032. };
  98033. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  98034. var newDeleted = deletedTriangles;
  98035. for (var i = 0; i < vertex.triangleCount; ++i) {
  98036. var ref = this.references[vertex.triangleStart + i];
  98037. var t = this.triangles[ref.triangleId];
  98038. if (t.deleted)
  98039. continue;
  98040. if (deletedArray[i] && t.deletePending) {
  98041. t.deleted = true;
  98042. newDeleted++;
  98043. continue;
  98044. }
  98045. t.vertices[ref.vertexId] = origVertex;
  98046. t.isDirty = true;
  98047. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  98048. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  98049. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  98050. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  98051. this.references.push(ref);
  98052. }
  98053. return newDeleted;
  98054. };
  98055. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  98056. for (var i = 0; i < this.vertices.length; ++i) {
  98057. var vCount = [];
  98058. var vId = [];
  98059. var v = this.vertices[i];
  98060. var j;
  98061. for (j = 0; j < v.triangleCount; ++j) {
  98062. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  98063. for (var ii = 0; ii < 3; ii++) {
  98064. var ofs = 0;
  98065. var vv = triangle.vertices[ii];
  98066. while (ofs < vCount.length) {
  98067. if (vId[ofs] === vv.id)
  98068. break;
  98069. ++ofs;
  98070. }
  98071. if (ofs === vCount.length) {
  98072. vCount.push(1);
  98073. vId.push(vv.id);
  98074. }
  98075. else {
  98076. vCount[ofs]++;
  98077. }
  98078. }
  98079. }
  98080. for (j = 0; j < vCount.length; ++j) {
  98081. if (vCount[j] === 1) {
  98082. this.vertices[vId[j]].isBorder = true;
  98083. }
  98084. else {
  98085. this.vertices[vId[j]].isBorder = false;
  98086. }
  98087. }
  98088. }
  98089. };
  98090. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  98091. if (identifyBorders === void 0) { identifyBorders = false; }
  98092. var i;
  98093. if (!identifyBorders) {
  98094. var newTrianglesVector = [];
  98095. for (i = 0; i < this.triangles.length; ++i) {
  98096. if (!this.triangles[i].deleted) {
  98097. newTrianglesVector.push(this.triangles[i]);
  98098. }
  98099. }
  98100. this.triangles = newTrianglesVector;
  98101. }
  98102. for (i = 0; i < this.vertices.length; ++i) {
  98103. this.vertices[i].triangleCount = 0;
  98104. this.vertices[i].triangleStart = 0;
  98105. }
  98106. var t;
  98107. var j;
  98108. var v;
  98109. for (i = 0; i < this.triangles.length; ++i) {
  98110. t = this.triangles[i];
  98111. for (j = 0; j < 3; ++j) {
  98112. v = t.vertices[j];
  98113. v.triangleCount++;
  98114. }
  98115. }
  98116. var tStart = 0;
  98117. for (i = 0; i < this.vertices.length; ++i) {
  98118. this.vertices[i].triangleStart = tStart;
  98119. tStart += this.vertices[i].triangleCount;
  98120. this.vertices[i].triangleCount = 0;
  98121. }
  98122. var newReferences = new Array(this.triangles.length * 3);
  98123. for (i = 0; i < this.triangles.length; ++i) {
  98124. t = this.triangles[i];
  98125. for (j = 0; j < 3; ++j) {
  98126. v = t.vertices[j];
  98127. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  98128. v.triangleCount++;
  98129. }
  98130. }
  98131. this.references = newReferences;
  98132. if (identifyBorders) {
  98133. this.identifyBorder();
  98134. }
  98135. };
  98136. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  98137. var x = point.x;
  98138. var y = point.y;
  98139. var z = point.z;
  98140. 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
  98141. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  98142. };
  98143. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  98144. var q = vertex1.q.add(vertex2.q);
  98145. var border = vertex1.isBorder && vertex2.isBorder;
  98146. var error = 0;
  98147. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  98148. if (qDet !== 0 && !border) {
  98149. if (!pointResult) {
  98150. pointResult = BABYLON.Vector3.Zero();
  98151. }
  98152. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  98153. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  98154. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  98155. error = this.vertexError(q, pointResult);
  98156. }
  98157. else {
  98158. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  98159. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  98160. var error1 = this.vertexError(q, vertex1.position);
  98161. var error2 = this.vertexError(q, vertex2.position);
  98162. var error3 = this.vertexError(q, p3);
  98163. error = Math.min(error1, error2, error3);
  98164. if (error === error1) {
  98165. if (pointResult) {
  98166. pointResult.copyFrom(vertex1.position);
  98167. }
  98168. }
  98169. else if (error === error2) {
  98170. if (pointResult) {
  98171. pointResult.copyFrom(vertex2.position);
  98172. }
  98173. }
  98174. else {
  98175. if (pointResult) {
  98176. pointResult.copyFrom(p3);
  98177. }
  98178. }
  98179. }
  98180. return error;
  98181. };
  98182. return QuadraticErrorSimplification;
  98183. }());
  98184. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  98185. })(BABYLON || (BABYLON = {}));
  98186. //# sourceMappingURL=babylon.meshSimplification.js.map
  98187. var BABYLON;
  98188. (function (BABYLON) {
  98189. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  98190. get: function () {
  98191. if (!this._simplificationQueue) {
  98192. this._simplificationQueue = new BABYLON.SimplificationQueue();
  98193. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  98194. if (!component) {
  98195. component = new SimplicationQueueSceneComponent(this);
  98196. this._addComponent(component);
  98197. }
  98198. }
  98199. return this._simplificationQueue;
  98200. },
  98201. set: function (value) {
  98202. this._simplificationQueue = value;
  98203. },
  98204. enumerable: true,
  98205. configurable: true
  98206. });
  98207. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  98208. if (parallelProcessing === void 0) { parallelProcessing = true; }
  98209. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  98210. this.getScene().simplificationQueue.addTask({
  98211. settings: settings,
  98212. parallelProcessing: parallelProcessing,
  98213. mesh: this,
  98214. simplificationType: simplificationType,
  98215. successCallback: successCallback
  98216. });
  98217. return this;
  98218. };
  98219. /**
  98220. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  98221. * created in a scene
  98222. */
  98223. var SimplicationQueueSceneComponent = /** @class */ (function () {
  98224. /**
  98225. * Creates a new instance of the component for the given scene
  98226. * @param scene Defines the scene to register the component in
  98227. */
  98228. function SimplicationQueueSceneComponent(scene) {
  98229. /**
  98230. * The component name helpfull to identify the component in the list of scene components.
  98231. */
  98232. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  98233. this.scene = scene;
  98234. }
  98235. /**
  98236. * Registers the component in a given scene
  98237. */
  98238. SimplicationQueueSceneComponent.prototype.register = function () {
  98239. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  98240. };
  98241. /**
  98242. * Rebuilds the elements related to this component in case of
  98243. * context lost for instance.
  98244. */
  98245. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  98246. // Nothing to do for this component
  98247. };
  98248. /**
  98249. * Disposes the component and the associated ressources
  98250. */
  98251. SimplicationQueueSceneComponent.prototype.dispose = function () {
  98252. // Nothing to do for this component
  98253. };
  98254. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  98255. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  98256. this.scene._simplificationQueue.executeNext();
  98257. }
  98258. };
  98259. return SimplicationQueueSceneComponent;
  98260. }());
  98261. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  98262. })(BABYLON || (BABYLON = {}));
  98263. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  98264. var BABYLON;
  98265. (function (BABYLON) {
  98266. var MeshLODLevel = /** @class */ (function () {
  98267. function MeshLODLevel(distance, mesh) {
  98268. this.distance = distance;
  98269. this.mesh = mesh;
  98270. }
  98271. return MeshLODLevel;
  98272. }());
  98273. BABYLON.MeshLODLevel = MeshLODLevel;
  98274. })(BABYLON || (BABYLON = {}));
  98275. //# sourceMappingURL=babylon.meshLODLevel.js.map
  98276. var BABYLON;
  98277. (function (BABYLON) {
  98278. /**
  98279. * Defines the root class used to create scene optimization to use with SceneOptimizer
  98280. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98281. */
  98282. var SceneOptimization = /** @class */ (function () {
  98283. /**
  98284. * Creates the SceneOptimization object
  98285. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98286. * @param desc defines the description associated with the optimization
  98287. */
  98288. function SceneOptimization(
  98289. /**
  98290. * Defines the priority of this optimization (0 by default which means first in the list)
  98291. */
  98292. priority) {
  98293. if (priority === void 0) { priority = 0; }
  98294. this.priority = priority;
  98295. }
  98296. /**
  98297. * Gets a string describing the action executed by the current optimization
  98298. * @returns description string
  98299. */
  98300. SceneOptimization.prototype.getDescription = function () {
  98301. return "";
  98302. };
  98303. /**
  98304. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98305. * @param scene defines the current scene where to apply this optimization
  98306. * @param optimizer defines the current optimizer
  98307. * @returns true if everything that can be done was applied
  98308. */
  98309. SceneOptimization.prototype.apply = function (scene, optimizer) {
  98310. return true;
  98311. };
  98312. ;
  98313. return SceneOptimization;
  98314. }());
  98315. BABYLON.SceneOptimization = SceneOptimization;
  98316. /**
  98317. * Defines an optimization used to reduce the size of render target textures
  98318. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98319. */
  98320. var TextureOptimization = /** @class */ (function (_super) {
  98321. __extends(TextureOptimization, _super);
  98322. /**
  98323. * Creates the TextureOptimization object
  98324. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98325. * @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
  98326. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  98327. */
  98328. function TextureOptimization(
  98329. /**
  98330. * Defines the priority of this optimization (0 by default which means first in the list)
  98331. */
  98332. priority,
  98333. /**
  98334. * 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
  98335. */
  98336. maximumSize,
  98337. /**
  98338. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  98339. */
  98340. step) {
  98341. if (priority === void 0) { priority = 0; }
  98342. if (maximumSize === void 0) { maximumSize = 1024; }
  98343. if (step === void 0) { step = 0.5; }
  98344. var _this = _super.call(this, priority) || this;
  98345. _this.priority = priority;
  98346. _this.maximumSize = maximumSize;
  98347. _this.step = step;
  98348. return _this;
  98349. }
  98350. /**
  98351. * Gets a string describing the action executed by the current optimization
  98352. * @returns description string
  98353. */
  98354. TextureOptimization.prototype.getDescription = function () {
  98355. return "Reducing render target texture size to " + this.maximumSize;
  98356. };
  98357. /**
  98358. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98359. * @param scene defines the current scene where to apply this optimization
  98360. * @param optimizer defines the current optimizer
  98361. * @returns true if everything that can be done was applied
  98362. */
  98363. TextureOptimization.prototype.apply = function (scene, optimizer) {
  98364. var allDone = true;
  98365. for (var index = 0; index < scene.textures.length; index++) {
  98366. var texture = scene.textures[index];
  98367. if (!texture.canRescale || texture.getContext) {
  98368. continue;
  98369. }
  98370. var currentSize = texture.getSize();
  98371. var maxDimension = Math.max(currentSize.width, currentSize.height);
  98372. if (maxDimension > this.maximumSize) {
  98373. texture.scale(this.step);
  98374. allDone = false;
  98375. }
  98376. }
  98377. return allDone;
  98378. };
  98379. return TextureOptimization;
  98380. }(SceneOptimization));
  98381. BABYLON.TextureOptimization = TextureOptimization;
  98382. /**
  98383. * Defines an optimization used to increase or decrease the rendering resolution
  98384. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98385. */
  98386. var HardwareScalingOptimization = /** @class */ (function (_super) {
  98387. __extends(HardwareScalingOptimization, _super);
  98388. /**
  98389. * Creates the HardwareScalingOptimization object
  98390. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98391. * @param maximumScale defines the maximum scale to use (2 by default)
  98392. * @param step defines the step to use between two passes (0.5 by default)
  98393. */
  98394. function HardwareScalingOptimization(
  98395. /**
  98396. * Defines the priority of this optimization (0 by default which means first in the list)
  98397. */
  98398. priority,
  98399. /**
  98400. * Defines the maximum scale to use (2 by default)
  98401. */
  98402. maximumScale,
  98403. /**
  98404. * Defines the step to use between two passes (0.5 by default)
  98405. */
  98406. step) {
  98407. if (priority === void 0) { priority = 0; }
  98408. if (maximumScale === void 0) { maximumScale = 2; }
  98409. if (step === void 0) { step = 0.25; }
  98410. var _this = _super.call(this, priority) || this;
  98411. _this.priority = priority;
  98412. _this.maximumScale = maximumScale;
  98413. _this.step = step;
  98414. _this._currentScale = -1;
  98415. _this._directionOffset = 1;
  98416. return _this;
  98417. }
  98418. /**
  98419. * Gets a string describing the action executed by the current optimization
  98420. * @return description string
  98421. */
  98422. HardwareScalingOptimization.prototype.getDescription = function () {
  98423. return "Setting hardware scaling level to " + this._currentScale;
  98424. };
  98425. /**
  98426. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98427. * @param scene defines the current scene where to apply this optimization
  98428. * @param optimizer defines the current optimizer
  98429. * @returns true if everything that can be done was applied
  98430. */
  98431. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  98432. if (this._currentScale === -1) {
  98433. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  98434. if (this._currentScale > this.maximumScale) {
  98435. this._directionOffset = -1;
  98436. }
  98437. }
  98438. this._currentScale += this._directionOffset * this.step;
  98439. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  98440. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  98441. };
  98442. ;
  98443. return HardwareScalingOptimization;
  98444. }(SceneOptimization));
  98445. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  98446. /**
  98447. * Defines an optimization used to remove shadows
  98448. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98449. */
  98450. var ShadowsOptimization = /** @class */ (function (_super) {
  98451. __extends(ShadowsOptimization, _super);
  98452. function ShadowsOptimization() {
  98453. return _super !== null && _super.apply(this, arguments) || this;
  98454. }
  98455. /**
  98456. * Gets a string describing the action executed by the current optimization
  98457. * @return description string
  98458. */
  98459. ShadowsOptimization.prototype.getDescription = function () {
  98460. return "Turning shadows on/off";
  98461. };
  98462. /**
  98463. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98464. * @param scene defines the current scene where to apply this optimization
  98465. * @param optimizer defines the current optimizer
  98466. * @returns true if everything that can be done was applied
  98467. */
  98468. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  98469. scene.shadowsEnabled = optimizer.isInImprovementMode;
  98470. return true;
  98471. };
  98472. ;
  98473. return ShadowsOptimization;
  98474. }(SceneOptimization));
  98475. BABYLON.ShadowsOptimization = ShadowsOptimization;
  98476. /**
  98477. * Defines an optimization used to turn post-processes off
  98478. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98479. */
  98480. var PostProcessesOptimization = /** @class */ (function (_super) {
  98481. __extends(PostProcessesOptimization, _super);
  98482. function PostProcessesOptimization() {
  98483. return _super !== null && _super.apply(this, arguments) || this;
  98484. }
  98485. /**
  98486. * Gets a string describing the action executed by the current optimization
  98487. * @return description string
  98488. */
  98489. PostProcessesOptimization.prototype.getDescription = function () {
  98490. return "Turning post-processes on/off";
  98491. };
  98492. /**
  98493. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98494. * @param scene defines the current scene where to apply this optimization
  98495. * @param optimizer defines the current optimizer
  98496. * @returns true if everything that can be done was applied
  98497. */
  98498. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  98499. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  98500. return true;
  98501. };
  98502. ;
  98503. return PostProcessesOptimization;
  98504. }(SceneOptimization));
  98505. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  98506. /**
  98507. * Defines an optimization used to turn lens flares off
  98508. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98509. */
  98510. var LensFlaresOptimization = /** @class */ (function (_super) {
  98511. __extends(LensFlaresOptimization, _super);
  98512. function LensFlaresOptimization() {
  98513. return _super !== null && _super.apply(this, arguments) || this;
  98514. }
  98515. /**
  98516. * Gets a string describing the action executed by the current optimization
  98517. * @return description string
  98518. */
  98519. LensFlaresOptimization.prototype.getDescription = function () {
  98520. return "Turning lens flares on/off";
  98521. };
  98522. /**
  98523. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98524. * @param scene defines the current scene where to apply this optimization
  98525. * @param optimizer defines the current optimizer
  98526. * @returns true if everything that can be done was applied
  98527. */
  98528. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  98529. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  98530. return true;
  98531. };
  98532. ;
  98533. return LensFlaresOptimization;
  98534. }(SceneOptimization));
  98535. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  98536. /**
  98537. * Defines an optimization based on user defined callback.
  98538. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98539. */
  98540. var CustomOptimization = /** @class */ (function (_super) {
  98541. __extends(CustomOptimization, _super);
  98542. function CustomOptimization() {
  98543. return _super !== null && _super.apply(this, arguments) || this;
  98544. }
  98545. /**
  98546. * Gets a string describing the action executed by the current optimization
  98547. * @returns description string
  98548. */
  98549. CustomOptimization.prototype.getDescription = function () {
  98550. if (this.onGetDescription) {
  98551. return this.onGetDescription();
  98552. }
  98553. return "Running user defined callback";
  98554. };
  98555. /**
  98556. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98557. * @param scene defines the current scene where to apply this optimization
  98558. * @param optimizer defines the current optimizer
  98559. * @returns true if everything that can be done was applied
  98560. */
  98561. CustomOptimization.prototype.apply = function (scene, optimizer) {
  98562. if (this.onApply) {
  98563. return this.onApply(scene, optimizer);
  98564. }
  98565. return true;
  98566. };
  98567. ;
  98568. return CustomOptimization;
  98569. }(SceneOptimization));
  98570. BABYLON.CustomOptimization = CustomOptimization;
  98571. /**
  98572. * Defines an optimization used to turn particles off
  98573. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98574. */
  98575. var ParticlesOptimization = /** @class */ (function (_super) {
  98576. __extends(ParticlesOptimization, _super);
  98577. function ParticlesOptimization() {
  98578. return _super !== null && _super.apply(this, arguments) || this;
  98579. }
  98580. /**
  98581. * Gets a string describing the action executed by the current optimization
  98582. * @return description string
  98583. */
  98584. ParticlesOptimization.prototype.getDescription = function () {
  98585. return "Turning particles on/off";
  98586. };
  98587. /**
  98588. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98589. * @param scene defines the current scene where to apply this optimization
  98590. * @param optimizer defines the current optimizer
  98591. * @returns true if everything that can be done was applied
  98592. */
  98593. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  98594. scene.particlesEnabled = optimizer.isInImprovementMode;
  98595. return true;
  98596. };
  98597. ;
  98598. return ParticlesOptimization;
  98599. }(SceneOptimization));
  98600. BABYLON.ParticlesOptimization = ParticlesOptimization;
  98601. /**
  98602. * Defines an optimization used to turn render targets off
  98603. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98604. */
  98605. var RenderTargetsOptimization = /** @class */ (function (_super) {
  98606. __extends(RenderTargetsOptimization, _super);
  98607. function RenderTargetsOptimization() {
  98608. return _super !== null && _super.apply(this, arguments) || this;
  98609. }
  98610. /**
  98611. * Gets a string describing the action executed by the current optimization
  98612. * @return description string
  98613. */
  98614. RenderTargetsOptimization.prototype.getDescription = function () {
  98615. return "Turning render targets off";
  98616. };
  98617. /**
  98618. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98619. * @param scene defines the current scene where to apply this optimization
  98620. * @param optimizer defines the current optimizer
  98621. * @returns true if everything that can be done was applied
  98622. */
  98623. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  98624. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  98625. return true;
  98626. };
  98627. ;
  98628. return RenderTargetsOptimization;
  98629. }(SceneOptimization));
  98630. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  98631. /**
  98632. * Defines an optimization used to merge meshes with compatible materials
  98633. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98634. */
  98635. var MergeMeshesOptimization = /** @class */ (function (_super) {
  98636. __extends(MergeMeshesOptimization, _super);
  98637. function MergeMeshesOptimization() {
  98638. var _this = _super !== null && _super.apply(this, arguments) || this;
  98639. _this._canBeMerged = function (abstractMesh) {
  98640. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  98641. return false;
  98642. }
  98643. var mesh = abstractMesh;
  98644. if (mesh.isDisposed()) {
  98645. return false;
  98646. }
  98647. if (!mesh.isVisible || !mesh.isEnabled()) {
  98648. return false;
  98649. }
  98650. if (mesh.instances.length > 0) {
  98651. return false;
  98652. }
  98653. if (mesh.skeleton || mesh.hasLODLevels) {
  98654. return false;
  98655. }
  98656. return true;
  98657. };
  98658. return _this;
  98659. }
  98660. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  98661. /**
  98662. * Gets or sets a boolean which defines if optimization octree has to be updated
  98663. */
  98664. get: function () {
  98665. return MergeMeshesOptimization._UpdateSelectionTree;
  98666. },
  98667. /**
  98668. * Gets or sets a boolean which defines if optimization octree has to be updated
  98669. */
  98670. set: function (value) {
  98671. MergeMeshesOptimization._UpdateSelectionTree = value;
  98672. },
  98673. enumerable: true,
  98674. configurable: true
  98675. });
  98676. /**
  98677. * Gets a string describing the action executed by the current optimization
  98678. * @return description string
  98679. */
  98680. MergeMeshesOptimization.prototype.getDescription = function () {
  98681. return "Merging similar meshes together";
  98682. };
  98683. /**
  98684. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98685. * @param scene defines the current scene where to apply this optimization
  98686. * @param optimizer defines the current optimizer
  98687. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  98688. * @returns true if everything that can be done was applied
  98689. */
  98690. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  98691. var globalPool = scene.meshes.slice(0);
  98692. var globalLength = globalPool.length;
  98693. for (var index = 0; index < globalLength; index++) {
  98694. var currentPool = new Array();
  98695. var current = globalPool[index];
  98696. // Checks
  98697. if (!this._canBeMerged(current)) {
  98698. continue;
  98699. }
  98700. currentPool.push(current);
  98701. // Find compatible meshes
  98702. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  98703. var otherMesh = globalPool[subIndex];
  98704. if (!this._canBeMerged(otherMesh)) {
  98705. continue;
  98706. }
  98707. if (otherMesh.material !== current.material) {
  98708. continue;
  98709. }
  98710. if (otherMesh.checkCollisions !== current.checkCollisions) {
  98711. continue;
  98712. }
  98713. currentPool.push(otherMesh);
  98714. globalLength--;
  98715. globalPool.splice(subIndex, 1);
  98716. subIndex--;
  98717. }
  98718. if (currentPool.length < 2) {
  98719. continue;
  98720. }
  98721. // Merge meshes
  98722. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  98723. }
  98724. if (updateSelectionTree != undefined) {
  98725. if (updateSelectionTree) {
  98726. scene.createOrUpdateSelectionOctree();
  98727. }
  98728. }
  98729. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  98730. scene.createOrUpdateSelectionOctree();
  98731. }
  98732. return true;
  98733. };
  98734. ;
  98735. MergeMeshesOptimization._UpdateSelectionTree = false;
  98736. return MergeMeshesOptimization;
  98737. }(SceneOptimization));
  98738. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  98739. /**
  98740. * Defines a list of options used by SceneOptimizer
  98741. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98742. */
  98743. var SceneOptimizerOptions = /** @class */ (function () {
  98744. /**
  98745. * Creates a new list of options used by SceneOptimizer
  98746. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  98747. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  98748. */
  98749. function SceneOptimizerOptions(
  98750. /**
  98751. * Defines the target frame rate to reach (60 by default)
  98752. */
  98753. targetFrameRate,
  98754. /**
  98755. * Defines the interval between two checkes (2000ms by default)
  98756. */
  98757. trackerDuration) {
  98758. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  98759. if (trackerDuration === void 0) { trackerDuration = 2000; }
  98760. this.targetFrameRate = targetFrameRate;
  98761. this.trackerDuration = trackerDuration;
  98762. /**
  98763. * Gets the list of optimizations to apply
  98764. */
  98765. this.optimizations = new Array();
  98766. }
  98767. /**
  98768. * Add a new optimization
  98769. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  98770. * @returns the current SceneOptimizerOptions
  98771. */
  98772. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  98773. this.optimizations.push(optimization);
  98774. return this;
  98775. };
  98776. /**
  98777. * Add a new custom optimization
  98778. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  98779. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  98780. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98781. * @returns the current SceneOptimizerOptions
  98782. */
  98783. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  98784. if (priority === void 0) { priority = 0; }
  98785. var optimization = new CustomOptimization(priority);
  98786. optimization.onApply = onApply;
  98787. optimization.onGetDescription = onGetDescription;
  98788. this.optimizations.push(optimization);
  98789. return this;
  98790. };
  98791. /**
  98792. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  98793. * @param targetFrameRate defines the target frame rate (60 by default)
  98794. * @returns a SceneOptimizerOptions object
  98795. */
  98796. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  98797. var result = new SceneOptimizerOptions(targetFrameRate);
  98798. var priority = 0;
  98799. result.addOptimization(new MergeMeshesOptimization(priority));
  98800. result.addOptimization(new ShadowsOptimization(priority));
  98801. result.addOptimization(new LensFlaresOptimization(priority));
  98802. // Next priority
  98803. priority++;
  98804. result.addOptimization(new PostProcessesOptimization(priority));
  98805. result.addOptimization(new ParticlesOptimization(priority));
  98806. // Next priority
  98807. priority++;
  98808. result.addOptimization(new TextureOptimization(priority, 1024));
  98809. return result;
  98810. };
  98811. /**
  98812. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  98813. * @param targetFrameRate defines the target frame rate (60 by default)
  98814. * @returns a SceneOptimizerOptions object
  98815. */
  98816. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  98817. var result = new SceneOptimizerOptions(targetFrameRate);
  98818. var priority = 0;
  98819. result.addOptimization(new MergeMeshesOptimization(priority));
  98820. result.addOptimization(new ShadowsOptimization(priority));
  98821. result.addOptimization(new LensFlaresOptimization(priority));
  98822. // Next priority
  98823. priority++;
  98824. result.addOptimization(new PostProcessesOptimization(priority));
  98825. result.addOptimization(new ParticlesOptimization(priority));
  98826. // Next priority
  98827. priority++;
  98828. result.addOptimization(new TextureOptimization(priority, 512));
  98829. // Next priority
  98830. priority++;
  98831. result.addOptimization(new RenderTargetsOptimization(priority));
  98832. // Next priority
  98833. priority++;
  98834. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  98835. return result;
  98836. };
  98837. /**
  98838. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  98839. * @param targetFrameRate defines the target frame rate (60 by default)
  98840. * @returns a SceneOptimizerOptions object
  98841. */
  98842. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  98843. var result = new SceneOptimizerOptions(targetFrameRate);
  98844. var priority = 0;
  98845. result.addOptimization(new MergeMeshesOptimization(priority));
  98846. result.addOptimization(new ShadowsOptimization(priority));
  98847. result.addOptimization(new LensFlaresOptimization(priority));
  98848. // Next priority
  98849. priority++;
  98850. result.addOptimization(new PostProcessesOptimization(priority));
  98851. result.addOptimization(new ParticlesOptimization(priority));
  98852. // Next priority
  98853. priority++;
  98854. result.addOptimization(new TextureOptimization(priority, 256));
  98855. // Next priority
  98856. priority++;
  98857. result.addOptimization(new RenderTargetsOptimization(priority));
  98858. // Next priority
  98859. priority++;
  98860. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  98861. return result;
  98862. };
  98863. return SceneOptimizerOptions;
  98864. }());
  98865. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  98866. /**
  98867. * Class used to run optimizations in order to reach a target frame rate
  98868. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98869. */
  98870. var SceneOptimizer = /** @class */ (function () {
  98871. /**
  98872. * Creates a new SceneOptimizer
  98873. * @param scene defines the scene to work on
  98874. * @param options defines the options to use with the SceneOptimizer
  98875. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  98876. * @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)
  98877. */
  98878. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  98879. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  98880. if (improvementMode === void 0) { improvementMode = false; }
  98881. var _this = this;
  98882. this._isRunning = false;
  98883. this._currentPriorityLevel = 0;
  98884. this._targetFrameRate = 60;
  98885. this._trackerDuration = 2000;
  98886. this._currentFrameRate = 0;
  98887. this._improvementMode = false;
  98888. /**
  98889. * Defines an observable called when the optimizer reaches the target frame rate
  98890. */
  98891. this.onSuccessObservable = new BABYLON.Observable();
  98892. /**
  98893. * Defines an observable called when the optimizer enables an optimization
  98894. */
  98895. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  98896. /**
  98897. * Defines an observable called when the optimizer is not able to reach the target frame rate
  98898. */
  98899. this.onFailureObservable = new BABYLON.Observable();
  98900. if (!options) {
  98901. this._options = new SceneOptimizerOptions();
  98902. }
  98903. else {
  98904. this._options = options;
  98905. }
  98906. if (this._options.targetFrameRate) {
  98907. this._targetFrameRate = this._options.targetFrameRate;
  98908. }
  98909. if (this._options.trackerDuration) {
  98910. this._trackerDuration = this._options.trackerDuration;
  98911. }
  98912. if (autoGeneratePriorities) {
  98913. var priority = 0;
  98914. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  98915. var optim = _a[_i];
  98916. optim.priority = priority++;
  98917. }
  98918. }
  98919. this._improvementMode = improvementMode;
  98920. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  98921. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  98922. _this._sceneDisposeObserver = null;
  98923. _this.dispose();
  98924. });
  98925. }
  98926. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  98927. /**
  98928. * Gets a boolean indicating if the optimizer is in improvement mode
  98929. */
  98930. get: function () {
  98931. return this._improvementMode;
  98932. },
  98933. enumerable: true,
  98934. configurable: true
  98935. });
  98936. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  98937. /**
  98938. * Gets the current priority level (0 at start)
  98939. */
  98940. get: function () {
  98941. return this._currentPriorityLevel;
  98942. },
  98943. enumerable: true,
  98944. configurable: true
  98945. });
  98946. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  98947. /**
  98948. * Gets the current frame rate checked by the SceneOptimizer
  98949. */
  98950. get: function () {
  98951. return this._currentFrameRate;
  98952. },
  98953. enumerable: true,
  98954. configurable: true
  98955. });
  98956. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  98957. /**
  98958. * Gets or sets the current target frame rate (60 by default)
  98959. */
  98960. get: function () {
  98961. return this._targetFrameRate;
  98962. },
  98963. /**
  98964. * Gets or sets the current target frame rate (60 by default)
  98965. */
  98966. set: function (value) {
  98967. this._targetFrameRate = value;
  98968. },
  98969. enumerable: true,
  98970. configurable: true
  98971. });
  98972. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  98973. /**
  98974. * Gets or sets the current interval between two checks (every 2000ms by default)
  98975. */
  98976. get: function () {
  98977. return this._trackerDuration;
  98978. },
  98979. /**
  98980. * Gets or sets the current interval between two checks (every 2000ms by default)
  98981. */
  98982. set: function (value) {
  98983. this._trackerDuration = value;
  98984. },
  98985. enumerable: true,
  98986. configurable: true
  98987. });
  98988. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  98989. /**
  98990. * Gets the list of active optimizations
  98991. */
  98992. get: function () {
  98993. return this._options.optimizations;
  98994. },
  98995. enumerable: true,
  98996. configurable: true
  98997. });
  98998. /**
  98999. * Stops the current optimizer
  99000. */
  99001. SceneOptimizer.prototype.stop = function () {
  99002. this._isRunning = false;
  99003. };
  99004. /**
  99005. * Reset the optimizer to initial step (current priority level = 0)
  99006. */
  99007. SceneOptimizer.prototype.reset = function () {
  99008. this._currentPriorityLevel = 0;
  99009. };
  99010. /**
  99011. * Start the optimizer. By default it will try to reach a specific framerate
  99012. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  99013. */
  99014. SceneOptimizer.prototype.start = function () {
  99015. var _this = this;
  99016. if (this._isRunning) {
  99017. return;
  99018. }
  99019. this._isRunning = true;
  99020. // Let's wait for the scene to be ready before running our check
  99021. this._scene.executeWhenReady(function () {
  99022. setTimeout(function () {
  99023. _this._checkCurrentState();
  99024. }, _this._trackerDuration);
  99025. });
  99026. };
  99027. SceneOptimizer.prototype._checkCurrentState = function () {
  99028. var _this = this;
  99029. if (!this._isRunning) {
  99030. return;
  99031. }
  99032. var scene = this._scene;
  99033. var options = this._options;
  99034. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  99035. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  99036. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  99037. this._isRunning = false;
  99038. this.onSuccessObservable.notifyObservers(this);
  99039. return;
  99040. }
  99041. // Apply current level of optimizations
  99042. var allDone = true;
  99043. var noOptimizationApplied = true;
  99044. for (var index = 0; index < options.optimizations.length; index++) {
  99045. var optimization = options.optimizations[index];
  99046. if (optimization.priority === this._currentPriorityLevel) {
  99047. noOptimizationApplied = false;
  99048. allDone = allDone && optimization.apply(scene, this);
  99049. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  99050. }
  99051. }
  99052. // If no optimization was applied, this is a failure :(
  99053. if (noOptimizationApplied) {
  99054. this._isRunning = false;
  99055. this.onFailureObservable.notifyObservers(this);
  99056. return;
  99057. }
  99058. // If all optimizations were done, move to next level
  99059. if (allDone) {
  99060. this._currentPriorityLevel++;
  99061. }
  99062. // Let's the system running for a specific amount of time before checking FPS
  99063. scene.executeWhenReady(function () {
  99064. setTimeout(function () {
  99065. _this._checkCurrentState();
  99066. }, _this._trackerDuration);
  99067. });
  99068. };
  99069. /**
  99070. * Release all resources
  99071. */
  99072. SceneOptimizer.prototype.dispose = function () {
  99073. this.stop();
  99074. this.onSuccessObservable.clear();
  99075. this.onFailureObservable.clear();
  99076. this.onNewOptimizationAppliedObservable.clear();
  99077. if (this._sceneDisposeObserver) {
  99078. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  99079. }
  99080. };
  99081. /**
  99082. * Helper function to create a SceneOptimizer with one single line of code
  99083. * @param scene defines the scene to work on
  99084. * @param options defines the options to use with the SceneOptimizer
  99085. * @param onSuccess defines a callback to call on success
  99086. * @param onFailure defines a callback to call on failure
  99087. * @returns the new SceneOptimizer object
  99088. */
  99089. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  99090. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  99091. if (onSuccess) {
  99092. optimizer.onSuccessObservable.add(function () {
  99093. onSuccess();
  99094. });
  99095. }
  99096. if (onFailure) {
  99097. optimizer.onFailureObservable.add(function () {
  99098. onFailure();
  99099. });
  99100. }
  99101. optimizer.start();
  99102. return optimizer;
  99103. };
  99104. return SceneOptimizer;
  99105. }());
  99106. BABYLON.SceneOptimizer = SceneOptimizer;
  99107. })(BABYLON || (BABYLON = {}));
  99108. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  99109. var BABYLON;
  99110. (function (BABYLON) {
  99111. var OutlineRenderer = /** @class */ (function () {
  99112. function OutlineRenderer(scene) {
  99113. this.zOffset = 1;
  99114. this._scene = scene;
  99115. }
  99116. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  99117. var _this = this;
  99118. if (useOverlay === void 0) { useOverlay = false; }
  99119. var scene = this._scene;
  99120. var engine = this._scene.getEngine();
  99121. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  99122. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  99123. return;
  99124. }
  99125. var mesh = subMesh.getRenderingMesh();
  99126. var material = subMesh.getMaterial();
  99127. if (!material || !scene.activeCamera) {
  99128. return;
  99129. }
  99130. engine.enableEffect(this._effect);
  99131. // Logarithmic depth
  99132. if (material.useLogarithmicDepth) {
  99133. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  99134. }
  99135. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  99136. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  99137. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  99138. // Bones
  99139. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  99140. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  99141. }
  99142. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  99143. // Alpha test
  99144. if (material && material.needAlphaTesting()) {
  99145. var alphaTexture = material.getAlphaTestTexture();
  99146. if (alphaTexture) {
  99147. this._effect.setTexture("diffuseSampler", alphaTexture);
  99148. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  99149. }
  99150. }
  99151. engine.setZOffset(-this.zOffset);
  99152. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  99153. engine.setZOffset(0);
  99154. };
  99155. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  99156. var defines = [];
  99157. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  99158. var mesh = subMesh.getMesh();
  99159. var material = subMesh.getMaterial();
  99160. if (material) {
  99161. // Alpha test
  99162. if (material.needAlphaTesting()) {
  99163. defines.push("#define ALPHATEST");
  99164. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  99165. attribs.push(BABYLON.VertexBuffer.UVKind);
  99166. defines.push("#define UV1");
  99167. }
  99168. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  99169. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  99170. defines.push("#define UV2");
  99171. }
  99172. }
  99173. //Logarithmic depth
  99174. if (material.useLogarithmicDepth) {
  99175. defines.push("#define LOGARITHMICDEPTH");
  99176. }
  99177. }
  99178. // Bones
  99179. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  99180. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  99181. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  99182. if (mesh.numBoneInfluencers > 4) {
  99183. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  99184. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  99185. }
  99186. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  99187. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  99188. }
  99189. else {
  99190. defines.push("#define NUM_BONE_INFLUENCERS 0");
  99191. }
  99192. // Instances
  99193. if (useInstances) {
  99194. defines.push("#define INSTANCES");
  99195. attribs.push("world0");
  99196. attribs.push("world1");
  99197. attribs.push("world2");
  99198. attribs.push("world3");
  99199. }
  99200. // Get correct effect
  99201. var join = defines.join("\n");
  99202. if (this._cachedDefines !== join) {
  99203. this._cachedDefines = join;
  99204. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  99205. }
  99206. return this._effect.isReady();
  99207. };
  99208. return OutlineRenderer;
  99209. }());
  99210. BABYLON.OutlineRenderer = OutlineRenderer;
  99211. })(BABYLON || (BABYLON = {}));
  99212. //# sourceMappingURL=babylon.outlineRenderer.js.map
  99213. var BABYLON;
  99214. (function (BABYLON) {
  99215. /**
  99216. * FaceAdjacencies Helper class to generate edges
  99217. */
  99218. var FaceAdjacencies = /** @class */ (function () {
  99219. function FaceAdjacencies() {
  99220. this.edges = new Array();
  99221. this.edgesConnectedCount = 0;
  99222. }
  99223. return FaceAdjacencies;
  99224. }());
  99225. /**
  99226. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  99227. */
  99228. var EdgesRenderer = /** @class */ (function () {
  99229. /**
  99230. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  99231. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  99232. * @param source Mesh used to create edges
  99233. * @param epsilon sum of angles in adjacency to check for edge
  99234. * @param checkVerticesInsteadOfIndices
  99235. * @param generateEdgesLines - should generate Lines or only prepare resources.
  99236. */
  99237. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  99238. if (epsilon === void 0) { epsilon = 0.95; }
  99239. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  99240. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  99241. this.edgesWidthScalerForOrthographic = 1000.0;
  99242. this.edgesWidthScalerForPerspective = 50.0;
  99243. this._linesPositions = new Array();
  99244. this._linesNormals = new Array();
  99245. this._linesIndices = new Array();
  99246. this._buffers = {};
  99247. this._checkVerticesInsteadOfIndices = false;
  99248. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  99249. this.isEnabled = true;
  99250. this._source = source;
  99251. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  99252. this._epsilon = epsilon;
  99253. this._prepareRessources();
  99254. if (generateEdgesLines) {
  99255. this._generateEdgesLines();
  99256. }
  99257. }
  99258. EdgesRenderer.prototype._prepareRessources = function () {
  99259. if (this._lineShader) {
  99260. return;
  99261. }
  99262. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  99263. attributes: ["position", "normal"],
  99264. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  99265. });
  99266. this._lineShader.disableDepthWrite = true;
  99267. this._lineShader.backFaceCulling = false;
  99268. };
  99269. /** @hidden */
  99270. EdgesRenderer.prototype._rebuild = function () {
  99271. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  99272. if (buffer) {
  99273. buffer._rebuild();
  99274. }
  99275. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  99276. if (buffer) {
  99277. buffer._rebuild();
  99278. }
  99279. var scene = this._source.getScene();
  99280. var engine = scene.getEngine();
  99281. this._ib = engine.createIndexBuffer(this._linesIndices);
  99282. };
  99283. /**
  99284. * Releases the required resources for the edges renderer
  99285. */
  99286. EdgesRenderer.prototype.dispose = function () {
  99287. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  99288. if (buffer) {
  99289. buffer.dispose();
  99290. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  99291. }
  99292. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  99293. if (buffer) {
  99294. buffer.dispose();
  99295. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  99296. }
  99297. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  99298. this._lineShader.dispose();
  99299. };
  99300. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  99301. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  99302. return 0;
  99303. }
  99304. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  99305. return 1;
  99306. }
  99307. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  99308. return 2;
  99309. }
  99310. return -1;
  99311. };
  99312. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  99313. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  99314. return 0;
  99315. }
  99316. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  99317. return 1;
  99318. }
  99319. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  99320. return 2;
  99321. }
  99322. return -1;
  99323. };
  99324. /**
  99325. * Checks if the pair of p0 and p1 is en edge
  99326. * @param faceIndex
  99327. * @param edge
  99328. * @param faceNormals
  99329. * @param p0
  99330. * @param p1
  99331. * @private
  99332. */
  99333. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  99334. var needToCreateLine;
  99335. if (edge === undefined) {
  99336. needToCreateLine = true;
  99337. }
  99338. else {
  99339. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  99340. needToCreateLine = dotProduct < this._epsilon;
  99341. }
  99342. if (needToCreateLine) {
  99343. var offset = this._linesPositions.length / 3;
  99344. var normal = p0.subtract(p1);
  99345. normal.normalize();
  99346. // Positions
  99347. this._linesPositions.push(p0.x);
  99348. this._linesPositions.push(p0.y);
  99349. this._linesPositions.push(p0.z);
  99350. this._linesPositions.push(p0.x);
  99351. this._linesPositions.push(p0.y);
  99352. this._linesPositions.push(p0.z);
  99353. this._linesPositions.push(p1.x);
  99354. this._linesPositions.push(p1.y);
  99355. this._linesPositions.push(p1.z);
  99356. this._linesPositions.push(p1.x);
  99357. this._linesPositions.push(p1.y);
  99358. this._linesPositions.push(p1.z);
  99359. // Normals
  99360. this._linesNormals.push(p1.x);
  99361. this._linesNormals.push(p1.y);
  99362. this._linesNormals.push(p1.z);
  99363. this._linesNormals.push(-1);
  99364. this._linesNormals.push(p1.x);
  99365. this._linesNormals.push(p1.y);
  99366. this._linesNormals.push(p1.z);
  99367. this._linesNormals.push(1);
  99368. this._linesNormals.push(p0.x);
  99369. this._linesNormals.push(p0.y);
  99370. this._linesNormals.push(p0.z);
  99371. this._linesNormals.push(-1);
  99372. this._linesNormals.push(p0.x);
  99373. this._linesNormals.push(p0.y);
  99374. this._linesNormals.push(p0.z);
  99375. this._linesNormals.push(1);
  99376. // Indices
  99377. this._linesIndices.push(offset);
  99378. this._linesIndices.push(offset + 1);
  99379. this._linesIndices.push(offset + 2);
  99380. this._linesIndices.push(offset);
  99381. this._linesIndices.push(offset + 2);
  99382. this._linesIndices.push(offset + 3);
  99383. }
  99384. };
  99385. /**
  99386. * Generates lines edges from adjacencjes
  99387. * @private
  99388. */
  99389. EdgesRenderer.prototype._generateEdgesLines = function () {
  99390. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99391. var indices = this._source.getIndices();
  99392. if (!indices || !positions) {
  99393. return;
  99394. }
  99395. // First let's find adjacencies
  99396. var adjacencies = new Array();
  99397. var faceNormals = new Array();
  99398. var index;
  99399. var faceAdjacencies;
  99400. // Prepare faces
  99401. for (index = 0; index < indices.length; index += 3) {
  99402. faceAdjacencies = new FaceAdjacencies();
  99403. var p0Index = indices[index];
  99404. var p1Index = indices[index + 1];
  99405. var p2Index = indices[index + 2];
  99406. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  99407. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  99408. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  99409. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  99410. faceNormal.normalize();
  99411. faceNormals.push(faceNormal);
  99412. adjacencies.push(faceAdjacencies);
  99413. }
  99414. // Scan
  99415. for (index = 0; index < adjacencies.length; index++) {
  99416. faceAdjacencies = adjacencies[index];
  99417. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  99418. var otherFaceAdjacencies = adjacencies[otherIndex];
  99419. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  99420. break;
  99421. }
  99422. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  99423. continue;
  99424. }
  99425. var otherP0 = indices[otherIndex * 3];
  99426. var otherP1 = indices[otherIndex * 3 + 1];
  99427. var otherP2 = indices[otherIndex * 3 + 2];
  99428. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  99429. var otherEdgeIndex = 0;
  99430. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  99431. continue;
  99432. }
  99433. switch (edgeIndex) {
  99434. case 0:
  99435. if (this._checkVerticesInsteadOfIndices) {
  99436. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99437. }
  99438. else {
  99439. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  99440. }
  99441. break;
  99442. case 1:
  99443. if (this._checkVerticesInsteadOfIndices) {
  99444. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99445. }
  99446. else {
  99447. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  99448. }
  99449. break;
  99450. case 2:
  99451. if (this._checkVerticesInsteadOfIndices) {
  99452. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99453. }
  99454. else {
  99455. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  99456. }
  99457. break;
  99458. }
  99459. if (otherEdgeIndex === -1) {
  99460. continue;
  99461. }
  99462. faceAdjacencies.edges[edgeIndex] = otherIndex;
  99463. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  99464. faceAdjacencies.edgesConnectedCount++;
  99465. otherFaceAdjacencies.edgesConnectedCount++;
  99466. if (faceAdjacencies.edgesConnectedCount === 3) {
  99467. break;
  99468. }
  99469. }
  99470. }
  99471. }
  99472. // Create lines
  99473. for (index = 0; index < adjacencies.length; index++) {
  99474. // 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
  99475. var current = adjacencies[index];
  99476. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  99477. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  99478. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  99479. }
  99480. // Merge into a single mesh
  99481. var engine = this._source.getScene().getEngine();
  99482. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  99483. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  99484. this._ib = engine.createIndexBuffer(this._linesIndices);
  99485. this._indicesCount = this._linesIndices.length;
  99486. };
  99487. EdgesRenderer.prototype.render = function () {
  99488. var scene = this._source.getScene();
  99489. if (!this._lineShader.isReady() || !scene.activeCamera) {
  99490. return;
  99491. }
  99492. var engine = scene.getEngine();
  99493. this._lineShader._preBind();
  99494. if (this._source.edgesColor.a !== 1) {
  99495. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  99496. }
  99497. else {
  99498. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99499. }
  99500. // VBOs
  99501. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  99502. scene.resetCachedMaterial();
  99503. this._lineShader.setColor4("color", this._source.edgesColor);
  99504. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  99505. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  99506. }
  99507. else {
  99508. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  99509. }
  99510. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  99511. this._lineShader.bind(this._source.getWorldMatrix());
  99512. // Draw order
  99513. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  99514. this._lineShader.unbind();
  99515. };
  99516. return EdgesRenderer;
  99517. }());
  99518. BABYLON.EdgesRenderer = EdgesRenderer;
  99519. })(BABYLON || (BABYLON = {}));
  99520. //# sourceMappingURL=babylon.edgesRenderer.js.map
  99521. var BABYLON;
  99522. (function (BABYLON) {
  99523. /**
  99524. * FaceAdjacencies Helper class to generate edges
  99525. */
  99526. var FaceAdjacencies = /** @class */ (function () {
  99527. function FaceAdjacencies() {
  99528. this.edges = new Array();
  99529. this.edgesConnectedCount = 0;
  99530. }
  99531. return FaceAdjacencies;
  99532. }());
  99533. /**
  99534. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  99535. */
  99536. var LineEdgesRenderer = /** @class */ (function (_super) {
  99537. __extends(LineEdgesRenderer, _super);
  99538. /**
  99539. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  99540. * @param source LineMesh used to generate edges
  99541. * @param epsilon not important (specified angle for edge detection)
  99542. * @param checkVerticesInsteadOfIndices not important for LineMesh
  99543. */
  99544. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  99545. if (epsilon === void 0) { epsilon = 0.95; }
  99546. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  99547. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  99548. _this._generateEdgesLines();
  99549. return _this;
  99550. }
  99551. /**
  99552. * Always create the edge since its a line so only important things are p0 and p1
  99553. * @param faceIndex not important for LineMesh
  99554. * @param edge not important for LineMesh
  99555. * @param faceNormals not important for LineMesh
  99556. * @param p0 beginnig of line
  99557. * @param p1 end of line
  99558. */
  99559. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  99560. var offset = this._linesPositions.length / 3;
  99561. var normal = p0.subtract(p1);
  99562. normal.normalize();
  99563. // Positions
  99564. this._linesPositions.push(p0.x);
  99565. this._linesPositions.push(p0.y);
  99566. this._linesPositions.push(p0.z);
  99567. this._linesPositions.push(p0.x);
  99568. this._linesPositions.push(p0.y);
  99569. this._linesPositions.push(p0.z);
  99570. this._linesPositions.push(p1.x);
  99571. this._linesPositions.push(p1.y);
  99572. this._linesPositions.push(p1.z);
  99573. this._linesPositions.push(p1.x);
  99574. this._linesPositions.push(p1.y);
  99575. this._linesPositions.push(p1.z);
  99576. // Normals
  99577. this._linesNormals.push(p1.x);
  99578. this._linesNormals.push(p1.y);
  99579. this._linesNormals.push(p1.z);
  99580. this._linesNormals.push(-1);
  99581. this._linesNormals.push(p1.x);
  99582. this._linesNormals.push(p1.y);
  99583. this._linesNormals.push(p1.z);
  99584. this._linesNormals.push(1);
  99585. this._linesNormals.push(p0.x);
  99586. this._linesNormals.push(p0.y);
  99587. this._linesNormals.push(p0.z);
  99588. this._linesNormals.push(-1);
  99589. this._linesNormals.push(p0.x);
  99590. this._linesNormals.push(p0.y);
  99591. this._linesNormals.push(p0.z);
  99592. this._linesNormals.push(1);
  99593. // Indices
  99594. this._linesIndices.push(offset);
  99595. this._linesIndices.push(offset + 1);
  99596. this._linesIndices.push(offset + 2);
  99597. this._linesIndices.push(offset);
  99598. this._linesIndices.push(offset + 2);
  99599. this._linesIndices.push(offset + 3);
  99600. };
  99601. /**
  99602. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  99603. */
  99604. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  99605. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99606. var indices = this._source.getIndices();
  99607. if (!indices || !positions) {
  99608. return;
  99609. }
  99610. // First let's find adjacencies
  99611. var adjacencies = new Array();
  99612. var faceNormals = new Array();
  99613. var index;
  99614. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  99615. var currentAdjecancy = new FaceAdjacencies();
  99616. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  99617. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  99618. adjacencies.push(currentAdjecancy);
  99619. }
  99620. // Create lines
  99621. for (index = 0; index < adjacencies.length; index++) {
  99622. // 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
  99623. var current = adjacencies[index];
  99624. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  99625. }
  99626. // Merge into a single mesh
  99627. var engine = this._source.getScene().getEngine();
  99628. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  99629. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  99630. this._ib = engine.createIndexBuffer(this._linesIndices);
  99631. this._indicesCount = this._linesIndices.length;
  99632. };
  99633. return LineEdgesRenderer;
  99634. }(BABYLON.EdgesRenderer));
  99635. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  99636. })(BABYLON || (BABYLON = {}));
  99637. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  99638. var BABYLON;
  99639. (function (BABYLON) {
  99640. // Adds the parser to the scene parsers.
  99641. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  99642. if (parsedData.effectLayers) {
  99643. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  99644. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  99645. container.effectLayers.push(effectLayer);
  99646. }
  99647. }
  99648. });
  99649. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  99650. var index = this.effectLayers.indexOf(toRemove);
  99651. if (index !== -1) {
  99652. this.effectLayers.splice(index, 1);
  99653. }
  99654. return index;
  99655. };
  99656. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  99657. this.effectLayers.push(newEffectLayer);
  99658. };
  99659. /**
  99660. * Defines the layer scene component responsible to manage any effect layers
  99661. * in a given scene.
  99662. */
  99663. var EffectLayerSceneComponent = /** @class */ (function () {
  99664. /**
  99665. * Creates a new instance of the component for the given scene
  99666. * @param scene Defines the scene to register the component in
  99667. */
  99668. function EffectLayerSceneComponent(scene) {
  99669. /**
  99670. * The component name helpfull to identify the component in the list of scene components.
  99671. */
  99672. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  99673. this._renderEffects = false;
  99674. this._needStencil = false;
  99675. this._previousStencilState = false;
  99676. this.scene = scene;
  99677. this._engine = scene.getEngine();
  99678. scene.effectLayers = new Array();
  99679. }
  99680. /**
  99681. * Registers the component in a given scene
  99682. */
  99683. EffectLayerSceneComponent.prototype.register = function () {
  99684. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  99685. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  99686. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  99687. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  99688. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  99689. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  99690. };
  99691. /**
  99692. * Rebuilds the elements related to this component in case of
  99693. * context lost for instance.
  99694. */
  99695. EffectLayerSceneComponent.prototype.rebuild = function () {
  99696. var layers = this.scene.effectLayers;
  99697. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  99698. var effectLayer = layers_1[_i];
  99699. effectLayer._rebuild();
  99700. }
  99701. };
  99702. /**
  99703. * Serializes the component data to the specified json object
  99704. * @param serializationObject The object to serialize to
  99705. */
  99706. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  99707. // Effect layers
  99708. serializationObject.effectLayers = [];
  99709. var layers = this.scene.effectLayers;
  99710. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  99711. var effectLayer = layers_2[_i];
  99712. if (effectLayer.serialize) {
  99713. serializationObject.effectLayers.push(effectLayer.serialize());
  99714. }
  99715. }
  99716. };
  99717. /**
  99718. * Adds all the element from the container to the scene
  99719. * @param container the container holding the elements
  99720. */
  99721. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  99722. var _this = this;
  99723. if (!container.effectLayers) {
  99724. return;
  99725. }
  99726. container.effectLayers.forEach(function (o) {
  99727. _this.scene.addEffectLayer(o);
  99728. });
  99729. };
  99730. /**
  99731. * Removes all the elements in the container from the scene
  99732. * @param container contains the elements to remove
  99733. */
  99734. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  99735. var _this = this;
  99736. if (!container.effectLayers) {
  99737. return;
  99738. }
  99739. container.effectLayers.forEach(function (o) {
  99740. _this.scene.removeEffectLayer(o);
  99741. });
  99742. };
  99743. /**
  99744. * Disposes the component and the associated ressources.
  99745. */
  99746. EffectLayerSceneComponent.prototype.dispose = function () {
  99747. var layers = this.scene.effectLayers;
  99748. while (layers.length) {
  99749. layers[0].dispose();
  99750. }
  99751. };
  99752. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  99753. var layers = this.scene.effectLayers;
  99754. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  99755. var layer = layers_3[_i];
  99756. if (!layer.hasMesh(mesh)) {
  99757. continue;
  99758. }
  99759. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  99760. var subMesh = _b[_a];
  99761. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  99762. return false;
  99763. }
  99764. }
  99765. }
  99766. return true;
  99767. };
  99768. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  99769. this._renderEffects = false;
  99770. this._needStencil = false;
  99771. var layers = this.scene.effectLayers;
  99772. if (layers && layers.length > 0) {
  99773. this._previousStencilState = this._engine.getStencilBuffer();
  99774. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  99775. var effectLayer = layers_4[_i];
  99776. if (effectLayer.shouldRender() &&
  99777. (!effectLayer.camera ||
  99778. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  99779. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  99780. this._renderEffects = true;
  99781. this._needStencil = this._needStencil || effectLayer.needStencil();
  99782. var renderTarget = effectLayer._mainTexture;
  99783. if (renderTarget._shouldRender()) {
  99784. this.scene.incrementRenderId();
  99785. renderTarget.render(false, false);
  99786. }
  99787. }
  99788. }
  99789. this.scene.incrementRenderId();
  99790. }
  99791. };
  99792. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  99793. // Activate effect Layer stencil
  99794. if (this._needStencil) {
  99795. this._engine.setStencilBuffer(true);
  99796. }
  99797. };
  99798. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  99799. // Restore effect Layer stencil
  99800. if (this._needStencil) {
  99801. this._engine.setStencilBuffer(this._previousStencilState);
  99802. }
  99803. };
  99804. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  99805. if (this._renderEffects) {
  99806. this._engine.setDepthBuffer(false);
  99807. var layers = this.scene.effectLayers;
  99808. for (var i = 0; i < layers.length; i++) {
  99809. var effectLayer = layers[i];
  99810. if (effectLayer.renderingGroupId === renderingGroupId) {
  99811. if (effectLayer.shouldRender()) {
  99812. effectLayer.render();
  99813. }
  99814. }
  99815. }
  99816. this._engine.setDepthBuffer(true);
  99817. }
  99818. };
  99819. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  99820. if (this._renderEffects) {
  99821. this._draw(-1);
  99822. }
  99823. };
  99824. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  99825. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  99826. this._draw(index);
  99827. }
  99828. };
  99829. return EffectLayerSceneComponent;
  99830. }());
  99831. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  99832. })(BABYLON || (BABYLON = {}));
  99833. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  99834. var __assign = (this && this.__assign) || function () {
  99835. __assign = Object.assign || function(t) {
  99836. for (var s, i = 1, n = arguments.length; i < n; i++) {
  99837. s = arguments[i];
  99838. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  99839. t[p] = s[p];
  99840. }
  99841. return t;
  99842. };
  99843. return __assign.apply(this, arguments);
  99844. };
  99845. var BABYLON;
  99846. (function (BABYLON) {
  99847. /**
  99848. * The effect layer Helps adding post process effect blended with the main pass.
  99849. *
  99850. * This can be for instance use to generate glow or higlight effects on the scene.
  99851. *
  99852. * The effect layer class can not be used directly and is intented to inherited from to be
  99853. * customized per effects.
  99854. */
  99855. var EffectLayer = /** @class */ (function () {
  99856. /**
  99857. * Instantiates a new effect Layer and references it in the scene.
  99858. * @param name The name of the layer
  99859. * @param scene The scene to use the layer in
  99860. */
  99861. function EffectLayer(
  99862. /** The Friendly of the effect in the scene */
  99863. name, scene) {
  99864. this._vertexBuffers = {};
  99865. this._maxSize = 0;
  99866. this._mainTextureDesiredSize = { width: 0, height: 0 };
  99867. this._shouldRender = true;
  99868. this._postProcesses = [];
  99869. this._textures = [];
  99870. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  99871. /**
  99872. * The clear color of the texture used to generate the glow map.
  99873. */
  99874. this.neutralColor = new BABYLON.Color4();
  99875. /**
  99876. * Specifies wether the highlight layer is enabled or not.
  99877. */
  99878. this.isEnabled = true;
  99879. /**
  99880. * An event triggered when the effect layer has been disposed.
  99881. */
  99882. this.onDisposeObservable = new BABYLON.Observable();
  99883. /**
  99884. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  99885. */
  99886. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  99887. /**
  99888. * An event triggered when the generated texture is being merged in the scene.
  99889. */
  99890. this.onBeforeComposeObservable = new BABYLON.Observable();
  99891. /**
  99892. * An event triggered when the generated texture has been merged in the scene.
  99893. */
  99894. this.onAfterComposeObservable = new BABYLON.Observable();
  99895. /**
  99896. * An event triggered when the efffect layer changes its size.
  99897. */
  99898. this.onSizeChangedObservable = new BABYLON.Observable();
  99899. this.name = name;
  99900. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  99901. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  99902. if (!component) {
  99903. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  99904. this._scene._addComponent(component);
  99905. }
  99906. this._engine = this._scene.getEngine();
  99907. this._maxSize = this._engine.getCaps().maxTextureSize;
  99908. this._scene.effectLayers.push(this);
  99909. // Generate Buffers
  99910. this._generateIndexBuffer();
  99911. this._genrateVertexBuffer();
  99912. }
  99913. Object.defineProperty(EffectLayer.prototype, "camera", {
  99914. /**
  99915. * Gets the camera attached to the layer.
  99916. */
  99917. get: function () {
  99918. return this._effectLayerOptions.camera;
  99919. },
  99920. enumerable: true,
  99921. configurable: true
  99922. });
  99923. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  99924. /**
  99925. * Gets the rendering group id the layer should render in.
  99926. */
  99927. get: function () {
  99928. return this._effectLayerOptions.renderingGroupId;
  99929. },
  99930. enumerable: true,
  99931. configurable: true
  99932. });
  99933. /**
  99934. * Initializes the effect layer with the required options.
  99935. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  99936. */
  99937. EffectLayer.prototype._init = function (options) {
  99938. // Adapt options
  99939. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  99940. this._setMainTextureSize();
  99941. this._createMainTexture();
  99942. this._createTextureAndPostProcesses();
  99943. this._mergeEffect = this._createMergeEffect();
  99944. };
  99945. /**
  99946. * Generates the index buffer of the full screen quad blending to the main canvas.
  99947. */
  99948. EffectLayer.prototype._generateIndexBuffer = function () {
  99949. // Indices
  99950. var indices = [];
  99951. indices.push(0);
  99952. indices.push(1);
  99953. indices.push(2);
  99954. indices.push(0);
  99955. indices.push(2);
  99956. indices.push(3);
  99957. this._indexBuffer = this._engine.createIndexBuffer(indices);
  99958. };
  99959. /**
  99960. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  99961. */
  99962. EffectLayer.prototype._genrateVertexBuffer = function () {
  99963. // VBO
  99964. var vertices = [];
  99965. vertices.push(1, 1);
  99966. vertices.push(-1, 1);
  99967. vertices.push(-1, -1);
  99968. vertices.push(1, -1);
  99969. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  99970. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  99971. };
  99972. /**
  99973. * Sets the main texture desired size which is the closest power of two
  99974. * of the engine canvas size.
  99975. */
  99976. EffectLayer.prototype._setMainTextureSize = function () {
  99977. if (this._effectLayerOptions.mainTextureFixedSize) {
  99978. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  99979. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  99980. }
  99981. else {
  99982. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  99983. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  99984. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  99985. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  99986. }
  99987. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  99988. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  99989. };
  99990. /**
  99991. * Creates the main texture for the effect layer.
  99992. */
  99993. EffectLayer.prototype._createMainTexture = function () {
  99994. var _this = this;
  99995. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  99996. width: this._mainTextureDesiredSize.width,
  99997. height: this._mainTextureDesiredSize.height
  99998. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  99999. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  100000. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100001. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100002. this._mainTexture.anisotropicFilteringLevel = 1;
  100003. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100004. this._mainTexture.renderParticles = false;
  100005. this._mainTexture.renderList = null;
  100006. this._mainTexture.ignoreCameraViewport = true;
  100007. // Custom render function
  100008. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  100009. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  100010. var index;
  100011. var engine = _this._scene.getEngine();
  100012. if (depthOnlySubMeshes.length) {
  100013. engine.setColorWrite(false);
  100014. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  100015. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  100016. }
  100017. engine.setColorWrite(true);
  100018. }
  100019. for (index = 0; index < opaqueSubMeshes.length; index++) {
  100020. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  100021. }
  100022. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  100023. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  100024. }
  100025. for (index = 0; index < transparentSubMeshes.length; index++) {
  100026. _this._renderSubMesh(transparentSubMeshes.data[index]);
  100027. }
  100028. };
  100029. this._mainTexture.onClearObservable.add(function (engine) {
  100030. engine.clear(_this.neutralColor, true, true, true);
  100031. });
  100032. };
  100033. /**
  100034. * Checks for the readiness of the element composing the layer.
  100035. * @param subMesh the mesh to check for
  100036. * @param useInstances specify wether or not to use instances to render the mesh
  100037. * @param emissiveTexture the associated emissive texture used to generate the glow
  100038. * @return true if ready otherwise, false
  100039. */
  100040. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  100041. var material = subMesh.getMaterial();
  100042. if (!material) {
  100043. return false;
  100044. }
  100045. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  100046. return false;
  100047. }
  100048. var defines = [];
  100049. var attribs = [BABYLON.VertexBuffer.PositionKind];
  100050. var mesh = subMesh.getMesh();
  100051. var uv1 = false;
  100052. var uv2 = false;
  100053. // Alpha test
  100054. if (material && material.needAlphaTesting()) {
  100055. var alphaTexture = material.getAlphaTestTexture();
  100056. if (alphaTexture) {
  100057. defines.push("#define ALPHATEST");
  100058. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  100059. alphaTexture.coordinatesIndex === 1) {
  100060. defines.push("#define DIFFUSEUV2");
  100061. uv2 = true;
  100062. }
  100063. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100064. defines.push("#define DIFFUSEUV1");
  100065. uv1 = true;
  100066. }
  100067. }
  100068. }
  100069. // Emissive
  100070. if (emissiveTexture) {
  100071. defines.push("#define EMISSIVE");
  100072. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  100073. emissiveTexture.coordinatesIndex === 1) {
  100074. defines.push("#define EMISSIVEUV2");
  100075. uv2 = true;
  100076. }
  100077. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100078. defines.push("#define EMISSIVEUV1");
  100079. uv1 = true;
  100080. }
  100081. }
  100082. if (uv1) {
  100083. attribs.push(BABYLON.VertexBuffer.UVKind);
  100084. defines.push("#define UV1");
  100085. }
  100086. if (uv2) {
  100087. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100088. defines.push("#define UV2");
  100089. }
  100090. // Bones
  100091. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  100092. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  100093. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  100094. if (mesh.numBoneInfluencers > 4) {
  100095. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  100096. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  100097. }
  100098. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  100099. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  100100. }
  100101. else {
  100102. defines.push("#define NUM_BONE_INFLUENCERS 0");
  100103. }
  100104. // Morph targets
  100105. var manager = mesh.morphTargetManager;
  100106. var morphInfluencers = 0;
  100107. if (manager) {
  100108. if (manager.numInfluencers > 0) {
  100109. defines.push("#define MORPHTARGETS");
  100110. morphInfluencers = manager.numInfluencers;
  100111. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  100112. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  100113. }
  100114. }
  100115. // Instances
  100116. if (useInstances) {
  100117. defines.push("#define INSTANCES");
  100118. attribs.push("world0");
  100119. attribs.push("world1");
  100120. attribs.push("world2");
  100121. attribs.push("world3");
  100122. }
  100123. // Get correct effect
  100124. var join = defines.join("\n");
  100125. if (this._cachedDefines !== join) {
  100126. this._cachedDefines = join;
  100127. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  100128. }
  100129. return this._effectLayerMapGenerationEffect.isReady();
  100130. };
  100131. /**
  100132. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  100133. */
  100134. EffectLayer.prototype.render = function () {
  100135. var currentEffect = this._mergeEffect;
  100136. // Check
  100137. if (!currentEffect.isReady())
  100138. return;
  100139. for (var i = 0; i < this._postProcesses.length; i++) {
  100140. if (!this._postProcesses[i].isReady()) {
  100141. return;
  100142. }
  100143. }
  100144. var engine = this._scene.getEngine();
  100145. this.onBeforeComposeObservable.notifyObservers(this);
  100146. // Render
  100147. engine.enableEffect(currentEffect);
  100148. engine.setState(false);
  100149. // VBOs
  100150. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  100151. // Cache
  100152. var previousAlphaMode = engine.getAlphaMode();
  100153. // Go Blend.
  100154. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  100155. // Blends the map on the main canvas.
  100156. this._internalRender(currentEffect);
  100157. // Restore Alpha
  100158. engine.setAlphaMode(previousAlphaMode);
  100159. this.onAfterComposeObservable.notifyObservers(this);
  100160. // Handle size changes.
  100161. var size = this._mainTexture.getSize();
  100162. this._setMainTextureSize();
  100163. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  100164. // Recreate RTT and post processes on size change.
  100165. this.onSizeChangedObservable.notifyObservers(this);
  100166. this._disposeTextureAndPostProcesses();
  100167. this._createMainTexture();
  100168. this._createTextureAndPostProcesses();
  100169. }
  100170. };
  100171. /**
  100172. * Determine if a given mesh will be used in the current effect.
  100173. * @param mesh mesh to test
  100174. * @returns true if the mesh will be used
  100175. */
  100176. EffectLayer.prototype.hasMesh = function (mesh) {
  100177. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  100178. return true;
  100179. }
  100180. return false;
  100181. };
  100182. /**
  100183. * Returns true if the layer contains information to display, otherwise false.
  100184. * @returns true if the glow layer should be rendered
  100185. */
  100186. EffectLayer.prototype.shouldRender = function () {
  100187. return this.isEnabled && this._shouldRender;
  100188. };
  100189. /**
  100190. * Returns true if the mesh should render, otherwise false.
  100191. * @param mesh The mesh to render
  100192. * @returns true if it should render otherwise false
  100193. */
  100194. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  100195. return true;
  100196. };
  100197. /**
  100198. * Returns true if the mesh should render, otherwise false.
  100199. * @param mesh The mesh to render
  100200. * @returns true if it should render otherwise false
  100201. */
  100202. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  100203. return true;
  100204. };
  100205. /**
  100206. * Renders the submesh passed in parameter to the generation map.
  100207. */
  100208. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  100209. var _this = this;
  100210. if (!this.shouldRender()) {
  100211. return;
  100212. }
  100213. var material = subMesh.getMaterial();
  100214. var mesh = subMesh.getRenderingMesh();
  100215. var scene = this._scene;
  100216. var engine = scene.getEngine();
  100217. if (!material) {
  100218. return;
  100219. }
  100220. // Do not block in blend mode.
  100221. if (material.needAlphaBlendingForMesh(mesh)) {
  100222. return;
  100223. }
  100224. // Culling
  100225. engine.setState(material.backFaceCulling);
  100226. // Managing instances
  100227. var batch = mesh._getInstancesRenderList(subMesh._id);
  100228. if (batch.mustReturn) {
  100229. return;
  100230. }
  100231. // Early Exit per mesh
  100232. if (!this._shouldRenderMesh(mesh)) {
  100233. return;
  100234. }
  100235. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  100236. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  100237. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  100238. engine.enableEffect(this._effectLayerMapGenerationEffect);
  100239. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  100240. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  100241. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  100242. // Alpha test
  100243. if (material && material.needAlphaTesting()) {
  100244. var alphaTexture = material.getAlphaTestTexture();
  100245. if (alphaTexture) {
  100246. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  100247. var textureMatrix = alphaTexture.getTextureMatrix();
  100248. if (textureMatrix) {
  100249. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  100250. }
  100251. }
  100252. }
  100253. // Glow emissive only
  100254. if (this._emissiveTextureAndColor.texture) {
  100255. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  100256. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  100257. }
  100258. // Bones
  100259. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  100260. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  100261. }
  100262. // Morph targets
  100263. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  100264. // Draw
  100265. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  100266. }
  100267. else {
  100268. // Need to reset refresh rate of the main map
  100269. this._mainTexture.resetRefreshCounter();
  100270. }
  100271. };
  100272. /**
  100273. * Rebuild the required buffers.
  100274. * @hidden Internal use only.
  100275. */
  100276. EffectLayer.prototype._rebuild = function () {
  100277. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100278. if (vb) {
  100279. vb._rebuild();
  100280. }
  100281. this._generateIndexBuffer();
  100282. };
  100283. /**
  100284. * Dispose only the render target textures and post process.
  100285. */
  100286. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  100287. this._mainTexture.dispose();
  100288. for (var i = 0; i < this._postProcesses.length; i++) {
  100289. if (this._postProcesses[i]) {
  100290. this._postProcesses[i].dispose();
  100291. }
  100292. }
  100293. this._postProcesses = [];
  100294. for (var i = 0; i < this._textures.length; i++) {
  100295. if (this._textures[i]) {
  100296. this._textures[i].dispose();
  100297. }
  100298. }
  100299. this._textures = [];
  100300. };
  100301. /**
  100302. * Dispose the highlight layer and free resources.
  100303. */
  100304. EffectLayer.prototype.dispose = function () {
  100305. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100306. if (vertexBuffer) {
  100307. vertexBuffer.dispose();
  100308. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  100309. }
  100310. if (this._indexBuffer) {
  100311. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  100312. this._indexBuffer = null;
  100313. }
  100314. // Clean textures and post processes
  100315. this._disposeTextureAndPostProcesses();
  100316. // Remove from scene
  100317. var index = this._scene.effectLayers.indexOf(this, 0);
  100318. if (index > -1) {
  100319. this._scene.effectLayers.splice(index, 1);
  100320. }
  100321. // Callback
  100322. this.onDisposeObservable.notifyObservers(this);
  100323. this.onDisposeObservable.clear();
  100324. this.onBeforeRenderMainTextureObservable.clear();
  100325. this.onBeforeComposeObservable.clear();
  100326. this.onAfterComposeObservable.clear();
  100327. this.onSizeChangedObservable.clear();
  100328. };
  100329. /**
  100330. * Gets the class name of the effect layer
  100331. * @returns the string with the class name of the effect layer
  100332. */
  100333. EffectLayer.prototype.getClassName = function () {
  100334. return "EffectLayer";
  100335. };
  100336. /**
  100337. * Creates an effect layer from parsed effect layer data
  100338. * @param parsedEffectLayer defines effect layer data
  100339. * @param scene defines the current scene
  100340. * @param rootUrl defines the root URL containing the effect layer information
  100341. * @returns a parsed effect Layer
  100342. */
  100343. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  100344. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  100345. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  100346. };
  100347. __decorate([
  100348. BABYLON.serialize()
  100349. ], EffectLayer.prototype, "name", void 0);
  100350. __decorate([
  100351. BABYLON.serializeAsColor4()
  100352. ], EffectLayer.prototype, "neutralColor", void 0);
  100353. __decorate([
  100354. BABYLON.serialize()
  100355. ], EffectLayer.prototype, "isEnabled", void 0);
  100356. __decorate([
  100357. BABYLON.serializeAsCameraReference()
  100358. ], EffectLayer.prototype, "camera", null);
  100359. __decorate([
  100360. BABYLON.serialize()
  100361. ], EffectLayer.prototype, "renderingGroupId", null);
  100362. return EffectLayer;
  100363. }());
  100364. BABYLON.EffectLayer = EffectLayer;
  100365. })(BABYLON || (BABYLON = {}));
  100366. //# sourceMappingURL=babylon.effectLayer.js.map
  100367. var BABYLON;
  100368. (function (BABYLON) {
  100369. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  100370. for (var index = 0; index < this.effectLayers.length; index++) {
  100371. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  100372. return this.effectLayers[index];
  100373. }
  100374. }
  100375. return null;
  100376. };
  100377. /**
  100378. * Special Glow Blur post process only blurring the alpha channel
  100379. * It enforces keeping the most luminous color in the color channel.
  100380. */
  100381. var GlowBlurPostProcess = /** @class */ (function (_super) {
  100382. __extends(GlowBlurPostProcess, _super);
  100383. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  100384. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  100385. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  100386. _this.direction = direction;
  100387. _this.kernel = kernel;
  100388. _this.onApplyObservable.add(function (effect) {
  100389. effect.setFloat2("screenSize", _this.width, _this.height);
  100390. effect.setVector2("direction", _this.direction);
  100391. effect.setFloat("blurWidth", _this.kernel);
  100392. });
  100393. return _this;
  100394. }
  100395. return GlowBlurPostProcess;
  100396. }(BABYLON.PostProcess));
  100397. /**
  100398. * The highlight layer Helps adding a glow effect around a mesh.
  100399. *
  100400. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  100401. * glowy meshes to your scene.
  100402. *
  100403. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  100404. */
  100405. var HighlightLayer = /** @class */ (function (_super) {
  100406. __extends(HighlightLayer, _super);
  100407. /**
  100408. * Instantiates a new highlight Layer and references it to the scene..
  100409. * @param name The name of the layer
  100410. * @param scene The scene to use the layer in
  100411. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  100412. */
  100413. function HighlightLayer(name, scene, options) {
  100414. var _this = _super.call(this, name, scene) || this;
  100415. _this.name = name;
  100416. /**
  100417. * Specifies whether or not the inner glow is ACTIVE in the layer.
  100418. */
  100419. _this.innerGlow = true;
  100420. /**
  100421. * Specifies whether or not the outer glow is ACTIVE in the layer.
  100422. */
  100423. _this.outerGlow = true;
  100424. /**
  100425. * An event triggered when the highlight layer is being blurred.
  100426. */
  100427. _this.onBeforeBlurObservable = new BABYLON.Observable();
  100428. /**
  100429. * An event triggered when the highlight layer has been blurred.
  100430. */
  100431. _this.onAfterBlurObservable = new BABYLON.Observable();
  100432. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  100433. _this._meshes = {};
  100434. _this._excludedMeshes = {};
  100435. _this.neutralColor = HighlightLayer.NeutralColor;
  100436. // Warn on stencil
  100437. if (!_this._engine.isStencilEnable) {
  100438. 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 }");
  100439. }
  100440. // Adapt options
  100441. _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);
  100442. // Initialize the layer
  100443. _this._init({
  100444. alphaBlendingMode: _this._options.alphaBlendingMode,
  100445. camera: _this._options.camera,
  100446. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  100447. mainTextureRatio: _this._options.mainTextureRatio,
  100448. renderingGroupId: _this._options.renderingGroupId
  100449. });
  100450. // Do not render as long as no meshes have been added
  100451. _this._shouldRender = false;
  100452. return _this;
  100453. }
  100454. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  100455. /**
  100456. * Gets the horizontal size of the blur.
  100457. */
  100458. get: function () {
  100459. return this._horizontalBlurPostprocess.kernel;
  100460. },
  100461. /**
  100462. * Specifies the horizontal size of the blur.
  100463. */
  100464. set: function (value) {
  100465. this._horizontalBlurPostprocess.kernel = value;
  100466. },
  100467. enumerable: true,
  100468. configurable: true
  100469. });
  100470. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  100471. /**
  100472. * Gets the vertical size of the blur.
  100473. */
  100474. get: function () {
  100475. return this._verticalBlurPostprocess.kernel;
  100476. },
  100477. /**
  100478. * Specifies the vertical size of the blur.
  100479. */
  100480. set: function (value) {
  100481. this._verticalBlurPostprocess.kernel = value;
  100482. },
  100483. enumerable: true,
  100484. configurable: true
  100485. });
  100486. /**
  100487. * Get the effect name of the layer.
  100488. * @return The effect name
  100489. */
  100490. HighlightLayer.prototype.getEffectName = function () {
  100491. return HighlightLayer.EffectName;
  100492. };
  100493. /**
  100494. * Create the merge effect. This is the shader use to blit the information back
  100495. * to the main canvas at the end of the scene rendering.
  100496. */
  100497. HighlightLayer.prototype._createMergeEffect = function () {
  100498. // Effect
  100499. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  100500. };
  100501. /**
  100502. * Creates the render target textures and post processes used in the highlight layer.
  100503. */
  100504. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  100505. var _this = this;
  100506. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  100507. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  100508. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  100509. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  100510. var textureType = 0;
  100511. if (this._engine.getCaps().textureHalfFloatRender) {
  100512. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100513. }
  100514. else {
  100515. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100516. }
  100517. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  100518. width: blurTextureWidth,
  100519. height: blurTextureHeight
  100520. }, this._scene, false, true, textureType);
  100521. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100522. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100523. this._blurTexture.anisotropicFilteringLevel = 16;
  100524. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  100525. this._blurTexture.renderParticles = false;
  100526. this._blurTexture.ignoreCameraViewport = true;
  100527. this._textures = [this._blurTexture];
  100528. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  100529. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100530. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  100531. effect.setTexture("textureSampler", _this._mainTexture);
  100532. });
  100533. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100534. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  100535. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  100536. });
  100537. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100538. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  100539. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  100540. });
  100541. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  100542. }
  100543. else {
  100544. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  100545. width: blurTextureWidth,
  100546. height: blurTextureHeight
  100547. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100548. this._horizontalBlurPostprocess.width = blurTextureWidth;
  100549. this._horizontalBlurPostprocess.height = blurTextureHeight;
  100550. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  100551. effect.setTexture("textureSampler", _this._mainTexture);
  100552. });
  100553. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  100554. width: blurTextureWidth,
  100555. height: blurTextureHeight
  100556. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100557. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  100558. }
  100559. this._mainTexture.onAfterUnbindObservable.add(function () {
  100560. _this.onBeforeBlurObservable.notifyObservers(_this);
  100561. var internalTexture = _this._blurTexture.getInternalTexture();
  100562. if (internalTexture) {
  100563. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  100564. }
  100565. _this.onAfterBlurObservable.notifyObservers(_this);
  100566. });
  100567. // Prevent autoClear.
  100568. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  100569. };
  100570. /**
  100571. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  100572. */
  100573. HighlightLayer.prototype.needStencil = function () {
  100574. return true;
  100575. };
  100576. /**
  100577. * Checks for the readiness of the element composing the layer.
  100578. * @param subMesh the mesh to check for
  100579. * @param useInstances specify wether or not to use instances to render the mesh
  100580. * @param emissiveTexture the associated emissive texture used to generate the glow
  100581. * @return true if ready otherwise, false
  100582. */
  100583. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  100584. var material = subMesh.getMaterial();
  100585. var mesh = subMesh.getRenderingMesh();
  100586. if (!material || !mesh || !this._meshes) {
  100587. return false;
  100588. }
  100589. var emissiveTexture = null;
  100590. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  100591. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  100592. emissiveTexture = material.emissiveTexture;
  100593. }
  100594. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  100595. };
  100596. /**
  100597. * Implementation specific of rendering the generating effect on the main canvas.
  100598. * @param effect The effect used to render through
  100599. */
  100600. HighlightLayer.prototype._internalRender = function (effect) {
  100601. // Texture
  100602. effect.setTexture("textureSampler", this._blurTexture);
  100603. // Cache
  100604. var engine = this._engine;
  100605. var previousStencilBuffer = engine.getStencilBuffer();
  100606. var previousStencilFunction = engine.getStencilFunction();
  100607. var previousStencilMask = engine.getStencilMask();
  100608. var previousStencilOperationPass = engine.getStencilOperationPass();
  100609. var previousStencilOperationFail = engine.getStencilOperationFail();
  100610. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  100611. var previousStencilReference = engine.getStencilFunctionReference();
  100612. // Stencil operations
  100613. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  100614. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  100615. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  100616. // Draw order
  100617. engine.setStencilMask(0x00);
  100618. engine.setStencilBuffer(true);
  100619. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  100620. // 2 passes inner outer
  100621. if (this.outerGlow) {
  100622. effect.setFloat("offset", 0);
  100623. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  100624. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100625. }
  100626. if (this.innerGlow) {
  100627. effect.setFloat("offset", 1);
  100628. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  100629. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100630. }
  100631. // Restore Cache
  100632. engine.setStencilFunction(previousStencilFunction);
  100633. engine.setStencilMask(previousStencilMask);
  100634. engine.setStencilBuffer(previousStencilBuffer);
  100635. engine.setStencilOperationPass(previousStencilOperationPass);
  100636. engine.setStencilOperationFail(previousStencilOperationFail);
  100637. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  100638. engine.setStencilFunctionReference(previousStencilReference);
  100639. };
  100640. /**
  100641. * Returns true if the layer contains information to display, otherwise false.
  100642. */
  100643. HighlightLayer.prototype.shouldRender = function () {
  100644. if (_super.prototype.shouldRender.call(this)) {
  100645. return this._meshes ? true : false;
  100646. }
  100647. return false;
  100648. };
  100649. /**
  100650. * Returns true if the mesh should render, otherwise false.
  100651. * @param mesh The mesh to render
  100652. * @returns true if it should render otherwise false
  100653. */
  100654. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  100655. // Excluded Mesh
  100656. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  100657. return false;
  100658. }
  100659. ;
  100660. if (!_super.prototype.hasMesh.call(this, mesh)) {
  100661. return false;
  100662. }
  100663. return true;
  100664. };
  100665. /**
  100666. * Sets the required values for both the emissive texture and and the main color.
  100667. */
  100668. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  100669. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  100670. if (highlightLayerMesh) {
  100671. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  100672. }
  100673. else {
  100674. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  100675. }
  100676. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  100677. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  100678. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  100679. }
  100680. else {
  100681. this._emissiveTextureAndColor.texture = null;
  100682. }
  100683. };
  100684. /**
  100685. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  100686. * @param mesh The mesh to exclude from the highlight layer
  100687. */
  100688. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  100689. if (!this._excludedMeshes) {
  100690. return;
  100691. }
  100692. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  100693. if (!meshExcluded) {
  100694. this._excludedMeshes[mesh.uniqueId] = {
  100695. mesh: mesh,
  100696. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  100697. mesh.getEngine().setStencilBuffer(false);
  100698. }),
  100699. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  100700. mesh.getEngine().setStencilBuffer(true);
  100701. }),
  100702. };
  100703. }
  100704. };
  100705. /**
  100706. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  100707. * @param mesh The mesh to highlight
  100708. */
  100709. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  100710. if (!this._excludedMeshes) {
  100711. return;
  100712. }
  100713. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  100714. if (meshExcluded) {
  100715. if (meshExcluded.beforeRender) {
  100716. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  100717. }
  100718. if (meshExcluded.afterRender) {
  100719. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  100720. }
  100721. }
  100722. this._excludedMeshes[mesh.uniqueId] = null;
  100723. };
  100724. /**
  100725. * Determine if a given mesh will be highlighted by the current HighlightLayer
  100726. * @param mesh mesh to test
  100727. * @returns true if the mesh will be highlighted by the current HighlightLayer
  100728. */
  100729. HighlightLayer.prototype.hasMesh = function (mesh) {
  100730. if (!this._meshes) {
  100731. return false;
  100732. }
  100733. if (!_super.prototype.hasMesh.call(this, mesh)) {
  100734. return false;
  100735. }
  100736. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  100737. };
  100738. /**
  100739. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  100740. * @param mesh The mesh to highlight
  100741. * @param color The color of the highlight
  100742. * @param glowEmissiveOnly Extract the glow from the emissive texture
  100743. */
  100744. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  100745. var _this = this;
  100746. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  100747. if (!this._meshes) {
  100748. return;
  100749. }
  100750. var meshHighlight = this._meshes[mesh.uniqueId];
  100751. if (meshHighlight) {
  100752. meshHighlight.color = color;
  100753. }
  100754. else {
  100755. this._meshes[mesh.uniqueId] = {
  100756. mesh: mesh,
  100757. color: color,
  100758. // Lambda required for capture due to Observable this context
  100759. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  100760. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  100761. _this._defaultStencilReference(mesh);
  100762. }
  100763. else {
  100764. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  100765. }
  100766. }),
  100767. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  100768. glowEmissiveOnly: glowEmissiveOnly
  100769. };
  100770. mesh.onDisposeObservable.add(function () {
  100771. _this._disposeMesh(mesh);
  100772. });
  100773. }
  100774. this._shouldRender = true;
  100775. };
  100776. /**
  100777. * Remove a mesh from the highlight layer in order to make it stop glowing.
  100778. * @param mesh The mesh to highlight
  100779. */
  100780. HighlightLayer.prototype.removeMesh = function (mesh) {
  100781. if (!this._meshes) {
  100782. return;
  100783. }
  100784. var meshHighlight = this._meshes[mesh.uniqueId];
  100785. if (meshHighlight) {
  100786. if (meshHighlight.observerHighlight) {
  100787. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  100788. }
  100789. if (meshHighlight.observerDefault) {
  100790. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  100791. }
  100792. delete this._meshes[mesh.uniqueId];
  100793. }
  100794. this._shouldRender = false;
  100795. for (var meshHighlightToCheck in this._meshes) {
  100796. if (this._meshes[meshHighlightToCheck]) {
  100797. this._shouldRender = true;
  100798. break;
  100799. }
  100800. }
  100801. };
  100802. /**
  100803. * Force the stencil to the normal expected value for none glowing parts
  100804. */
  100805. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  100806. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  100807. };
  100808. /**
  100809. * Free any resources and references associated to a mesh.
  100810. * Internal use
  100811. * @param mesh The mesh to free.
  100812. * @hidden
  100813. */
  100814. HighlightLayer.prototype._disposeMesh = function (mesh) {
  100815. this.removeMesh(mesh);
  100816. this.removeExcludedMesh(mesh);
  100817. };
  100818. /**
  100819. * Dispose the highlight layer and free resources.
  100820. */
  100821. HighlightLayer.prototype.dispose = function () {
  100822. if (this._meshes) {
  100823. // Clean mesh references
  100824. for (var id in this._meshes) {
  100825. var meshHighlight = this._meshes[id];
  100826. if (meshHighlight && meshHighlight.mesh) {
  100827. if (meshHighlight.observerHighlight) {
  100828. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  100829. }
  100830. if (meshHighlight.observerDefault) {
  100831. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  100832. }
  100833. }
  100834. }
  100835. this._meshes = null;
  100836. }
  100837. if (this._excludedMeshes) {
  100838. for (var id in this._excludedMeshes) {
  100839. var meshHighlight = this._excludedMeshes[id];
  100840. if (meshHighlight) {
  100841. if (meshHighlight.beforeRender) {
  100842. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  100843. }
  100844. if (meshHighlight.afterRender) {
  100845. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  100846. }
  100847. }
  100848. }
  100849. this._excludedMeshes = null;
  100850. }
  100851. _super.prototype.dispose.call(this);
  100852. };
  100853. /**
  100854. * Gets the class name of the effect layer
  100855. * @returns the string with the class name of the effect layer
  100856. */
  100857. HighlightLayer.prototype.getClassName = function () {
  100858. return "HighlightLayer";
  100859. };
  100860. /**
  100861. * Serializes this Highlight layer
  100862. * @returns a serialized Highlight layer object
  100863. */
  100864. HighlightLayer.prototype.serialize = function () {
  100865. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  100866. serializationObject.customType = "BABYLON.HighlightLayer";
  100867. // Highlighted meshes
  100868. serializationObject.meshes = [];
  100869. if (this._meshes) {
  100870. for (var m in this._meshes) {
  100871. var mesh = this._meshes[m];
  100872. if (mesh) {
  100873. serializationObject.meshes.push({
  100874. glowEmissiveOnly: mesh.glowEmissiveOnly,
  100875. color: mesh.color.asArray(),
  100876. meshId: mesh.mesh.id
  100877. });
  100878. }
  100879. }
  100880. }
  100881. // Excluded meshes
  100882. serializationObject.excludedMeshes = [];
  100883. if (this._excludedMeshes) {
  100884. for (var e in this._excludedMeshes) {
  100885. var excludedMesh = this._excludedMeshes[e];
  100886. if (excludedMesh) {
  100887. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  100888. }
  100889. }
  100890. }
  100891. return serializationObject;
  100892. };
  100893. /**
  100894. * Creates a Highlight layer from parsed Highlight layer data
  100895. * @param parsedHightlightLayer defines the Highlight layer data
  100896. * @param scene defines the current scene
  100897. * @param rootUrl defines the root URL containing the Highlight layer information
  100898. * @returns a parsed Highlight layer
  100899. */
  100900. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  100901. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  100902. var index;
  100903. // Excluded meshes
  100904. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  100905. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  100906. if (mesh) {
  100907. hl.addExcludedMesh(mesh);
  100908. }
  100909. }
  100910. // Included meshes
  100911. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  100912. var highlightedMesh = parsedHightlightLayer.meshes[index];
  100913. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  100914. if (mesh) {
  100915. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  100916. }
  100917. }
  100918. return hl;
  100919. };
  100920. /**
  100921. * Effect Name of the highlight layer.
  100922. */
  100923. HighlightLayer.EffectName = "HighlightLayer";
  100924. /**
  100925. * The neutral color used during the preparation of the glow effect.
  100926. * This is black by default as the blend operation is a blend operation.
  100927. */
  100928. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  100929. /**
  100930. * Stencil value used for glowing meshes.
  100931. */
  100932. HighlightLayer.GlowingMeshStencilReference = 0x02;
  100933. /**
  100934. * Stencil value used for the other meshes in the scene.
  100935. */
  100936. HighlightLayer.NormalMeshStencilReference = 0x01;
  100937. __decorate([
  100938. BABYLON.serialize()
  100939. ], HighlightLayer.prototype, "innerGlow", void 0);
  100940. __decorate([
  100941. BABYLON.serialize()
  100942. ], HighlightLayer.prototype, "outerGlow", void 0);
  100943. __decorate([
  100944. BABYLON.serialize()
  100945. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  100946. __decorate([
  100947. BABYLON.serialize()
  100948. ], HighlightLayer.prototype, "blurVerticalSize", null);
  100949. __decorate([
  100950. BABYLON.serialize("options")
  100951. ], HighlightLayer.prototype, "_options", void 0);
  100952. return HighlightLayer;
  100953. }(BABYLON.EffectLayer));
  100954. BABYLON.HighlightLayer = HighlightLayer;
  100955. })(BABYLON || (BABYLON = {}));
  100956. //# sourceMappingURL=babylon.highlightLayer.js.map
  100957. var BABYLON;
  100958. (function (BABYLON) {
  100959. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  100960. for (var index = 0; index < this.effectLayers.length; index++) {
  100961. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  100962. return this.effectLayers[index];
  100963. }
  100964. }
  100965. return null;
  100966. };
  100967. /**
  100968. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  100969. *
  100970. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  100971. * glowy meshes to your scene.
  100972. *
  100973. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  100974. */
  100975. var GlowLayer = /** @class */ (function (_super) {
  100976. __extends(GlowLayer, _super);
  100977. /**
  100978. * Instantiates a new glow Layer and references it to the scene.
  100979. * @param name The name of the layer
  100980. * @param scene The scene to use the layer in
  100981. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  100982. */
  100983. function GlowLayer(name, scene, options) {
  100984. var _this = _super.call(this, name, scene) || this;
  100985. _this._intensity = 1.0;
  100986. _this._includedOnlyMeshes = [];
  100987. _this._excludedMeshes = [];
  100988. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  100989. // Adapt options
  100990. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  100991. // Initialize the layer
  100992. _this._init({
  100993. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  100994. camera: _this._options.camera,
  100995. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  100996. mainTextureRatio: _this._options.mainTextureRatio,
  100997. renderingGroupId: _this._options.renderingGroupId
  100998. });
  100999. return _this;
  101000. }
  101001. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  101002. /**
  101003. * Gets the kernel size of the blur.
  101004. */
  101005. get: function () {
  101006. return this._horizontalBlurPostprocess1.kernel;
  101007. },
  101008. /**
  101009. * Sets the kernel size of the blur.
  101010. */
  101011. set: function (value) {
  101012. this._horizontalBlurPostprocess1.kernel = value;
  101013. this._verticalBlurPostprocess1.kernel = value;
  101014. this._horizontalBlurPostprocess2.kernel = value;
  101015. this._verticalBlurPostprocess2.kernel = value;
  101016. },
  101017. enumerable: true,
  101018. configurable: true
  101019. });
  101020. Object.defineProperty(GlowLayer.prototype, "intensity", {
  101021. /**
  101022. * Gets the glow intensity.
  101023. */
  101024. get: function () {
  101025. return this._intensity;
  101026. },
  101027. /**
  101028. * Sets the glow intensity.
  101029. */
  101030. set: function (value) {
  101031. this._intensity = value;
  101032. },
  101033. enumerable: true,
  101034. configurable: true
  101035. });
  101036. /**
  101037. * Get the effect name of the layer.
  101038. * @return The effect name
  101039. */
  101040. GlowLayer.prototype.getEffectName = function () {
  101041. return GlowLayer.EffectName;
  101042. };
  101043. /**
  101044. * Create the merge effect. This is the shader use to blit the information back
  101045. * to the main canvas at the end of the scene rendering.
  101046. */
  101047. GlowLayer.prototype._createMergeEffect = function () {
  101048. // Effect
  101049. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  101050. };
  101051. /**
  101052. * Creates the render target textures and post processes used in the glow layer.
  101053. */
  101054. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  101055. var _this = this;
  101056. var blurTextureWidth = this._mainTextureDesiredSize.width;
  101057. var blurTextureHeight = this._mainTextureDesiredSize.height;
  101058. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  101059. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  101060. var textureType = 0;
  101061. if (this._engine.getCaps().textureHalfFloatRender) {
  101062. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  101063. }
  101064. else {
  101065. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101066. }
  101067. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  101068. width: blurTextureWidth,
  101069. height: blurTextureHeight
  101070. }, this._scene, false, true, textureType);
  101071. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101072. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101073. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101074. this._blurTexture1.renderParticles = false;
  101075. this._blurTexture1.ignoreCameraViewport = true;
  101076. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  101077. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  101078. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  101079. width: blurTextureWidth2,
  101080. height: blurTextureHeight2
  101081. }, this._scene, false, true, textureType);
  101082. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101083. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101084. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101085. this._blurTexture2.renderParticles = false;
  101086. this._blurTexture2.ignoreCameraViewport = true;
  101087. this._textures = [this._blurTexture1, this._blurTexture2];
  101088. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  101089. width: blurTextureWidth,
  101090. height: blurTextureHeight
  101091. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101092. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  101093. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  101094. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  101095. effect.setTexture("textureSampler", _this._mainTexture);
  101096. });
  101097. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  101098. width: blurTextureWidth,
  101099. height: blurTextureHeight
  101100. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101101. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  101102. width: blurTextureWidth2,
  101103. height: blurTextureHeight2
  101104. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101105. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  101106. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  101107. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  101108. effect.setTexture("textureSampler", _this._blurTexture1);
  101109. });
  101110. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  101111. width: blurTextureWidth2,
  101112. height: blurTextureHeight2
  101113. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101114. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  101115. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  101116. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  101117. this._mainTexture.samples = this._options.mainTextureSamples;
  101118. this._mainTexture.onAfterUnbindObservable.add(function () {
  101119. var internalTexture = _this._blurTexture1.getInternalTexture();
  101120. if (internalTexture) {
  101121. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  101122. internalTexture = _this._blurTexture2.getInternalTexture();
  101123. if (internalTexture) {
  101124. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  101125. }
  101126. }
  101127. });
  101128. // Prevent autoClear.
  101129. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  101130. };
  101131. /**
  101132. * Checks for the readiness of the element composing the layer.
  101133. * @param subMesh the mesh to check for
  101134. * @param useInstances specify wether or not to use instances to render the mesh
  101135. * @param emissiveTexture the associated emissive texture used to generate the glow
  101136. * @return true if ready otherwise, false
  101137. */
  101138. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  101139. var material = subMesh.getMaterial();
  101140. var mesh = subMesh.getRenderingMesh();
  101141. if (!material || !mesh) {
  101142. return false;
  101143. }
  101144. var emissiveTexture = material.emissiveTexture;
  101145. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  101146. };
  101147. /**
  101148. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  101149. */
  101150. GlowLayer.prototype.needStencil = function () {
  101151. return false;
  101152. };
  101153. /**
  101154. * Implementation specific of rendering the generating effect on the main canvas.
  101155. * @param effect The effect used to render through
  101156. */
  101157. GlowLayer.prototype._internalRender = function (effect) {
  101158. // Texture
  101159. effect.setTexture("textureSampler", this._blurTexture1);
  101160. effect.setTexture("textureSampler2", this._blurTexture2);
  101161. effect.setFloat("offset", this._intensity);
  101162. // Cache
  101163. var engine = this._engine;
  101164. var previousStencilBuffer = engine.getStencilBuffer();
  101165. // Draw order
  101166. engine.setStencilBuffer(false);
  101167. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  101168. // Draw order
  101169. engine.setStencilBuffer(previousStencilBuffer);
  101170. };
  101171. /**
  101172. * Sets the required values for both the emissive texture and and the main color.
  101173. */
  101174. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  101175. var textureLevel = 1.0;
  101176. if (this.customEmissiveTextureSelector) {
  101177. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  101178. }
  101179. else {
  101180. if (material) {
  101181. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  101182. if (this._emissiveTextureAndColor.texture) {
  101183. textureLevel = this._emissiveTextureAndColor.texture.level;
  101184. }
  101185. }
  101186. else {
  101187. this._emissiveTextureAndColor.texture = null;
  101188. }
  101189. }
  101190. if (this.customEmissiveColorSelector) {
  101191. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  101192. }
  101193. else {
  101194. if (material.emissiveColor) {
  101195. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  101196. }
  101197. else {
  101198. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  101199. }
  101200. }
  101201. };
  101202. /**
  101203. * Returns true if the mesh should render, otherwise false.
  101204. * @param mesh The mesh to render
  101205. * @returns true if it should render otherwise false
  101206. */
  101207. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  101208. return this.hasMesh(mesh);
  101209. };
  101210. /**
  101211. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  101212. * @param mesh The mesh to exclude from the glow layer
  101213. */
  101214. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  101215. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  101216. this._excludedMeshes.push(mesh.uniqueId);
  101217. }
  101218. };
  101219. /**
  101220. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  101221. * @param mesh The mesh to remove
  101222. */
  101223. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  101224. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  101225. if (index !== -1) {
  101226. this._excludedMeshes.splice(index, 1);
  101227. }
  101228. };
  101229. /**
  101230. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  101231. * @param mesh The mesh to include in the glow layer
  101232. */
  101233. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  101234. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  101235. this._includedOnlyMeshes.push(mesh.uniqueId);
  101236. }
  101237. };
  101238. /**
  101239. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  101240. * @param mesh The mesh to remove
  101241. */
  101242. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  101243. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  101244. if (index !== -1) {
  101245. this._includedOnlyMeshes.splice(index, 1);
  101246. }
  101247. };
  101248. /**
  101249. * Determine if a given mesh will be used in the glow layer
  101250. * @param mesh The mesh to test
  101251. * @returns true if the mesh will be highlighted by the current glow layer
  101252. */
  101253. GlowLayer.prototype.hasMesh = function (mesh) {
  101254. if (!_super.prototype.hasMesh.call(this, mesh)) {
  101255. return false;
  101256. }
  101257. // Included Mesh
  101258. if (this._includedOnlyMeshes.length) {
  101259. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  101260. }
  101261. ;
  101262. // Excluded Mesh
  101263. if (this._excludedMeshes.length) {
  101264. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  101265. }
  101266. ;
  101267. return true;
  101268. };
  101269. /**
  101270. * Free any resources and references associated to a mesh.
  101271. * Internal use
  101272. * @param mesh The mesh to free.
  101273. * @hidden
  101274. */
  101275. GlowLayer.prototype._disposeMesh = function (mesh) {
  101276. this.removeIncludedOnlyMesh(mesh);
  101277. this.removeExcludedMesh(mesh);
  101278. };
  101279. /**
  101280. * Gets the class name of the effect layer
  101281. * @returns the string with the class name of the effect layer
  101282. */
  101283. GlowLayer.prototype.getClassName = function () {
  101284. return "GlowLayer";
  101285. };
  101286. /**
  101287. * Serializes this glow layer
  101288. * @returns a serialized glow layer object
  101289. */
  101290. GlowLayer.prototype.serialize = function () {
  101291. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101292. serializationObject.customType = "BABYLON.GlowLayer";
  101293. var index;
  101294. // Included meshes
  101295. serializationObject.includedMeshes = [];
  101296. if (this._includedOnlyMeshes.length) {
  101297. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  101298. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  101299. if (mesh) {
  101300. serializationObject.includedMeshes.push(mesh.id);
  101301. }
  101302. }
  101303. }
  101304. // Excluded meshes
  101305. serializationObject.excludedMeshes = [];
  101306. if (this._excludedMeshes.length) {
  101307. for (index = 0; index < this._excludedMeshes.length; index++) {
  101308. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  101309. if (mesh) {
  101310. serializationObject.excludedMeshes.push(mesh.id);
  101311. }
  101312. }
  101313. }
  101314. return serializationObject;
  101315. };
  101316. /**
  101317. * Creates a Glow Layer from parsed glow layer data
  101318. * @param parsedGlowLayer defines glow layer data
  101319. * @param scene defines the current scene
  101320. * @param rootUrl defines the root URL containing the glow layer information
  101321. * @returns a parsed Glow Layer
  101322. */
  101323. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  101324. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  101325. var index;
  101326. // Excluded meshes
  101327. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  101328. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  101329. if (mesh) {
  101330. gl.addExcludedMesh(mesh);
  101331. }
  101332. }
  101333. // Included meshes
  101334. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  101335. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  101336. if (mesh) {
  101337. gl.addIncludedOnlyMesh(mesh);
  101338. }
  101339. }
  101340. return gl;
  101341. };
  101342. /**
  101343. * Effect Name of the layer.
  101344. */
  101345. GlowLayer.EffectName = "GlowLayer";
  101346. /**
  101347. * The default blur kernel size used for the glow.
  101348. */
  101349. GlowLayer.DefaultBlurKernelSize = 32;
  101350. /**
  101351. * The default texture size ratio used for the glow.
  101352. */
  101353. GlowLayer.DefaultTextureRatio = 0.5;
  101354. __decorate([
  101355. BABYLON.serialize()
  101356. ], GlowLayer.prototype, "blurKernelSize", null);
  101357. __decorate([
  101358. BABYLON.serialize()
  101359. ], GlowLayer.prototype, "intensity", null);
  101360. __decorate([
  101361. BABYLON.serialize("options")
  101362. ], GlowLayer.prototype, "_options", void 0);
  101363. return GlowLayer;
  101364. }(BABYLON.EffectLayer));
  101365. BABYLON.GlowLayer = GlowLayer;
  101366. })(BABYLON || (BABYLON = {}));
  101367. //# sourceMappingURL=babylon.glowLayer.js.map
  101368. var BABYLON;
  101369. (function (BABYLON) {
  101370. /**
  101371. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  101372. */
  101373. var AssetTaskState;
  101374. (function (AssetTaskState) {
  101375. /**
  101376. * Initialization
  101377. */
  101378. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  101379. /**
  101380. * Running
  101381. */
  101382. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  101383. /**
  101384. * Done
  101385. */
  101386. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  101387. /**
  101388. * Error
  101389. */
  101390. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  101391. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  101392. /**
  101393. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  101394. */
  101395. var AbstractAssetTask = /** @class */ (function () {
  101396. /**
  101397. * Creates a new {BABYLON.AssetsManager}
  101398. * @param name defines the name of the task
  101399. */
  101400. function AbstractAssetTask(
  101401. /**
  101402. * Task name
  101403. */ name) {
  101404. this.name = name;
  101405. this._isCompleted = false;
  101406. this._taskState = AssetTaskState.INIT;
  101407. }
  101408. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  101409. /**
  101410. * Get if the task is completed
  101411. */
  101412. get: function () {
  101413. return this._isCompleted;
  101414. },
  101415. enumerable: true,
  101416. configurable: true
  101417. });
  101418. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  101419. /**
  101420. * Gets the current state of the task
  101421. */
  101422. get: function () {
  101423. return this._taskState;
  101424. },
  101425. enumerable: true,
  101426. configurable: true
  101427. });
  101428. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  101429. /**
  101430. * Gets the current error object (if task is in error)
  101431. */
  101432. get: function () {
  101433. return this._errorObject;
  101434. },
  101435. enumerable: true,
  101436. configurable: true
  101437. });
  101438. /**
  101439. * Internal only
  101440. * @hidden
  101441. */
  101442. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  101443. if (this._errorObject) {
  101444. return;
  101445. }
  101446. this._errorObject = {
  101447. message: message,
  101448. exception: exception
  101449. };
  101450. };
  101451. /**
  101452. * Execute the current task
  101453. * @param scene defines the scene where you want your assets to be loaded
  101454. * @param onSuccess is a callback called when the task is successfully executed
  101455. * @param onError is a callback called if an error occurs
  101456. */
  101457. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  101458. var _this = this;
  101459. this._taskState = AssetTaskState.RUNNING;
  101460. this.runTask(scene, function () {
  101461. _this.onDoneCallback(onSuccess, onError);
  101462. }, function (msg, exception) {
  101463. _this.onErrorCallback(onError, msg, exception);
  101464. });
  101465. };
  101466. /**
  101467. * Execute the current task
  101468. * @param scene defines the scene where you want your assets to be loaded
  101469. * @param onSuccess is a callback called when the task is successfully executed
  101470. * @param onError is a callback called if an error occurs
  101471. */
  101472. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101473. throw new Error("runTask is not implemented");
  101474. };
  101475. /**
  101476. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  101477. * This can be used with failed tasks that have the reason for failure fixed.
  101478. */
  101479. AbstractAssetTask.prototype.reset = function () {
  101480. this._taskState = AssetTaskState.INIT;
  101481. };
  101482. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  101483. this._taskState = AssetTaskState.ERROR;
  101484. this._errorObject = {
  101485. message: message,
  101486. exception: exception
  101487. };
  101488. if (this.onError) {
  101489. this.onError(this, message, exception);
  101490. }
  101491. onError();
  101492. };
  101493. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  101494. try {
  101495. this._taskState = AssetTaskState.DONE;
  101496. this._isCompleted = true;
  101497. if (this.onSuccess) {
  101498. this.onSuccess(this);
  101499. }
  101500. onSuccess();
  101501. }
  101502. catch (e) {
  101503. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  101504. }
  101505. };
  101506. return AbstractAssetTask;
  101507. }());
  101508. BABYLON.AbstractAssetTask = AbstractAssetTask;
  101509. /**
  101510. * Class used to share progress information about assets loading
  101511. */
  101512. var AssetsProgressEvent = /** @class */ (function () {
  101513. /**
  101514. * Creates a {BABYLON.AssetsProgressEvent}
  101515. * @param remainingCount defines the number of remaining tasks to process
  101516. * @param totalCount defines the total number of tasks
  101517. * @param task defines the task that was just processed
  101518. */
  101519. function AssetsProgressEvent(remainingCount, totalCount, task) {
  101520. this.remainingCount = remainingCount;
  101521. this.totalCount = totalCount;
  101522. this.task = task;
  101523. }
  101524. return AssetsProgressEvent;
  101525. }());
  101526. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  101527. /**
  101528. * Define a task used by {BABYLON.AssetsManager} to load meshes
  101529. */
  101530. var MeshAssetTask = /** @class */ (function (_super) {
  101531. __extends(MeshAssetTask, _super);
  101532. /**
  101533. * Creates a new {BABYLON.MeshAssetTask}
  101534. * @param name defines the name of the task
  101535. * @param meshesNames defines the list of mesh's names you want to load
  101536. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  101537. * @param sceneFilename defines the filename of the scene to load from
  101538. */
  101539. function MeshAssetTask(
  101540. /**
  101541. * Defines the name of the task
  101542. */
  101543. name,
  101544. /**
  101545. * Defines the list of mesh's names you want to load
  101546. */
  101547. meshesNames,
  101548. /**
  101549. * Defines the root url to use as a base to load your meshes and associated resources
  101550. */
  101551. rootUrl,
  101552. /**
  101553. * Defines the filename of the scene to load from
  101554. */
  101555. sceneFilename) {
  101556. var _this = _super.call(this, name) || this;
  101557. _this.name = name;
  101558. _this.meshesNames = meshesNames;
  101559. _this.rootUrl = rootUrl;
  101560. _this.sceneFilename = sceneFilename;
  101561. return _this;
  101562. }
  101563. /**
  101564. * Execute the current task
  101565. * @param scene defines the scene where you want your assets to be loaded
  101566. * @param onSuccess is a callback called when the task is successfully executed
  101567. * @param onError is a callback called if an error occurs
  101568. */
  101569. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101570. var _this = this;
  101571. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  101572. _this.loadedMeshes = meshes;
  101573. _this.loadedParticleSystems = particleSystems;
  101574. _this.loadedSkeletons = skeletons;
  101575. onSuccess();
  101576. }, null, function (scene, message, exception) {
  101577. onError(message, exception);
  101578. });
  101579. };
  101580. return MeshAssetTask;
  101581. }(AbstractAssetTask));
  101582. BABYLON.MeshAssetTask = MeshAssetTask;
  101583. /**
  101584. * Define a task used by {BABYLON.AssetsManager} to load text content
  101585. */
  101586. var TextFileAssetTask = /** @class */ (function (_super) {
  101587. __extends(TextFileAssetTask, _super);
  101588. /**
  101589. * Creates a new TextFileAssetTask object
  101590. * @param name defines the name of the task
  101591. * @param url defines the location of the file to load
  101592. */
  101593. function TextFileAssetTask(
  101594. /**
  101595. * Defines the name of the task
  101596. */
  101597. name,
  101598. /**
  101599. * Defines the location of the file to load
  101600. */
  101601. url) {
  101602. var _this = _super.call(this, name) || this;
  101603. _this.name = name;
  101604. _this.url = url;
  101605. return _this;
  101606. }
  101607. /**
  101608. * Execute the current task
  101609. * @param scene defines the scene where you want your assets to be loaded
  101610. * @param onSuccess is a callback called when the task is successfully executed
  101611. * @param onError is a callback called if an error occurs
  101612. */
  101613. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101614. var _this = this;
  101615. scene._loadFile(this.url, function (data) {
  101616. _this.text = data;
  101617. onSuccess();
  101618. }, undefined, false, false, function (request, exception) {
  101619. if (request) {
  101620. onError(request.status + " " + request.statusText, exception);
  101621. }
  101622. });
  101623. };
  101624. return TextFileAssetTask;
  101625. }(AbstractAssetTask));
  101626. BABYLON.TextFileAssetTask = TextFileAssetTask;
  101627. /**
  101628. * Define a task used by {BABYLON.AssetsManager} to load binary data
  101629. */
  101630. var BinaryFileAssetTask = /** @class */ (function (_super) {
  101631. __extends(BinaryFileAssetTask, _super);
  101632. /**
  101633. * Creates a new BinaryFileAssetTask object
  101634. * @param name defines the name of the new task
  101635. * @param url defines the location of the file to load
  101636. */
  101637. function BinaryFileAssetTask(
  101638. /**
  101639. * Defines the name of the task
  101640. */
  101641. name,
  101642. /**
  101643. * Defines the location of the file to load
  101644. */
  101645. url) {
  101646. var _this = _super.call(this, name) || this;
  101647. _this.name = name;
  101648. _this.url = url;
  101649. return _this;
  101650. }
  101651. /**
  101652. * Execute the current task
  101653. * @param scene defines the scene where you want your assets to be loaded
  101654. * @param onSuccess is a callback called when the task is successfully executed
  101655. * @param onError is a callback called if an error occurs
  101656. */
  101657. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101658. var _this = this;
  101659. scene._loadFile(this.url, function (data) {
  101660. _this.data = data;
  101661. onSuccess();
  101662. }, undefined, true, true, function (request, exception) {
  101663. if (request) {
  101664. onError(request.status + " " + request.statusText, exception);
  101665. }
  101666. });
  101667. };
  101668. return BinaryFileAssetTask;
  101669. }(AbstractAssetTask));
  101670. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  101671. /**
  101672. * Define a task used by {BABYLON.AssetsManager} to load images
  101673. */
  101674. var ImageAssetTask = /** @class */ (function (_super) {
  101675. __extends(ImageAssetTask, _super);
  101676. /**
  101677. * Creates a new ImageAssetTask
  101678. * @param name defines the name of the task
  101679. * @param url defines the location of the image to load
  101680. */
  101681. function ImageAssetTask(
  101682. /**
  101683. * Defines the name of the task
  101684. */
  101685. name,
  101686. /**
  101687. * Defines the location of the image to load
  101688. */
  101689. url) {
  101690. var _this = _super.call(this, name) || this;
  101691. _this.name = name;
  101692. _this.url = url;
  101693. return _this;
  101694. }
  101695. /**
  101696. * Execute the current task
  101697. * @param scene defines the scene where you want your assets to be loaded
  101698. * @param onSuccess is a callback called when the task is successfully executed
  101699. * @param onError is a callback called if an error occurs
  101700. */
  101701. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101702. var _this = this;
  101703. var img = new Image();
  101704. BABYLON.Tools.SetCorsBehavior(this.url, img);
  101705. img.onload = function () {
  101706. _this.image = img;
  101707. onSuccess();
  101708. };
  101709. img.onerror = function (err) {
  101710. onError("Error loading image", err);
  101711. };
  101712. img.src = this.url;
  101713. };
  101714. return ImageAssetTask;
  101715. }(AbstractAssetTask));
  101716. BABYLON.ImageAssetTask = ImageAssetTask;
  101717. /**
  101718. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  101719. */
  101720. var TextureAssetTask = /** @class */ (function (_super) {
  101721. __extends(TextureAssetTask, _super);
  101722. /**
  101723. * Creates a new TextureAssetTask object
  101724. * @param name defines the name of the task
  101725. * @param url defines the location of the file to load
  101726. * @param noMipmap defines if mipmap should not be generated (default is false)
  101727. * @param invertY defines if texture must be inverted on Y axis (default is false)
  101728. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  101729. */
  101730. function TextureAssetTask(
  101731. /**
  101732. * Defines the name of the task
  101733. */
  101734. name,
  101735. /**
  101736. * Defines the location of the file to load
  101737. */
  101738. url,
  101739. /**
  101740. * Defines if mipmap should not be generated (default is false)
  101741. */
  101742. noMipmap,
  101743. /**
  101744. * Defines if texture must be inverted on Y axis (default is false)
  101745. */
  101746. invertY,
  101747. /**
  101748. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  101749. */
  101750. samplingMode) {
  101751. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  101752. var _this = _super.call(this, name) || this;
  101753. _this.name = name;
  101754. _this.url = url;
  101755. _this.noMipmap = noMipmap;
  101756. _this.invertY = invertY;
  101757. _this.samplingMode = samplingMode;
  101758. return _this;
  101759. }
  101760. /**
  101761. * Execute the current task
  101762. * @param scene defines the scene where you want your assets to be loaded
  101763. * @param onSuccess is a callback called when the task is successfully executed
  101764. * @param onError is a callback called if an error occurs
  101765. */
  101766. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101767. var onload = function () {
  101768. onSuccess();
  101769. };
  101770. var onerror = function (message, exception) {
  101771. onError(message, exception);
  101772. };
  101773. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  101774. };
  101775. return TextureAssetTask;
  101776. }(AbstractAssetTask));
  101777. BABYLON.TextureAssetTask = TextureAssetTask;
  101778. /**
  101779. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  101780. */
  101781. var CubeTextureAssetTask = /** @class */ (function (_super) {
  101782. __extends(CubeTextureAssetTask, _super);
  101783. /**
  101784. * Creates a new CubeTextureAssetTask
  101785. * @param name defines the name of the task
  101786. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  101787. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  101788. * @param noMipmap defines if mipmaps should not be generated (default is false)
  101789. * @param files defines the explicit list of files (undefined by default)
  101790. */
  101791. function CubeTextureAssetTask(
  101792. /**
  101793. * Defines the name of the task
  101794. */
  101795. name,
  101796. /**
  101797. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  101798. */
  101799. url,
  101800. /**
  101801. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  101802. */
  101803. extensions,
  101804. /**
  101805. * Defines if mipmaps should not be generated (default is false)
  101806. */
  101807. noMipmap,
  101808. /**
  101809. * Defines the explicit list of files (undefined by default)
  101810. */
  101811. files) {
  101812. var _this = _super.call(this, name) || this;
  101813. _this.name = name;
  101814. _this.url = url;
  101815. _this.extensions = extensions;
  101816. _this.noMipmap = noMipmap;
  101817. _this.files = files;
  101818. return _this;
  101819. }
  101820. /**
  101821. * Execute the current task
  101822. * @param scene defines the scene where you want your assets to be loaded
  101823. * @param onSuccess is a callback called when the task is successfully executed
  101824. * @param onError is a callback called if an error occurs
  101825. */
  101826. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101827. var onload = function () {
  101828. onSuccess();
  101829. };
  101830. var onerror = function (message, exception) {
  101831. onError(message, exception);
  101832. };
  101833. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  101834. };
  101835. return CubeTextureAssetTask;
  101836. }(AbstractAssetTask));
  101837. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  101838. /**
  101839. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  101840. */
  101841. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  101842. __extends(HDRCubeTextureAssetTask, _super);
  101843. /**
  101844. * Creates a new HDRCubeTextureAssetTask object
  101845. * @param name defines the name of the task
  101846. * @param url defines the location of the file to load
  101847. * @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.
  101848. * @param noMipmap defines if mipmaps should not be generated (default is false)
  101849. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  101850. * @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)
  101851. * @param reserved Internal use only
  101852. */
  101853. function HDRCubeTextureAssetTask(
  101854. /**
  101855. * Defines the name of the task
  101856. */
  101857. name,
  101858. /**
  101859. * Defines the location of the file to load
  101860. */
  101861. url,
  101862. /**
  101863. * Defines the desired size (the more it increases the longer the generation will be)
  101864. */
  101865. size,
  101866. /**
  101867. * Defines if mipmaps should not be generated (default is false)
  101868. */
  101869. noMipmap,
  101870. /**
  101871. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  101872. */
  101873. generateHarmonics,
  101874. /**
  101875. * 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)
  101876. */
  101877. gammaSpace,
  101878. /**
  101879. * Internal Use Only
  101880. */
  101881. reserved) {
  101882. if (noMipmap === void 0) { noMipmap = false; }
  101883. if (generateHarmonics === void 0) { generateHarmonics = true; }
  101884. if (gammaSpace === void 0) { gammaSpace = false; }
  101885. if (reserved === void 0) { reserved = false; }
  101886. var _this = _super.call(this, name) || this;
  101887. _this.name = name;
  101888. _this.url = url;
  101889. _this.size = size;
  101890. _this.noMipmap = noMipmap;
  101891. _this.generateHarmonics = generateHarmonics;
  101892. _this.gammaSpace = gammaSpace;
  101893. _this.reserved = reserved;
  101894. return _this;
  101895. }
  101896. /**
  101897. * Execute the current task
  101898. * @param scene defines the scene where you want your assets to be loaded
  101899. * @param onSuccess is a callback called when the task is successfully executed
  101900. * @param onError is a callback called if an error occurs
  101901. */
  101902. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  101903. var onload = function () {
  101904. onSuccess();
  101905. };
  101906. var onerror = function (message, exception) {
  101907. onError(message, exception);
  101908. };
  101909. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  101910. };
  101911. return HDRCubeTextureAssetTask;
  101912. }(AbstractAssetTask));
  101913. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  101914. /**
  101915. * This class can be used to easily import assets into a scene
  101916. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  101917. */
  101918. var AssetsManager = /** @class */ (function () {
  101919. /**
  101920. * Creates a new AssetsManager
  101921. * @param scene defines the scene to work on
  101922. */
  101923. function AssetsManager(scene) {
  101924. this._isLoading = false;
  101925. this._tasks = new Array();
  101926. this._waitingTasksCount = 0;
  101927. this._totalTasksCount = 0;
  101928. /**
  101929. * Observable called when all tasks are processed
  101930. */
  101931. this.onTaskSuccessObservable = new BABYLON.Observable();
  101932. /**
  101933. * Observable called when a task had an error
  101934. */
  101935. this.onTaskErrorObservable = new BABYLON.Observable();
  101936. /**
  101937. * Observable called when a task is successful
  101938. */
  101939. this.onTasksDoneObservable = new BABYLON.Observable();
  101940. /**
  101941. * Observable called when a task is done (whatever the result is)
  101942. */
  101943. this.onProgressObservable = new BABYLON.Observable();
  101944. /**
  101945. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  101946. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  101947. */
  101948. this.useDefaultLoadingScreen = true;
  101949. this._scene = scene;
  101950. }
  101951. /**
  101952. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  101953. * @param taskName defines the name of the new task
  101954. * @param meshesNames defines the name of meshes to load
  101955. * @param rootUrl defines the root url to use to locate files
  101956. * @param sceneFilename defines the filename of the scene file
  101957. * @returns a new {BABYLON.MeshAssetTask} object
  101958. */
  101959. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  101960. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  101961. this._tasks.push(task);
  101962. return task;
  101963. };
  101964. /**
  101965. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  101966. * @param taskName defines the name of the new task
  101967. * @param url defines the url of the file to load
  101968. * @returns a new {BABYLON.TextFileAssetTask} object
  101969. */
  101970. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  101971. var task = new TextFileAssetTask(taskName, url);
  101972. this._tasks.push(task);
  101973. return task;
  101974. };
  101975. /**
  101976. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  101977. * @param taskName defines the name of the new task
  101978. * @param url defines the url of the file to load
  101979. * @returns a new {BABYLON.BinaryFileAssetTask} object
  101980. */
  101981. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  101982. var task = new BinaryFileAssetTask(taskName, url);
  101983. this._tasks.push(task);
  101984. return task;
  101985. };
  101986. /**
  101987. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  101988. * @param taskName defines the name of the new task
  101989. * @param url defines the url of the file to load
  101990. * @returns a new {BABYLON.ImageAssetTask} object
  101991. */
  101992. AssetsManager.prototype.addImageTask = function (taskName, url) {
  101993. var task = new ImageAssetTask(taskName, url);
  101994. this._tasks.push(task);
  101995. return task;
  101996. };
  101997. /**
  101998. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  101999. * @param taskName defines the name of the new task
  102000. * @param url defines the url of the file to load
  102001. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102002. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  102003. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  102004. * @returns a new {BABYLON.TextureAssetTask} object
  102005. */
  102006. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  102007. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  102008. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  102009. this._tasks.push(task);
  102010. return task;
  102011. };
  102012. /**
  102013. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  102014. * @param taskName defines the name of the new task
  102015. * @param url defines the url of the file to load
  102016. * @param extensions defines the extension to use to load the cube map (can be null)
  102017. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102018. * @param files defines the list of files to load (can be null)
  102019. * @returns a new {BABYLON.CubeTextureAssetTask} object
  102020. */
  102021. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  102022. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  102023. this._tasks.push(task);
  102024. return task;
  102025. };
  102026. /**
  102027. *
  102028. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  102029. * @param taskName defines the name of the new task
  102030. * @param url defines the url of the file to load
  102031. * @param size defines the size you want for the cubemap (can be null)
  102032. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102033. * @param generateHarmonics defines if you want to automatically generate (true by default)
  102034. * @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)
  102035. * @param reserved Internal use only
  102036. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  102037. */
  102038. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  102039. if (noMipmap === void 0) { noMipmap = false; }
  102040. if (generateHarmonics === void 0) { generateHarmonics = true; }
  102041. if (gammaSpace === void 0) { gammaSpace = false; }
  102042. if (reserved === void 0) { reserved = false; }
  102043. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  102044. this._tasks.push(task);
  102045. return task;
  102046. };
  102047. /**
  102048. * Remove a task from the assets manager.
  102049. * @param task the task to remove
  102050. */
  102051. AssetsManager.prototype.removeTask = function (task) {
  102052. var index = this._tasks.indexOf(task);
  102053. if (index > -1) {
  102054. this._tasks.splice(index, 1);
  102055. }
  102056. };
  102057. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  102058. this._waitingTasksCount--;
  102059. try {
  102060. if (this.onProgress) {
  102061. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  102062. }
  102063. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  102064. }
  102065. catch (e) {
  102066. BABYLON.Tools.Error("Error running progress callbacks.");
  102067. console.log(e);
  102068. }
  102069. if (this._waitingTasksCount === 0) {
  102070. try {
  102071. if (this.onFinish) {
  102072. this.onFinish(this._tasks);
  102073. }
  102074. // Let's remove successfull tasks
  102075. var currentTasks = this._tasks.slice();
  102076. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  102077. var task = currentTasks_1[_i];
  102078. if (task.taskState === AssetTaskState.DONE) {
  102079. var index = this._tasks.indexOf(task);
  102080. if (index > -1) {
  102081. this._tasks.splice(index, 1);
  102082. }
  102083. }
  102084. }
  102085. this.onTasksDoneObservable.notifyObservers(this._tasks);
  102086. }
  102087. catch (e) {
  102088. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  102089. console.log(e);
  102090. }
  102091. this._isLoading = false;
  102092. this._scene.getEngine().hideLoadingUI();
  102093. }
  102094. };
  102095. AssetsManager.prototype._runTask = function (task) {
  102096. var _this = this;
  102097. var done = function () {
  102098. try {
  102099. if (_this.onTaskSuccess) {
  102100. _this.onTaskSuccess(task);
  102101. }
  102102. _this.onTaskSuccessObservable.notifyObservers(task);
  102103. _this._decreaseWaitingTasksCount(task);
  102104. }
  102105. catch (e) {
  102106. error("Error executing task success callbacks", e);
  102107. }
  102108. };
  102109. var error = function (message, exception) {
  102110. task._setErrorObject(message, exception);
  102111. if (_this.onTaskError) {
  102112. _this.onTaskError(task);
  102113. }
  102114. _this.onTaskErrorObservable.notifyObservers(task);
  102115. _this._decreaseWaitingTasksCount(task);
  102116. };
  102117. task.run(this._scene, done, error);
  102118. };
  102119. /**
  102120. * Reset the {BABYLON.AssetsManager} and remove all tasks
  102121. * @return the current instance of the {BABYLON.AssetsManager}
  102122. */
  102123. AssetsManager.prototype.reset = function () {
  102124. this._isLoading = false;
  102125. this._tasks = new Array();
  102126. return this;
  102127. };
  102128. /**
  102129. * Start the loading process
  102130. * @return the current instance of the {BABYLON.AssetsManager}
  102131. */
  102132. AssetsManager.prototype.load = function () {
  102133. if (this._isLoading) {
  102134. return this;
  102135. }
  102136. this._isLoading = true;
  102137. this._waitingTasksCount = this._tasks.length;
  102138. this._totalTasksCount = this._tasks.length;
  102139. if (this._waitingTasksCount === 0) {
  102140. this._isLoading = false;
  102141. if (this.onFinish) {
  102142. this.onFinish(this._tasks);
  102143. }
  102144. this.onTasksDoneObservable.notifyObservers(this._tasks);
  102145. return this;
  102146. }
  102147. if (this.useDefaultLoadingScreen) {
  102148. this._scene.getEngine().displayLoadingUI();
  102149. }
  102150. for (var index = 0; index < this._tasks.length; index++) {
  102151. var task = this._tasks[index];
  102152. if (task.taskState === AssetTaskState.INIT) {
  102153. this._runTask(task);
  102154. }
  102155. }
  102156. return this;
  102157. };
  102158. return AssetsManager;
  102159. }());
  102160. BABYLON.AssetsManager = AssetsManager;
  102161. })(BABYLON || (BABYLON = {}));
  102162. //# sourceMappingURL=babylon.assetsManager.js.map
  102163. var BABYLON;
  102164. (function (BABYLON) {
  102165. var serializedGeometries = [];
  102166. var serializeGeometry = function (geometry, serializationGeometries) {
  102167. if (serializedGeometries[geometry.id]) {
  102168. return;
  102169. }
  102170. if (geometry.doNotSerialize) {
  102171. return;
  102172. }
  102173. if (geometry instanceof BABYLON.BoxGeometry) {
  102174. serializationGeometries.boxes.push(geometry.serialize());
  102175. }
  102176. else if (geometry instanceof BABYLON.SphereGeometry) {
  102177. serializationGeometries.spheres.push(geometry.serialize());
  102178. }
  102179. else if (geometry instanceof BABYLON.CylinderGeometry) {
  102180. serializationGeometries.cylinders.push(geometry.serialize());
  102181. }
  102182. else if (geometry instanceof BABYLON.TorusGeometry) {
  102183. serializationGeometries.toruses.push(geometry.serialize());
  102184. }
  102185. else if (geometry instanceof BABYLON.GroundGeometry) {
  102186. serializationGeometries.grounds.push(geometry.serialize());
  102187. }
  102188. else if (geometry instanceof BABYLON.Plane) {
  102189. serializationGeometries.planes.push(geometry.serialize());
  102190. }
  102191. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  102192. serializationGeometries.torusKnots.push(geometry.serialize());
  102193. }
  102194. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  102195. throw new Error("Unknown primitive type");
  102196. }
  102197. else {
  102198. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  102199. }
  102200. serializedGeometries[geometry.id] = true;
  102201. };
  102202. var serializeMesh = function (mesh, serializationScene) {
  102203. var serializationObject = {};
  102204. // Geometry
  102205. var geometry = mesh._geometry;
  102206. if (geometry) {
  102207. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  102208. // 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
  102209. serializeGeometry(geometry, serializationScene.geometries);
  102210. }
  102211. }
  102212. // Custom
  102213. if (mesh.serialize) {
  102214. mesh.serialize(serializationObject);
  102215. }
  102216. return serializationObject;
  102217. };
  102218. var finalizeSingleMesh = function (mesh, serializationObject) {
  102219. //only works if the mesh is already loaded
  102220. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  102221. //serialize material
  102222. if (mesh.material) {
  102223. if (mesh.material instanceof BABYLON.MultiMaterial) {
  102224. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  102225. serializationObject.materials = serializationObject.materials || [];
  102226. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  102227. serializationObject.multiMaterials.push(mesh.material.serialize());
  102228. var _loop_1 = function (submaterial) {
  102229. if (submaterial) {
  102230. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  102231. serializationObject.materials.push(submaterial.serialize());
  102232. }
  102233. }
  102234. };
  102235. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  102236. var submaterial = _a[_i];
  102237. _loop_1(submaterial);
  102238. }
  102239. }
  102240. }
  102241. else {
  102242. serializationObject.materials = serializationObject.materials || [];
  102243. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  102244. serializationObject.materials.push(mesh.material.serialize());
  102245. }
  102246. }
  102247. }
  102248. //serialize geometry
  102249. var geometry = mesh._geometry;
  102250. if (geometry) {
  102251. if (!serializationObject.geometries) {
  102252. serializationObject.geometries = {};
  102253. serializationObject.geometries.boxes = [];
  102254. serializationObject.geometries.spheres = [];
  102255. serializationObject.geometries.cylinders = [];
  102256. serializationObject.geometries.toruses = [];
  102257. serializationObject.geometries.grounds = [];
  102258. serializationObject.geometries.planes = [];
  102259. serializationObject.geometries.torusKnots = [];
  102260. serializationObject.geometries.vertexData = [];
  102261. }
  102262. serializeGeometry(geometry, serializationObject.geometries);
  102263. }
  102264. // Skeletons
  102265. if (mesh.skeleton) {
  102266. serializationObject.skeletons = serializationObject.skeletons || [];
  102267. serializationObject.skeletons.push(mesh.skeleton.serialize());
  102268. }
  102269. //serialize the actual mesh
  102270. serializationObject.meshes = serializationObject.meshes || [];
  102271. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  102272. }
  102273. };
  102274. var SceneSerializer = /** @class */ (function () {
  102275. function SceneSerializer() {
  102276. }
  102277. SceneSerializer.ClearCache = function () {
  102278. serializedGeometries = [];
  102279. };
  102280. SceneSerializer.Serialize = function (scene) {
  102281. var serializationObject = {};
  102282. SceneSerializer.ClearCache();
  102283. // Scene
  102284. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  102285. serializationObject.autoClear = scene.autoClear;
  102286. serializationObject.clearColor = scene.clearColor.asArray();
  102287. serializationObject.ambientColor = scene.ambientColor.asArray();
  102288. serializationObject.gravity = scene.gravity.asArray();
  102289. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  102290. serializationObject.workerCollisions = scene.workerCollisions;
  102291. // Fog
  102292. if (scene.fogMode && scene.fogMode !== 0) {
  102293. serializationObject.fogMode = scene.fogMode;
  102294. serializationObject.fogColor = scene.fogColor.asArray();
  102295. serializationObject.fogStart = scene.fogStart;
  102296. serializationObject.fogEnd = scene.fogEnd;
  102297. serializationObject.fogDensity = scene.fogDensity;
  102298. }
  102299. //Physics
  102300. if (scene.isPhysicsEnabled()) {
  102301. var physicEngine = scene.getPhysicsEngine();
  102302. if (physicEngine) {
  102303. serializationObject.physicsEnabled = true;
  102304. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  102305. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  102306. }
  102307. }
  102308. // Metadata
  102309. if (scene.metadata) {
  102310. serializationObject.metadata = scene.metadata;
  102311. }
  102312. // Morph targets
  102313. serializationObject.morphTargetManagers = [];
  102314. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  102315. var abstractMesh = _a[_i];
  102316. var manager = abstractMesh.morphTargetManager;
  102317. if (manager) {
  102318. serializationObject.morphTargetManagers.push(manager.serialize());
  102319. }
  102320. }
  102321. // Lights
  102322. serializationObject.lights = [];
  102323. var index;
  102324. var light;
  102325. for (index = 0; index < scene.lights.length; index++) {
  102326. light = scene.lights[index];
  102327. if (!light.doNotSerialize) {
  102328. serializationObject.lights.push(light.serialize());
  102329. }
  102330. }
  102331. // Cameras
  102332. serializationObject.cameras = [];
  102333. for (index = 0; index < scene.cameras.length; index++) {
  102334. var camera = scene.cameras[index];
  102335. if (!camera.doNotSerialize) {
  102336. serializationObject.cameras.push(camera.serialize());
  102337. }
  102338. }
  102339. if (scene.activeCamera) {
  102340. serializationObject.activeCameraID = scene.activeCamera.id;
  102341. }
  102342. // Animations
  102343. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  102344. // Materials
  102345. serializationObject.materials = [];
  102346. serializationObject.multiMaterials = [];
  102347. var material;
  102348. for (index = 0; index < scene.materials.length; index++) {
  102349. material = scene.materials[index];
  102350. if (!material.doNotSerialize) {
  102351. serializationObject.materials.push(material.serialize());
  102352. }
  102353. }
  102354. // MultiMaterials
  102355. serializationObject.multiMaterials = [];
  102356. for (index = 0; index < scene.multiMaterials.length; index++) {
  102357. var multiMaterial = scene.multiMaterials[index];
  102358. serializationObject.multiMaterials.push(multiMaterial.serialize());
  102359. }
  102360. // Environment texture
  102361. if (scene.environmentTexture) {
  102362. serializationObject.environmentTexture = scene.environmentTexture.name;
  102363. }
  102364. // Skeletons
  102365. serializationObject.skeletons = [];
  102366. for (index = 0; index < scene.skeletons.length; index++) {
  102367. var skeleton = scene.skeletons[index];
  102368. if (!skeleton.doNotSerialize) {
  102369. serializationObject.skeletons.push(skeleton.serialize());
  102370. }
  102371. }
  102372. // Transform nodes
  102373. serializationObject.transformNodes = [];
  102374. for (index = 0; index < scene.transformNodes.length; index++) {
  102375. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  102376. }
  102377. // Geometries
  102378. serializationObject.geometries = {};
  102379. serializationObject.geometries.boxes = [];
  102380. serializationObject.geometries.spheres = [];
  102381. serializationObject.geometries.cylinders = [];
  102382. serializationObject.geometries.toruses = [];
  102383. serializationObject.geometries.grounds = [];
  102384. serializationObject.geometries.planes = [];
  102385. serializationObject.geometries.torusKnots = [];
  102386. serializationObject.geometries.vertexData = [];
  102387. serializedGeometries = [];
  102388. var geometries = scene.getGeometries();
  102389. for (index = 0; index < geometries.length; index++) {
  102390. var geometry = geometries[index];
  102391. if (geometry.isReady()) {
  102392. serializeGeometry(geometry, serializationObject.geometries);
  102393. }
  102394. }
  102395. // Meshes
  102396. serializationObject.meshes = [];
  102397. for (index = 0; index < scene.meshes.length; index++) {
  102398. var abstractMesh = scene.meshes[index];
  102399. if (abstractMesh instanceof BABYLON.Mesh) {
  102400. var mesh = abstractMesh;
  102401. if (!mesh.doNotSerialize) {
  102402. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  102403. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  102404. }
  102405. }
  102406. }
  102407. }
  102408. // Particles Systems
  102409. serializationObject.particleSystems = [];
  102410. for (index = 0; index < scene.particleSystems.length; index++) {
  102411. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  102412. }
  102413. // Shadows
  102414. serializationObject.shadowGenerators = [];
  102415. for (index = 0; index < scene.lights.length; index++) {
  102416. light = scene.lights[index];
  102417. var shadowGenerator = light.getShadowGenerator();
  102418. if (shadowGenerator) {
  102419. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  102420. }
  102421. }
  102422. // Action Manager
  102423. if (scene.actionManager) {
  102424. serializationObject.actions = scene.actionManager.serialize("scene");
  102425. }
  102426. // Audio
  102427. serializationObject.sounds = [];
  102428. for (index = 0; index < scene.soundTracks.length; index++) {
  102429. var soundtrack = scene.soundTracks[index];
  102430. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  102431. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  102432. }
  102433. }
  102434. // Components
  102435. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  102436. var component = _c[_b];
  102437. component.serialize(serializationObject);
  102438. }
  102439. return serializationObject;
  102440. };
  102441. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  102442. if (withParents === void 0) { withParents = false; }
  102443. if (withChildren === void 0) { withChildren = false; }
  102444. var serializationObject = {};
  102445. SceneSerializer.ClearCache();
  102446. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  102447. if (withParents || withChildren) {
  102448. //deliberate for loop! not for each, appended should be processed as well.
  102449. for (var i = 0; i < toSerialize.length; ++i) {
  102450. if (withChildren) {
  102451. toSerialize[i].getDescendants().forEach(function (node) {
  102452. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  102453. toSerialize.push(node);
  102454. }
  102455. });
  102456. }
  102457. //make sure the array doesn't contain the object already
  102458. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  102459. toSerialize.push(toSerialize[i].parent);
  102460. }
  102461. }
  102462. }
  102463. toSerialize.forEach(function (mesh) {
  102464. finalizeSingleMesh(mesh, serializationObject);
  102465. });
  102466. return serializationObject;
  102467. };
  102468. return SceneSerializer;
  102469. }());
  102470. BABYLON.SceneSerializer = SceneSerializer;
  102471. })(BABYLON || (BABYLON = {}));
  102472. //# sourceMappingURL=babylon.sceneSerializer.js.map
  102473. var BABYLON;
  102474. (function (BABYLON) {
  102475. /**
  102476. * Class used to generate realtime reflection / refraction cube textures
  102477. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  102478. */
  102479. var ReflectionProbe = /** @class */ (function () {
  102480. /**
  102481. * Creates a new reflection probe
  102482. * @param name defines the name of the probe
  102483. * @param size defines the texture resolution (for each face)
  102484. * @param scene defines the hosting scene
  102485. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  102486. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  102487. */
  102488. function ReflectionProbe(
  102489. /** defines the name of the probe */
  102490. name, size, scene, generateMipMaps, useFloat) {
  102491. if (generateMipMaps === void 0) { generateMipMaps = true; }
  102492. if (useFloat === void 0) { useFloat = false; }
  102493. var _this = this;
  102494. this.name = name;
  102495. this._viewMatrix = BABYLON.Matrix.Identity();
  102496. this._target = BABYLON.Vector3.Zero();
  102497. this._add = BABYLON.Vector3.Zero();
  102498. this._invertYAxis = false;
  102499. /** Gets or sets probe position (center of the cube map) */
  102500. this.position = BABYLON.Vector3.Zero();
  102501. this._scene = scene;
  102502. this._scene.reflectionProbes.push(this);
  102503. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  102504. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  102505. switch (faceIndex) {
  102506. case 0:
  102507. _this._add.copyFromFloats(1, 0, 0);
  102508. break;
  102509. case 1:
  102510. _this._add.copyFromFloats(-1, 0, 0);
  102511. break;
  102512. case 2:
  102513. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  102514. break;
  102515. case 3:
  102516. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  102517. break;
  102518. case 4:
  102519. _this._add.copyFromFloats(0, 0, 1);
  102520. break;
  102521. case 5:
  102522. _this._add.copyFromFloats(0, 0, -1);
  102523. break;
  102524. }
  102525. if (_this._attachedMesh) {
  102526. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  102527. }
  102528. _this.position.addToRef(_this._add, _this._target);
  102529. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  102530. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  102531. scene._forcedViewPosition = _this.position;
  102532. });
  102533. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  102534. scene._forcedViewPosition = null;
  102535. scene.updateTransformMatrix(true);
  102536. });
  102537. if (scene.activeCamera) {
  102538. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  102539. }
  102540. }
  102541. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  102542. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  102543. get: function () {
  102544. return this._renderTargetTexture.samples;
  102545. },
  102546. set: function (value) {
  102547. this._renderTargetTexture.samples = value;
  102548. },
  102549. enumerable: true,
  102550. configurable: true
  102551. });
  102552. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  102553. /** Gets or sets the refresh rate to use (on every frame by default) */
  102554. get: function () {
  102555. return this._renderTargetTexture.refreshRate;
  102556. },
  102557. set: function (value) {
  102558. this._renderTargetTexture.refreshRate = value;
  102559. },
  102560. enumerable: true,
  102561. configurable: true
  102562. });
  102563. /**
  102564. * Gets the hosting scene
  102565. * @returns a Scene
  102566. */
  102567. ReflectionProbe.prototype.getScene = function () {
  102568. return this._scene;
  102569. };
  102570. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  102571. /** Gets the internal CubeTexture used to render to */
  102572. get: function () {
  102573. return this._renderTargetTexture;
  102574. },
  102575. enumerable: true,
  102576. configurable: true
  102577. });
  102578. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  102579. /** Gets the list of meshes to render */
  102580. get: function () {
  102581. return this._renderTargetTexture.renderList;
  102582. },
  102583. enumerable: true,
  102584. configurable: true
  102585. });
  102586. /**
  102587. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  102588. * @param mesh defines the mesh to attach to
  102589. */
  102590. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  102591. this._attachedMesh = mesh;
  102592. };
  102593. /**
  102594. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  102595. * @param renderingGroupId The rendering group id corresponding to its index
  102596. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  102597. */
  102598. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  102599. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  102600. };
  102601. /**
  102602. * Clean all associated resources
  102603. */
  102604. ReflectionProbe.prototype.dispose = function () {
  102605. var index = this._scene.reflectionProbes.indexOf(this);
  102606. if (index !== -1) {
  102607. // Remove from the scene if found
  102608. this._scene.reflectionProbes.splice(index, 1);
  102609. }
  102610. if (this._renderTargetTexture) {
  102611. this._renderTargetTexture.dispose();
  102612. this._renderTargetTexture = null;
  102613. }
  102614. };
  102615. return ReflectionProbe;
  102616. }());
  102617. BABYLON.ReflectionProbe = ReflectionProbe;
  102618. })(BABYLON || (BABYLON = {}));
  102619. //# sourceMappingURL=babylon.reflectionProbe.js.map
  102620. var BABYLON;
  102621. (function (BABYLON) {
  102622. /**
  102623. * Defines the layer scene component responsible to manage any layers
  102624. * in a given scene.
  102625. */
  102626. var LayerSceneComponent = /** @class */ (function () {
  102627. /**
  102628. * Creates a new instance of the component for the given scene
  102629. * @param scene Defines the scene to register the component in
  102630. */
  102631. function LayerSceneComponent(scene) {
  102632. /**
  102633. * The component name helpfull to identify the component in the list of scene components.
  102634. */
  102635. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  102636. this.scene = scene;
  102637. this._engine = scene.getEngine();
  102638. scene.layers = new Array();
  102639. }
  102640. /**
  102641. * Registers the component in a given scene
  102642. */
  102643. LayerSceneComponent.prototype.register = function () {
  102644. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  102645. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  102646. };
  102647. /**
  102648. * Rebuilds the elements related to this component in case of
  102649. * context lost for instance.
  102650. */
  102651. LayerSceneComponent.prototype.rebuild = function () {
  102652. var layers = this.scene.layers;
  102653. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  102654. var layer = layers_1[_i];
  102655. layer._rebuild();
  102656. }
  102657. };
  102658. /**
  102659. * Disposes the component and the associated ressources.
  102660. */
  102661. LayerSceneComponent.prototype.dispose = function () {
  102662. var layers = this.scene.layers;
  102663. while (layers.length) {
  102664. layers[0].dispose();
  102665. }
  102666. };
  102667. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  102668. var layers = this.scene.layers;
  102669. if (layers.length) {
  102670. this._engine.setDepthBuffer(false);
  102671. var cameraLayerMask = camera.layerMask;
  102672. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  102673. var layer = layers_2[_i];
  102674. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  102675. layer.render();
  102676. }
  102677. }
  102678. this._engine.setDepthBuffer(true);
  102679. }
  102680. };
  102681. LayerSceneComponent.prototype._drawBackground = function (camera) {
  102682. this._draw(camera, true);
  102683. };
  102684. LayerSceneComponent.prototype._drawForeground = function (camera) {
  102685. this._draw(camera, false);
  102686. };
  102687. return LayerSceneComponent;
  102688. }());
  102689. BABYLON.LayerSceneComponent = LayerSceneComponent;
  102690. })(BABYLON || (BABYLON = {}));
  102691. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  102692. var BABYLON;
  102693. (function (BABYLON) {
  102694. var Layer = /** @class */ (function () {
  102695. function Layer(name, imgUrl, scene, isBackground, color) {
  102696. this.name = name;
  102697. this.scale = new BABYLON.Vector2(1, 1);
  102698. this.offset = new BABYLON.Vector2(0, 0);
  102699. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  102700. this.layerMask = 0x0FFFFFFF;
  102701. this._vertexBuffers = {};
  102702. // Events
  102703. /**
  102704. * An event triggered when the layer is disposed.
  102705. */
  102706. this.onDisposeObservable = new BABYLON.Observable();
  102707. /**
  102708. * An event triggered before rendering the scene
  102709. */
  102710. this.onBeforeRenderObservable = new BABYLON.Observable();
  102711. /**
  102712. * An event triggered after rendering the scene
  102713. */
  102714. this.onAfterRenderObservable = new BABYLON.Observable();
  102715. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  102716. this.isBackground = isBackground === undefined ? true : isBackground;
  102717. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  102718. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  102719. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  102720. if (!layerComponent) {
  102721. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  102722. this._scene._addComponent(layerComponent);
  102723. }
  102724. this._scene.layers.push(this);
  102725. var engine = this._scene.getEngine();
  102726. // VBO
  102727. var vertices = [];
  102728. vertices.push(1, 1);
  102729. vertices.push(-1, 1);
  102730. vertices.push(-1, -1);
  102731. vertices.push(1, -1);
  102732. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  102733. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  102734. this._createIndexBuffer();
  102735. // Effects
  102736. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  102737. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  102738. }
  102739. Object.defineProperty(Layer.prototype, "onDispose", {
  102740. set: function (callback) {
  102741. if (this._onDisposeObserver) {
  102742. this.onDisposeObservable.remove(this._onDisposeObserver);
  102743. }
  102744. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  102745. },
  102746. enumerable: true,
  102747. configurable: true
  102748. });
  102749. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  102750. set: function (callback) {
  102751. if (this._onBeforeRenderObserver) {
  102752. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  102753. }
  102754. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  102755. },
  102756. enumerable: true,
  102757. configurable: true
  102758. });
  102759. Object.defineProperty(Layer.prototype, "onAfterRender", {
  102760. set: function (callback) {
  102761. if (this._onAfterRenderObserver) {
  102762. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  102763. }
  102764. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  102765. },
  102766. enumerable: true,
  102767. configurable: true
  102768. });
  102769. Layer.prototype._createIndexBuffer = function () {
  102770. var engine = this._scene.getEngine();
  102771. // Indices
  102772. var indices = [];
  102773. indices.push(0);
  102774. indices.push(1);
  102775. indices.push(2);
  102776. indices.push(0);
  102777. indices.push(2);
  102778. indices.push(3);
  102779. this._indexBuffer = engine.createIndexBuffer(indices);
  102780. };
  102781. /** @hidden */
  102782. Layer.prototype._rebuild = function () {
  102783. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102784. if (vb) {
  102785. vb._rebuild();
  102786. }
  102787. this._createIndexBuffer();
  102788. };
  102789. Layer.prototype.render = function () {
  102790. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  102791. // Check
  102792. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  102793. return;
  102794. var engine = this._scene.getEngine();
  102795. this.onBeforeRenderObservable.notifyObservers(this);
  102796. // Render
  102797. engine.enableEffect(currentEffect);
  102798. engine.setState(false);
  102799. // Texture
  102800. currentEffect.setTexture("textureSampler", this.texture);
  102801. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  102802. // Color
  102803. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  102804. // Scale / offset
  102805. currentEffect.setVector2("offset", this.offset);
  102806. currentEffect.setVector2("scale", this.scale);
  102807. // VBOs
  102808. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  102809. // Draw order
  102810. if (!this.alphaTest) {
  102811. engine.setAlphaMode(this.alphaBlendingMode);
  102812. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102813. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  102814. }
  102815. else {
  102816. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102817. }
  102818. this.onAfterRenderObservable.notifyObservers(this);
  102819. };
  102820. Layer.prototype.dispose = function () {
  102821. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102822. if (vertexBuffer) {
  102823. vertexBuffer.dispose();
  102824. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  102825. }
  102826. if (this._indexBuffer) {
  102827. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  102828. this._indexBuffer = null;
  102829. }
  102830. if (this.texture) {
  102831. this.texture.dispose();
  102832. this.texture = null;
  102833. }
  102834. // Remove from scene
  102835. var index = this._scene.layers.indexOf(this);
  102836. this._scene.layers.splice(index, 1);
  102837. // Callback
  102838. this.onDisposeObservable.notifyObservers(this);
  102839. this.onDisposeObservable.clear();
  102840. this.onAfterRenderObservable.clear();
  102841. this.onBeforeRenderObservable.clear();
  102842. };
  102843. return Layer;
  102844. }());
  102845. BABYLON.Layer = Layer;
  102846. })(BABYLON || (BABYLON = {}));
  102847. //# sourceMappingURL=babylon.layer.js.map
  102848. var BABYLON;
  102849. (function (BABYLON) {
  102850. var TextureTools = /** @class */ (function () {
  102851. function TextureTools() {
  102852. }
  102853. /**
  102854. * Uses the GPU to create a copy texture rescaled at a given size
  102855. * @param texture Texture to copy from
  102856. * @param width Desired width
  102857. * @param height Desired height
  102858. * @return Generated texture
  102859. */
  102860. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  102861. if (useBilinearMode === void 0) { useBilinearMode = true; }
  102862. var scene = texture.getScene();
  102863. var engine = scene.getEngine();
  102864. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  102865. rtt.wrapU = texture.wrapU;
  102866. rtt.wrapV = texture.wrapV;
  102867. rtt.uOffset = texture.uOffset;
  102868. rtt.vOffset = texture.vOffset;
  102869. rtt.uScale = texture.uScale;
  102870. rtt.vScale = texture.vScale;
  102871. rtt.uAng = texture.uAng;
  102872. rtt.vAng = texture.vAng;
  102873. rtt.wAng = texture.wAng;
  102874. rtt.coordinatesIndex = texture.coordinatesIndex;
  102875. rtt.level = texture.level;
  102876. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  102877. rtt._texture.isReady = false;
  102878. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102879. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102880. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  102881. passPostProcess.getEffect().executeWhenCompiled(function () {
  102882. passPostProcess.onApply = function (effect) {
  102883. effect.setTexture("textureSampler", texture);
  102884. };
  102885. var internalTexture = rtt.getInternalTexture();
  102886. if (internalTexture) {
  102887. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  102888. engine.unBindFramebuffer(internalTexture);
  102889. rtt.disposeFramebufferObjects();
  102890. passPostProcess.dispose();
  102891. internalTexture.isReady = true;
  102892. }
  102893. });
  102894. return rtt;
  102895. };
  102896. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  102897. if (!scene._environmentBRDFTexture) {
  102898. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102899. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102900. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102901. scene._environmentBRDFTexture = texture;
  102902. }
  102903. return scene._environmentBRDFTexture;
  102904. };
  102905. 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=";
  102906. return TextureTools;
  102907. }());
  102908. BABYLON.TextureTools = TextureTools;
  102909. })(BABYLON || (BABYLON = {}));
  102910. //# sourceMappingURL=babylon.textureTools.js.map
  102911. var BABYLON;
  102912. (function (BABYLON) {
  102913. var FramingBehavior = /** @class */ (function () {
  102914. function FramingBehavior() {
  102915. this._mode = FramingBehavior.FitFrustumSidesMode;
  102916. this._radiusScale = 1.0;
  102917. this._positionScale = 0.5;
  102918. this._defaultElevation = 0.3;
  102919. this._elevationReturnTime = 1500;
  102920. this._elevationReturnWaitTime = 1000;
  102921. this._zoomStopsAnimation = false;
  102922. this._framingTime = 1500;
  102923. this._isPointerDown = false;
  102924. this._lastInteractionTime = -Infinity;
  102925. // Framing control
  102926. this._animatables = new Array();
  102927. this._betaIsAnimating = false;
  102928. }
  102929. Object.defineProperty(FramingBehavior.prototype, "name", {
  102930. get: function () {
  102931. return "Framing";
  102932. },
  102933. enumerable: true,
  102934. configurable: true
  102935. });
  102936. Object.defineProperty(FramingBehavior.prototype, "mode", {
  102937. /**
  102938. * Gets current mode used by the behavior.
  102939. */
  102940. get: function () {
  102941. return this._mode;
  102942. },
  102943. /**
  102944. * Sets the current mode used by the behavior
  102945. */
  102946. set: function (mode) {
  102947. this._mode = mode;
  102948. },
  102949. enumerable: true,
  102950. configurable: true
  102951. });
  102952. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  102953. /**
  102954. * Gets the scale applied to the radius
  102955. */
  102956. get: function () {
  102957. return this._radiusScale;
  102958. },
  102959. /**
  102960. * Sets the scale applied to the radius (1 by default)
  102961. */
  102962. set: function (radius) {
  102963. this._radiusScale = radius;
  102964. },
  102965. enumerable: true,
  102966. configurable: true
  102967. });
  102968. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  102969. /**
  102970. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  102971. */
  102972. get: function () {
  102973. return this._positionScale;
  102974. },
  102975. /**
  102976. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  102977. */
  102978. set: function (scale) {
  102979. this._positionScale = scale;
  102980. },
  102981. enumerable: true,
  102982. configurable: true
  102983. });
  102984. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  102985. /**
  102986. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  102987. * behaviour is triggered, in radians.
  102988. */
  102989. get: function () {
  102990. return this._defaultElevation;
  102991. },
  102992. /**
  102993. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  102994. * behaviour is triggered, in radians.
  102995. */
  102996. set: function (elevation) {
  102997. this._defaultElevation = elevation;
  102998. },
  102999. enumerable: true,
  103000. configurable: true
  103001. });
  103002. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  103003. /**
  103004. * Gets the time (in milliseconds) taken to return to the default beta position.
  103005. * Negative value indicates camera should not return to default.
  103006. */
  103007. get: function () {
  103008. return this._elevationReturnTime;
  103009. },
  103010. /**
  103011. * Sets the time (in milliseconds) taken to return to the default beta position.
  103012. * Negative value indicates camera should not return to default.
  103013. */
  103014. set: function (speed) {
  103015. this._elevationReturnTime = speed;
  103016. },
  103017. enumerable: true,
  103018. configurable: true
  103019. });
  103020. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  103021. /**
  103022. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  103023. */
  103024. get: function () {
  103025. return this._elevationReturnWaitTime;
  103026. },
  103027. /**
  103028. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  103029. */
  103030. set: function (time) {
  103031. this._elevationReturnWaitTime = time;
  103032. },
  103033. enumerable: true,
  103034. configurable: true
  103035. });
  103036. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  103037. /**
  103038. * Gets the flag that indicates if user zooming should stop animation.
  103039. */
  103040. get: function () {
  103041. return this._zoomStopsAnimation;
  103042. },
  103043. /**
  103044. * Sets the flag that indicates if user zooming should stop animation.
  103045. */
  103046. set: function (flag) {
  103047. this._zoomStopsAnimation = flag;
  103048. },
  103049. enumerable: true,
  103050. configurable: true
  103051. });
  103052. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  103053. /**
  103054. * Gets the transition time when framing the mesh, in milliseconds
  103055. */
  103056. get: function () {
  103057. return this._framingTime;
  103058. },
  103059. /**
  103060. * Sets the transition time when framing the mesh, in milliseconds
  103061. */
  103062. set: function (time) {
  103063. this._framingTime = time;
  103064. },
  103065. enumerable: true,
  103066. configurable: true
  103067. });
  103068. FramingBehavior.prototype.init = function () {
  103069. // Do notihng
  103070. };
  103071. FramingBehavior.prototype.attach = function (camera) {
  103072. var _this = this;
  103073. this._attachedCamera = camera;
  103074. var scene = this._attachedCamera.getScene();
  103075. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  103076. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  103077. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  103078. _this._isPointerDown = true;
  103079. return;
  103080. }
  103081. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  103082. _this._isPointerDown = false;
  103083. }
  103084. });
  103085. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  103086. if (mesh) {
  103087. _this.zoomOnMesh(mesh);
  103088. }
  103089. });
  103090. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103091. // Stop the animation if there is user interaction and the animation should stop for this interaction
  103092. _this._applyUserInteraction();
  103093. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  103094. // back to the default position after a given timeout
  103095. _this._maintainCameraAboveGround();
  103096. });
  103097. };
  103098. FramingBehavior.prototype.detach = function () {
  103099. if (!this._attachedCamera) {
  103100. return;
  103101. }
  103102. var scene = this._attachedCamera.getScene();
  103103. if (this._onPrePointerObservableObserver) {
  103104. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  103105. }
  103106. if (this._onAfterCheckInputsObserver) {
  103107. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103108. }
  103109. if (this._onMeshTargetChangedObserver) {
  103110. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103111. }
  103112. this._attachedCamera = null;
  103113. };
  103114. /**
  103115. * Targets the given mesh and updates zoom level accordingly.
  103116. * @param mesh The mesh to target.
  103117. * @param radius Optional. If a cached radius position already exists, overrides default.
  103118. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103119. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103120. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103121. */
  103122. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  103123. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103124. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103125. mesh.computeWorldMatrix(true);
  103126. var boundingBox = mesh.getBoundingInfo().boundingBox;
  103127. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  103128. };
  103129. /**
  103130. * Targets the given mesh with its children and updates zoom level accordingly.
  103131. * @param mesh The mesh to target.
  103132. * @param radius Optional. If a cached radius position already exists, overrides default.
  103133. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103134. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103135. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103136. */
  103137. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  103138. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103139. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103140. mesh.computeWorldMatrix(true);
  103141. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  103142. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  103143. };
  103144. /**
  103145. * Targets the given meshes with their children and updates zoom level accordingly.
  103146. * @param meshes The mesh to target.
  103147. * @param radius Optional. If a cached radius position already exists, overrides default.
  103148. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103149. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103150. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103151. */
  103152. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  103153. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103154. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103155. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  103156. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  103157. for (var i = 0; i < meshes.length; i++) {
  103158. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  103159. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  103160. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  103161. }
  103162. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  103163. };
  103164. /**
  103165. * Targets the given mesh and updates zoom level accordingly.
  103166. * @param mesh The mesh to target.
  103167. * @param radius Optional. If a cached radius position already exists, overrides default.
  103168. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103169. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103170. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103171. */
  103172. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  103173. var _this = this;
  103174. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103175. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103176. var zoomTarget;
  103177. if (!this._attachedCamera) {
  103178. return;
  103179. }
  103180. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  103181. var bottom = minimumWorld.y;
  103182. var top = maximumWorld.y;
  103183. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  103184. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  103185. if (focusOnOriginXZ) {
  103186. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  103187. }
  103188. else {
  103189. var centerWorld = minimumWorld.add(radiusWorld);
  103190. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  103191. }
  103192. if (!this._vectorTransition) {
  103193. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  103194. }
  103195. this._betaIsAnimating = true;
  103196. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  103197. if (animatable) {
  103198. this._animatables.push(animatable);
  103199. }
  103200. // sets the radius and lower radius bounds
  103201. // Small delta ensures camera is not always at lower zoom limit.
  103202. var radius = 0;
  103203. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  103204. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  103205. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  103206. radius = position;
  103207. }
  103208. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  103209. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  103210. if (this._attachedCamera.lowerRadiusLimit === null) {
  103211. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  103212. }
  103213. }
  103214. // Set sensibilities
  103215. var extend = maximumWorld.subtract(minimumWorld).length();
  103216. this._attachedCamera.panningSensibility = 5000 / extend;
  103217. this._attachedCamera.wheelPrecision = 100 / radius;
  103218. // transition to new radius
  103219. if (!this._radiusTransition) {
  103220. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  103221. }
  103222. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  103223. _this.stopAllAnimations();
  103224. if (onAnimationEnd) {
  103225. onAnimationEnd();
  103226. }
  103227. if (_this._attachedCamera) {
  103228. _this._attachedCamera.storeState();
  103229. }
  103230. });
  103231. if (animatable) {
  103232. this._animatables.push(animatable);
  103233. }
  103234. };
  103235. /**
  103236. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  103237. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  103238. * frustum width.
  103239. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  103240. * to fully enclose the mesh in the viewing frustum.
  103241. */
  103242. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  103243. var size = maximumWorld.subtract(minimumWorld);
  103244. var boxVectorGlobalDiagonal = size.length();
  103245. var frustumSlope = this._getFrustumSlope();
  103246. // Formula for setting distance
  103247. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  103248. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  103249. // Horizon distance
  103250. var radius = radiusWithoutFraming * this._radiusScale;
  103251. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  103252. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  103253. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  103254. var camera = this._attachedCamera;
  103255. if (!camera) {
  103256. return 0;
  103257. }
  103258. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  103259. // Don't exceed the requested limit
  103260. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  103261. }
  103262. // Don't exceed the upper radius limit
  103263. if (camera.upperRadiusLimit) {
  103264. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  103265. }
  103266. return distance;
  103267. };
  103268. /**
  103269. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  103270. * is automatically returned to its default position (expected to be above ground plane).
  103271. */
  103272. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  103273. var _this = this;
  103274. if (this._elevationReturnTime < 0) {
  103275. return;
  103276. }
  103277. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  103278. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  103279. var limitBeta = Math.PI * 0.5;
  103280. // Bring the camera back up if below the ground plane
  103281. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  103282. this._betaIsAnimating = true;
  103283. //Transition to new position
  103284. this.stopAllAnimations();
  103285. if (!this._betaTransition) {
  103286. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  103287. }
  103288. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  103289. _this._clearAnimationLocks();
  103290. _this.stopAllAnimations();
  103291. });
  103292. if (animatabe) {
  103293. this._animatables.push(animatabe);
  103294. }
  103295. }
  103296. };
  103297. /**
  103298. * Returns the frustum slope based on the canvas ratio and camera FOV
  103299. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  103300. */
  103301. FramingBehavior.prototype._getFrustumSlope = function () {
  103302. // Calculate the viewport ratio
  103303. // Aspect Ratio is Height/Width.
  103304. var camera = this._attachedCamera;
  103305. if (!camera) {
  103306. return BABYLON.Vector2.Zero();
  103307. }
  103308. var engine = camera.getScene().getEngine();
  103309. var aspectRatio = engine.getAspectRatio(camera);
  103310. // Camera FOV is the vertical field of view (top-bottom) in radians.
  103311. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  103312. var frustumSlopeY = Math.tan(camera.fov / 2);
  103313. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  103314. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  103315. // along the forward vector.
  103316. var frustumSlopeX = frustumSlopeY * aspectRatio;
  103317. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  103318. };
  103319. /**
  103320. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  103321. */
  103322. FramingBehavior.prototype._clearAnimationLocks = function () {
  103323. this._betaIsAnimating = false;
  103324. };
  103325. /**
  103326. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  103327. */
  103328. FramingBehavior.prototype._applyUserInteraction = function () {
  103329. if (this.isUserIsMoving) {
  103330. this._lastInteractionTime = BABYLON.Tools.Now;
  103331. this.stopAllAnimations();
  103332. this._clearAnimationLocks();
  103333. }
  103334. };
  103335. /**
  103336. * Stops and removes all animations that have been applied to the camera
  103337. */
  103338. FramingBehavior.prototype.stopAllAnimations = function () {
  103339. if (this._attachedCamera) {
  103340. this._attachedCamera.animations = [];
  103341. }
  103342. while (this._animatables.length) {
  103343. if (this._animatables[0]) {
  103344. this._animatables[0].onAnimationEnd = null;
  103345. this._animatables[0].stop();
  103346. }
  103347. this._animatables.shift();
  103348. }
  103349. };
  103350. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  103351. /**
  103352. * Gets a value indicating if the user is moving the camera
  103353. */
  103354. get: function () {
  103355. if (!this._attachedCamera) {
  103356. return false;
  103357. }
  103358. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  103359. this._attachedCamera.inertialBetaOffset !== 0 ||
  103360. this._attachedCamera.inertialRadiusOffset !== 0 ||
  103361. this._attachedCamera.inertialPanningX !== 0 ||
  103362. this._attachedCamera.inertialPanningY !== 0 ||
  103363. this._isPointerDown;
  103364. },
  103365. enumerable: true,
  103366. configurable: true
  103367. });
  103368. /**
  103369. * The easing function used by animations
  103370. */
  103371. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  103372. /**
  103373. * The easing mode used by animations
  103374. */
  103375. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  103376. // Statics
  103377. /**
  103378. * The camera can move all the way towards the mesh.
  103379. */
  103380. FramingBehavior.IgnoreBoundsSizeMode = 0;
  103381. /**
  103382. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  103383. */
  103384. FramingBehavior.FitFrustumSidesMode = 1;
  103385. return FramingBehavior;
  103386. }());
  103387. BABYLON.FramingBehavior = FramingBehavior;
  103388. })(BABYLON || (BABYLON = {}));
  103389. //# sourceMappingURL=babylon.framingBehavior.js.map
  103390. var BABYLON;
  103391. (function (BABYLON) {
  103392. /**
  103393. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  103394. */
  103395. var BouncingBehavior = /** @class */ (function () {
  103396. function BouncingBehavior() {
  103397. /**
  103398. * The duration of the animation, in milliseconds
  103399. */
  103400. this.transitionDuration = 450;
  103401. /**
  103402. * Length of the distance animated by the transition when lower radius is reached
  103403. */
  103404. this.lowerRadiusTransitionRange = 2;
  103405. /**
  103406. * Length of the distance animated by the transition when upper radius is reached
  103407. */
  103408. this.upperRadiusTransitionRange = -2;
  103409. this._autoTransitionRange = false;
  103410. // Animations
  103411. this._radiusIsAnimating = false;
  103412. this._radiusBounceTransition = null;
  103413. this._animatables = new Array();
  103414. }
  103415. Object.defineProperty(BouncingBehavior.prototype, "name", {
  103416. get: function () {
  103417. return "Bouncing";
  103418. },
  103419. enumerable: true,
  103420. configurable: true
  103421. });
  103422. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  103423. /**
  103424. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  103425. */
  103426. get: function () {
  103427. return this._autoTransitionRange;
  103428. },
  103429. /**
  103430. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  103431. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  103432. */
  103433. set: function (value) {
  103434. var _this = this;
  103435. if (this._autoTransitionRange === value) {
  103436. return;
  103437. }
  103438. this._autoTransitionRange = value;
  103439. var camera = this._attachedCamera;
  103440. if (!camera) {
  103441. return;
  103442. }
  103443. if (value) {
  103444. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  103445. if (!mesh) {
  103446. return;
  103447. }
  103448. mesh.computeWorldMatrix(true);
  103449. var diagonal = mesh.getBoundingInfo().diagonalLength;
  103450. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  103451. _this.upperRadiusTransitionRange = diagonal * 0.05;
  103452. });
  103453. }
  103454. else if (this._onMeshTargetChangedObserver) {
  103455. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103456. }
  103457. },
  103458. enumerable: true,
  103459. configurable: true
  103460. });
  103461. BouncingBehavior.prototype.init = function () {
  103462. // Do notihng
  103463. };
  103464. BouncingBehavior.prototype.attach = function (camera) {
  103465. var _this = this;
  103466. this._attachedCamera = camera;
  103467. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103468. if (!_this._attachedCamera) {
  103469. return;
  103470. }
  103471. // Add the bounce animation to the lower radius limit
  103472. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  103473. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  103474. }
  103475. // Add the bounce animation to the upper radius limit
  103476. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  103477. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  103478. }
  103479. });
  103480. };
  103481. BouncingBehavior.prototype.detach = function () {
  103482. if (!this._attachedCamera) {
  103483. return;
  103484. }
  103485. if (this._onAfterCheckInputsObserver) {
  103486. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103487. }
  103488. if (this._onMeshTargetChangedObserver) {
  103489. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103490. }
  103491. this._attachedCamera = null;
  103492. };
  103493. /**
  103494. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  103495. * @param radiusLimit The limit to check against.
  103496. * @return Bool to indicate if at limit.
  103497. */
  103498. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  103499. if (!this._attachedCamera) {
  103500. return false;
  103501. }
  103502. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  103503. return true;
  103504. }
  103505. return false;
  103506. };
  103507. /**
  103508. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  103509. * @param radiusDelta The delta by which to animate to. Can be negative.
  103510. */
  103511. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  103512. var _this = this;
  103513. if (!this._attachedCamera) {
  103514. return;
  103515. }
  103516. if (!this._radiusBounceTransition) {
  103517. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  103518. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  103519. }
  103520. // Prevent zoom until bounce has completed
  103521. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  103522. this._attachedCamera.wheelPrecision = Infinity;
  103523. this._attachedCamera.inertialRadiusOffset = 0;
  103524. // Animate to the radius limit
  103525. this.stopAllAnimations();
  103526. this._radiusIsAnimating = true;
  103527. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  103528. if (animatable) {
  103529. this._animatables.push(animatable);
  103530. }
  103531. };
  103532. /**
  103533. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  103534. */
  103535. BouncingBehavior.prototype._clearAnimationLocks = function () {
  103536. this._radiusIsAnimating = false;
  103537. if (this._attachedCamera) {
  103538. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  103539. }
  103540. };
  103541. /**
  103542. * Stops and removes all animations that have been applied to the camera
  103543. */
  103544. BouncingBehavior.prototype.stopAllAnimations = function () {
  103545. if (this._attachedCamera) {
  103546. this._attachedCamera.animations = [];
  103547. }
  103548. while (this._animatables.length) {
  103549. this._animatables[0].onAnimationEnd = null;
  103550. this._animatables[0].stop();
  103551. this._animatables.shift();
  103552. }
  103553. };
  103554. /**
  103555. * The easing function used by animations
  103556. */
  103557. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  103558. /**
  103559. * The easing mode used by animations
  103560. */
  103561. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  103562. return BouncingBehavior;
  103563. }());
  103564. BABYLON.BouncingBehavior = BouncingBehavior;
  103565. })(BABYLON || (BABYLON = {}));
  103566. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  103567. var BABYLON;
  103568. (function (BABYLON) {
  103569. var AutoRotationBehavior = /** @class */ (function () {
  103570. function AutoRotationBehavior() {
  103571. this._zoomStopsAnimation = false;
  103572. this._idleRotationSpeed = 0.05;
  103573. this._idleRotationWaitTime = 2000;
  103574. this._idleRotationSpinupTime = 2000;
  103575. this._isPointerDown = false;
  103576. this._lastFrameTime = null;
  103577. this._lastInteractionTime = -Infinity;
  103578. this._cameraRotationSpeed = 0;
  103579. this._lastFrameRadius = 0;
  103580. }
  103581. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  103582. get: function () {
  103583. return "AutoRotation";
  103584. },
  103585. enumerable: true,
  103586. configurable: true
  103587. });
  103588. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  103589. /**
  103590. * Gets the flag that indicates if user zooming should stop animation.
  103591. */
  103592. get: function () {
  103593. return this._zoomStopsAnimation;
  103594. },
  103595. /**
  103596. * Sets the flag that indicates if user zooming should stop animation.
  103597. */
  103598. set: function (flag) {
  103599. this._zoomStopsAnimation = flag;
  103600. },
  103601. enumerable: true,
  103602. configurable: true
  103603. });
  103604. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  103605. /**
  103606. * Gets the default speed at which the camera rotates around the model.
  103607. */
  103608. get: function () {
  103609. return this._idleRotationSpeed;
  103610. },
  103611. /**
  103612. * Sets the default speed at which the camera rotates around the model.
  103613. */
  103614. set: function (speed) {
  103615. this._idleRotationSpeed = speed;
  103616. },
  103617. enumerable: true,
  103618. configurable: true
  103619. });
  103620. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  103621. /**
  103622. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  103623. */
  103624. get: function () {
  103625. return this._idleRotationWaitTime;
  103626. },
  103627. /**
  103628. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  103629. */
  103630. set: function (time) {
  103631. this._idleRotationWaitTime = time;
  103632. },
  103633. enumerable: true,
  103634. configurable: true
  103635. });
  103636. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  103637. /**
  103638. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  103639. */
  103640. get: function () {
  103641. return this._idleRotationSpinupTime;
  103642. },
  103643. /**
  103644. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  103645. */
  103646. set: function (time) {
  103647. this._idleRotationSpinupTime = time;
  103648. },
  103649. enumerable: true,
  103650. configurable: true
  103651. });
  103652. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  103653. /**
  103654. * Gets a value indicating if the camera is currently rotating because of this behavior
  103655. */
  103656. get: function () {
  103657. return Math.abs(this._cameraRotationSpeed) > 0;
  103658. },
  103659. enumerable: true,
  103660. configurable: true
  103661. });
  103662. AutoRotationBehavior.prototype.init = function () {
  103663. // Do notihng
  103664. };
  103665. AutoRotationBehavior.prototype.attach = function (camera) {
  103666. var _this = this;
  103667. this._attachedCamera = camera;
  103668. var scene = this._attachedCamera.getScene();
  103669. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  103670. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  103671. _this._isPointerDown = true;
  103672. return;
  103673. }
  103674. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  103675. _this._isPointerDown = false;
  103676. }
  103677. });
  103678. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103679. var now = BABYLON.Tools.Now;
  103680. var dt = 0;
  103681. if (_this._lastFrameTime != null) {
  103682. dt = now - _this._lastFrameTime;
  103683. }
  103684. _this._lastFrameTime = now;
  103685. // Stop the animation if there is user interaction and the animation should stop for this interaction
  103686. _this._applyUserInteraction();
  103687. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  103688. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  103689. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  103690. // Step camera rotation by rotation speed
  103691. if (_this._attachedCamera) {
  103692. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  103693. }
  103694. });
  103695. };
  103696. AutoRotationBehavior.prototype.detach = function () {
  103697. if (!this._attachedCamera) {
  103698. return;
  103699. }
  103700. var scene = this._attachedCamera.getScene();
  103701. if (this._onPrePointerObservableObserver) {
  103702. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  103703. }
  103704. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103705. this._attachedCamera = null;
  103706. };
  103707. /**
  103708. * Returns true if user is scrolling.
  103709. * @return true if user is scrolling.
  103710. */
  103711. AutoRotationBehavior.prototype._userIsZooming = function () {
  103712. if (!this._attachedCamera) {
  103713. return false;
  103714. }
  103715. return this._attachedCamera.inertialRadiusOffset !== 0;
  103716. };
  103717. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  103718. if (!this._attachedCamera) {
  103719. return false;
  103720. }
  103721. var zoomHasHitLimit = false;
  103722. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  103723. zoomHasHitLimit = true;
  103724. }
  103725. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  103726. this._lastFrameRadius = this._attachedCamera.radius;
  103727. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  103728. };
  103729. /**
  103730. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  103731. */
  103732. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  103733. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  103734. this._lastInteractionTime = BABYLON.Tools.Now;
  103735. }
  103736. };
  103737. // Tools
  103738. AutoRotationBehavior.prototype._userIsMoving = function () {
  103739. if (!this._attachedCamera) {
  103740. return false;
  103741. }
  103742. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  103743. this._attachedCamera.inertialBetaOffset !== 0 ||
  103744. this._attachedCamera.inertialRadiusOffset !== 0 ||
  103745. this._attachedCamera.inertialPanningX !== 0 ||
  103746. this._attachedCamera.inertialPanningY !== 0 ||
  103747. this._isPointerDown;
  103748. };
  103749. return AutoRotationBehavior;
  103750. }());
  103751. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  103752. })(BABYLON || (BABYLON = {}));
  103753. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  103754. var BABYLON;
  103755. (function (BABYLON) {
  103756. var NullEngineOptions = /** @class */ (function () {
  103757. function NullEngineOptions() {
  103758. this.renderWidth = 512;
  103759. this.renderHeight = 256;
  103760. this.textureSize = 512;
  103761. this.deterministicLockstep = false;
  103762. this.lockstepMaxSteps = 4;
  103763. }
  103764. return NullEngineOptions;
  103765. }());
  103766. BABYLON.NullEngineOptions = NullEngineOptions;
  103767. /**
  103768. * The null engine class provides support for headless version of babylon.js.
  103769. * This can be used in server side scenario or for testing purposes
  103770. */
  103771. var NullEngine = /** @class */ (function (_super) {
  103772. __extends(NullEngine, _super);
  103773. function NullEngine(options) {
  103774. if (options === void 0) { options = new NullEngineOptions(); }
  103775. var _this = _super.call(this, null) || this;
  103776. if (options.deterministicLockstep === undefined) {
  103777. options.deterministicLockstep = false;
  103778. }
  103779. if (options.lockstepMaxSteps === undefined) {
  103780. options.lockstepMaxSteps = 4;
  103781. }
  103782. _this._options = options;
  103783. // Init caps
  103784. // We consider we are on a webgl1 capable device
  103785. _this._caps = new BABYLON.EngineCapabilities();
  103786. _this._caps.maxTexturesImageUnits = 16;
  103787. _this._caps.maxVertexTextureImageUnits = 16;
  103788. _this._caps.maxTextureSize = 512;
  103789. _this._caps.maxCubemapTextureSize = 512;
  103790. _this._caps.maxRenderTextureSize = 512;
  103791. _this._caps.maxVertexAttribs = 16;
  103792. _this._caps.maxVaryingVectors = 16;
  103793. _this._caps.maxFragmentUniformVectors = 16;
  103794. _this._caps.maxVertexUniformVectors = 16;
  103795. // Extensions
  103796. _this._caps.standardDerivatives = false;
  103797. _this._caps.astc = null;
  103798. _this._caps.s3tc = null;
  103799. _this._caps.pvrtc = null;
  103800. _this._caps.etc1 = null;
  103801. _this._caps.etc2 = null;
  103802. _this._caps.textureAnisotropicFilterExtension = null;
  103803. _this._caps.maxAnisotropy = 0;
  103804. _this._caps.uintIndices = false;
  103805. _this._caps.fragmentDepthSupported = false;
  103806. _this._caps.highPrecisionShaderSupported = true;
  103807. _this._caps.colorBufferFloat = false;
  103808. _this._caps.textureFloat = false;
  103809. _this._caps.textureFloatLinearFiltering = false;
  103810. _this._caps.textureFloatRender = false;
  103811. _this._caps.textureHalfFloat = false;
  103812. _this._caps.textureHalfFloatLinearFiltering = false;
  103813. _this._caps.textureHalfFloatRender = false;
  103814. _this._caps.textureLOD = false;
  103815. _this._caps.drawBuffersExtension = false;
  103816. _this._caps.depthTextureExtension = false;
  103817. _this._caps.vertexArrayObject = false;
  103818. _this._caps.instancedArrays = false;
  103819. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  103820. // Wrappers
  103821. if (typeof URL === "undefined") {
  103822. URL = {
  103823. createObjectURL: function () { },
  103824. revokeObjectURL: function () { }
  103825. };
  103826. }
  103827. if (typeof Blob === "undefined") {
  103828. Blob = function () { };
  103829. }
  103830. return _this;
  103831. }
  103832. NullEngine.prototype.isDeterministicLockStep = function () {
  103833. return this._options.deterministicLockstep;
  103834. };
  103835. NullEngine.prototype.getLockstepMaxSteps = function () {
  103836. return this._options.lockstepMaxSteps;
  103837. };
  103838. NullEngine.prototype.getHardwareScalingLevel = function () {
  103839. return 1.0;
  103840. };
  103841. NullEngine.prototype.createVertexBuffer = function (vertices) {
  103842. return {
  103843. capacity: 0,
  103844. references: 1,
  103845. is32Bits: false
  103846. };
  103847. };
  103848. NullEngine.prototype.createIndexBuffer = function (indices) {
  103849. return {
  103850. capacity: 0,
  103851. references: 1,
  103852. is32Bits: false
  103853. };
  103854. };
  103855. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  103856. if (stencil === void 0) { stencil = false; }
  103857. };
  103858. NullEngine.prototype.getRenderWidth = function (useScreen) {
  103859. if (useScreen === void 0) { useScreen = false; }
  103860. if (!useScreen && this._currentRenderTarget) {
  103861. return this._currentRenderTarget.width;
  103862. }
  103863. return this._options.renderWidth;
  103864. };
  103865. NullEngine.prototype.getRenderHeight = function (useScreen) {
  103866. if (useScreen === void 0) { useScreen = false; }
  103867. if (!useScreen && this._currentRenderTarget) {
  103868. return this._currentRenderTarget.height;
  103869. }
  103870. return this._options.renderHeight;
  103871. };
  103872. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  103873. this._cachedViewport = viewport;
  103874. };
  103875. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  103876. return {
  103877. transformFeedback: null,
  103878. __SPECTOR_rebuildProgram: null
  103879. };
  103880. };
  103881. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  103882. return [];
  103883. };
  103884. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  103885. return [];
  103886. };
  103887. NullEngine.prototype.bindSamplers = function (effect) {
  103888. this._currentEffect = null;
  103889. };
  103890. NullEngine.prototype.enableEffect = function (effect) {
  103891. this._currentEffect = effect;
  103892. if (effect.onBind) {
  103893. effect.onBind(effect);
  103894. }
  103895. if (effect._onBindObservable) {
  103896. effect._onBindObservable.notifyObservers(effect);
  103897. }
  103898. };
  103899. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  103900. if (zOffset === void 0) { zOffset = 0; }
  103901. if (reverseSide === void 0) { reverseSide = false; }
  103902. };
  103903. NullEngine.prototype.setIntArray = function (uniform, array) {
  103904. };
  103905. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  103906. };
  103907. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  103908. };
  103909. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  103910. };
  103911. NullEngine.prototype.setFloatArray = function (uniform, array) {
  103912. };
  103913. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  103914. };
  103915. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  103916. };
  103917. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  103918. };
  103919. NullEngine.prototype.setArray = function (uniform, array) {
  103920. };
  103921. NullEngine.prototype.setArray2 = function (uniform, array) {
  103922. };
  103923. NullEngine.prototype.setArray3 = function (uniform, array) {
  103924. };
  103925. NullEngine.prototype.setArray4 = function (uniform, array) {
  103926. };
  103927. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  103928. };
  103929. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  103930. };
  103931. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  103932. };
  103933. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  103934. };
  103935. NullEngine.prototype.setFloat = function (uniform, value) {
  103936. };
  103937. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  103938. };
  103939. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  103940. };
  103941. NullEngine.prototype.setBool = function (uniform, bool) {
  103942. };
  103943. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  103944. };
  103945. NullEngine.prototype.setColor3 = function (uniform, color3) {
  103946. };
  103947. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  103948. };
  103949. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  103950. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  103951. if (this._alphaMode === mode) {
  103952. return;
  103953. }
  103954. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  103955. if (!noDepthWriteChange) {
  103956. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  103957. }
  103958. this._alphaMode = mode;
  103959. };
  103960. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  103961. };
  103962. NullEngine.prototype.wipeCaches = function (bruteForce) {
  103963. if (this.preventCacheWipeBetweenFrames) {
  103964. return;
  103965. }
  103966. this.resetTextureCache();
  103967. this._currentEffect = null;
  103968. if (bruteForce) {
  103969. this._currentProgram = null;
  103970. this._stencilState.reset();
  103971. this._depthCullingState.reset();
  103972. this._alphaState.reset();
  103973. }
  103974. this._cachedVertexBuffers = null;
  103975. this._cachedIndexBuffer = null;
  103976. this._cachedEffectForVertexBuffers = null;
  103977. };
  103978. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  103979. };
  103980. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  103981. };
  103982. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  103983. };
  103984. /** @hidden */
  103985. NullEngine.prototype._createTexture = function () {
  103986. return {};
  103987. };
  103988. /** @hidden */
  103989. NullEngine.prototype._releaseTexture = function (texture) {
  103990. };
  103991. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  103992. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  103993. if (onLoad === void 0) { onLoad = null; }
  103994. if (onError === void 0) { onError = null; }
  103995. if (buffer === void 0) { buffer = null; }
  103996. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  103997. var url = String(urlArg);
  103998. texture.url = url;
  103999. texture.generateMipMaps = !noMipmap;
  104000. texture.samplingMode = samplingMode;
  104001. texture.invertY = invertY;
  104002. texture.baseWidth = this._options.textureSize;
  104003. texture.baseHeight = this._options.textureSize;
  104004. texture.width = this._options.textureSize;
  104005. texture.height = this._options.textureSize;
  104006. if (format) {
  104007. texture.format = format;
  104008. }
  104009. texture.isReady = true;
  104010. if (onLoad) {
  104011. onLoad();
  104012. }
  104013. this._internalTexturesCache.push(texture);
  104014. return texture;
  104015. };
  104016. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  104017. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  104018. if (options !== undefined && typeof options === "object") {
  104019. fullOptions.generateMipMaps = options.generateMipMaps;
  104020. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  104021. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  104022. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  104023. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  104024. }
  104025. else {
  104026. fullOptions.generateMipMaps = options;
  104027. fullOptions.generateDepthBuffer = true;
  104028. fullOptions.generateStencilBuffer = false;
  104029. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  104030. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  104031. }
  104032. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  104033. var width = size.width || size;
  104034. var height = size.height || size;
  104035. texture._depthStencilBuffer = {};
  104036. texture._framebuffer = {};
  104037. texture.baseWidth = width;
  104038. texture.baseHeight = height;
  104039. texture.width = width;
  104040. texture.height = height;
  104041. texture.isReady = true;
  104042. texture.samples = 1;
  104043. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  104044. texture.samplingMode = fullOptions.samplingMode;
  104045. texture.type = fullOptions.type;
  104046. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  104047. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  104048. this._internalTexturesCache.push(texture);
  104049. return texture;
  104050. };
  104051. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  104052. texture.samplingMode = samplingMode;
  104053. };
  104054. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  104055. if (this._currentRenderTarget) {
  104056. this.unBindFramebuffer(this._currentRenderTarget);
  104057. }
  104058. this._currentRenderTarget = texture;
  104059. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  104060. if (this._cachedViewport && !forceFullscreenViewport) {
  104061. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  104062. }
  104063. };
  104064. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  104065. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  104066. this._currentRenderTarget = null;
  104067. if (onBeforeUnbind) {
  104068. if (texture._MSAAFramebuffer) {
  104069. this._currentFramebuffer = texture._framebuffer;
  104070. }
  104071. onBeforeUnbind();
  104072. }
  104073. this._currentFramebuffer = null;
  104074. };
  104075. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  104076. var vbo = {
  104077. capacity: 1,
  104078. references: 1,
  104079. is32Bits: false
  104080. };
  104081. return vbo;
  104082. };
  104083. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  104084. if (premulAlpha === void 0) { premulAlpha = false; }
  104085. };
  104086. /**
  104087. * @hidden
  104088. * Get the current error code of the webGL context
  104089. * @returns the error code
  104090. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  104091. */
  104092. NullEngine.prototype.getError = function () {
  104093. return 0;
  104094. };
  104095. /** @hidden */
  104096. NullEngine.prototype._getUnpackAlignement = function () {
  104097. return 1;
  104098. };
  104099. /** @hidden */
  104100. NullEngine.prototype._unpackFlipY = function (value) {
  104101. };
  104102. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  104103. if (offset === void 0) { offset = 0; }
  104104. };
  104105. /**
  104106. * Updates a dynamic vertex buffer.
  104107. * @param vertexBuffer the vertex buffer to update
  104108. * @param data the data used to update the vertex buffer
  104109. * @param byteOffset the byte offset of the data (optional)
  104110. * @param byteLength the byte length of the data (optional)
  104111. */
  104112. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  104113. };
  104114. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  104115. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  104116. this._boundTexturesCache[this._activeChannel] = texture;
  104117. return true;
  104118. }
  104119. return false;
  104120. };
  104121. /** @hidden */
  104122. NullEngine.prototype._bindTexture = function (channel, texture) {
  104123. if (channel < 0) {
  104124. return;
  104125. }
  104126. this._bindTextureDirectly(0, texture);
  104127. };
  104128. /** @hidden */
  104129. NullEngine.prototype._releaseBuffer = function (buffer) {
  104130. buffer.references--;
  104131. if (buffer.references === 0) {
  104132. return true;
  104133. }
  104134. return false;
  104135. };
  104136. NullEngine.prototype.releaseEffects = function () {
  104137. };
  104138. NullEngine.prototype.displayLoadingUI = function () {
  104139. };
  104140. NullEngine.prototype.hideLoadingUI = function () {
  104141. };
  104142. /** @hidden */
  104143. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  104144. if (faceIndex === void 0) { faceIndex = 0; }
  104145. if (lod === void 0) { lod = 0; }
  104146. };
  104147. /** @hidden */
  104148. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  104149. if (faceIndex === void 0) { faceIndex = 0; }
  104150. if (lod === void 0) { lod = 0; }
  104151. };
  104152. /** @hidden */
  104153. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  104154. if (faceIndex === void 0) { faceIndex = 0; }
  104155. if (lod === void 0) { lod = 0; }
  104156. };
  104157. /** @hidden */
  104158. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  104159. if (faceIndex === void 0) { faceIndex = 0; }
  104160. if (lod === void 0) { lod = 0; }
  104161. };
  104162. return NullEngine;
  104163. }(BABYLON.Engine));
  104164. BABYLON.NullEngine = NullEngine;
  104165. })(BABYLON || (BABYLON = {}));
  104166. //# sourceMappingURL=babylon.nullEngine.js.map
  104167. var BABYLON;
  104168. (function (BABYLON) {
  104169. /**
  104170. * This class can be used to get instrumentation data from a Babylon engine
  104171. */
  104172. var EngineInstrumentation = /** @class */ (function () {
  104173. function EngineInstrumentation(engine) {
  104174. this.engine = engine;
  104175. this._captureGPUFrameTime = false;
  104176. this._gpuFrameTime = new BABYLON.PerfCounter();
  104177. this._captureShaderCompilationTime = false;
  104178. this._shaderCompilationTime = new BABYLON.PerfCounter();
  104179. // Observers
  104180. this._onBeginFrameObserver = null;
  104181. this._onEndFrameObserver = null;
  104182. this._onBeforeShaderCompilationObserver = null;
  104183. this._onAfterShaderCompilationObserver = null;
  104184. }
  104185. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  104186. // Properties
  104187. /**
  104188. * Gets the perf counter used for GPU frame time
  104189. */
  104190. get: function () {
  104191. return this._gpuFrameTime;
  104192. },
  104193. enumerable: true,
  104194. configurable: true
  104195. });
  104196. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  104197. /**
  104198. * Gets the GPU frame time capture status
  104199. */
  104200. get: function () {
  104201. return this._captureGPUFrameTime;
  104202. },
  104203. /**
  104204. * Enable or disable the GPU frame time capture
  104205. */
  104206. set: function (value) {
  104207. var _this = this;
  104208. if (value === this._captureGPUFrameTime) {
  104209. return;
  104210. }
  104211. this._captureGPUFrameTime = value;
  104212. if (value) {
  104213. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  104214. if (!_this._gpuFrameTimeToken) {
  104215. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  104216. }
  104217. });
  104218. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  104219. if (!_this._gpuFrameTimeToken) {
  104220. return;
  104221. }
  104222. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  104223. if (time > -1) {
  104224. _this._gpuFrameTimeToken = null;
  104225. _this._gpuFrameTime.fetchNewFrame();
  104226. _this._gpuFrameTime.addCount(time, true);
  104227. }
  104228. });
  104229. }
  104230. else {
  104231. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  104232. this._onBeginFrameObserver = null;
  104233. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  104234. this._onEndFrameObserver = null;
  104235. }
  104236. },
  104237. enumerable: true,
  104238. configurable: true
  104239. });
  104240. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  104241. /**
  104242. * Gets the perf counter used for shader compilation time
  104243. */
  104244. get: function () {
  104245. return this._shaderCompilationTime;
  104246. },
  104247. enumerable: true,
  104248. configurable: true
  104249. });
  104250. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  104251. /**
  104252. * Gets the shader compilation time capture status
  104253. */
  104254. get: function () {
  104255. return this._captureShaderCompilationTime;
  104256. },
  104257. /**
  104258. * Enable or disable the shader compilation time capture
  104259. */
  104260. set: function (value) {
  104261. var _this = this;
  104262. if (value === this._captureShaderCompilationTime) {
  104263. return;
  104264. }
  104265. this._captureShaderCompilationTime = value;
  104266. if (value) {
  104267. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  104268. _this._shaderCompilationTime.fetchNewFrame();
  104269. _this._shaderCompilationTime.beginMonitoring();
  104270. });
  104271. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  104272. _this._shaderCompilationTime.endMonitoring();
  104273. });
  104274. }
  104275. else {
  104276. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  104277. this._onBeforeShaderCompilationObserver = null;
  104278. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  104279. this._onAfterShaderCompilationObserver = null;
  104280. }
  104281. },
  104282. enumerable: true,
  104283. configurable: true
  104284. });
  104285. EngineInstrumentation.prototype.dispose = function () {
  104286. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  104287. this._onBeginFrameObserver = null;
  104288. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  104289. this._onEndFrameObserver = null;
  104290. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  104291. this._onBeforeShaderCompilationObserver = null;
  104292. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  104293. this._onAfterShaderCompilationObserver = null;
  104294. this.engine = null;
  104295. };
  104296. return EngineInstrumentation;
  104297. }());
  104298. BABYLON.EngineInstrumentation = EngineInstrumentation;
  104299. })(BABYLON || (BABYLON = {}));
  104300. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  104301. var BABYLON;
  104302. (function (BABYLON) {
  104303. /**
  104304. * This class can be used to get instrumentation data from a Babylon engine
  104305. */
  104306. var SceneInstrumentation = /** @class */ (function () {
  104307. function SceneInstrumentation(scene) {
  104308. var _this = this;
  104309. this.scene = scene;
  104310. this._captureActiveMeshesEvaluationTime = false;
  104311. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  104312. this._captureRenderTargetsRenderTime = false;
  104313. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  104314. this._captureFrameTime = false;
  104315. this._frameTime = new BABYLON.PerfCounter();
  104316. this._captureRenderTime = false;
  104317. this._renderTime = new BABYLON.PerfCounter();
  104318. this._captureInterFrameTime = false;
  104319. this._interFrameTime = new BABYLON.PerfCounter();
  104320. this._captureParticlesRenderTime = false;
  104321. this._particlesRenderTime = new BABYLON.PerfCounter();
  104322. this._captureSpritesRenderTime = false;
  104323. this._spritesRenderTime = new BABYLON.PerfCounter();
  104324. this._capturePhysicsTime = false;
  104325. this._physicsTime = new BABYLON.PerfCounter();
  104326. this._captureAnimationsTime = false;
  104327. this._animationsTime = new BABYLON.PerfCounter();
  104328. this._captureCameraRenderTime = false;
  104329. this._cameraRenderTime = new BABYLON.PerfCounter();
  104330. // Observers
  104331. this._onBeforeActiveMeshesEvaluationObserver = null;
  104332. this._onAfterActiveMeshesEvaluationObserver = null;
  104333. this._onBeforeRenderTargetsRenderObserver = null;
  104334. this._onAfterRenderTargetsRenderObserver = null;
  104335. this._onAfterRenderObserver = null;
  104336. this._onBeforeDrawPhaseObserver = null;
  104337. this._onAfterDrawPhaseObserver = null;
  104338. this._onBeforeAnimationsObserver = null;
  104339. this._onBeforeParticlesRenderingObserver = null;
  104340. this._onAfterParticlesRenderingObserver = null;
  104341. this._onBeforeSpritesRenderingObserver = null;
  104342. this._onAfterSpritesRenderingObserver = null;
  104343. this._onBeforePhysicsObserver = null;
  104344. this._onAfterPhysicsObserver = null;
  104345. this._onAfterAnimationsObserver = null;
  104346. this._onBeforeCameraRenderObserver = null;
  104347. this._onAfterCameraRenderObserver = null;
  104348. // Before render
  104349. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  104350. if (_this._captureActiveMeshesEvaluationTime) {
  104351. _this._activeMeshesEvaluationTime.fetchNewFrame();
  104352. }
  104353. if (_this._captureRenderTargetsRenderTime) {
  104354. _this._renderTargetsRenderTime.fetchNewFrame();
  104355. }
  104356. if (_this._captureFrameTime) {
  104357. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  104358. _this._frameTime.beginMonitoring();
  104359. }
  104360. if (_this._captureInterFrameTime) {
  104361. _this._interFrameTime.endMonitoring();
  104362. }
  104363. if (_this._captureParticlesRenderTime) {
  104364. _this._particlesRenderTime.fetchNewFrame();
  104365. }
  104366. if (_this._captureSpritesRenderTime) {
  104367. _this._spritesRenderTime.fetchNewFrame();
  104368. }
  104369. if (_this._captureAnimationsTime) {
  104370. _this._animationsTime.beginMonitoring();
  104371. }
  104372. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  104373. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  104374. });
  104375. // After render
  104376. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  104377. if (_this._captureFrameTime) {
  104378. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  104379. _this._frameTime.endMonitoring();
  104380. }
  104381. if (_this._captureRenderTime) {
  104382. _this._renderTime.endMonitoring(false);
  104383. }
  104384. if (_this._captureInterFrameTime) {
  104385. _this._interFrameTime.beginMonitoring();
  104386. }
  104387. });
  104388. }
  104389. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  104390. // Properties
  104391. /**
  104392. * Gets the perf counter used for active meshes evaluation time
  104393. */
  104394. get: function () {
  104395. return this._activeMeshesEvaluationTime;
  104396. },
  104397. enumerable: true,
  104398. configurable: true
  104399. });
  104400. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  104401. /**
  104402. * Gets the active meshes evaluation time capture status
  104403. */
  104404. get: function () {
  104405. return this._captureActiveMeshesEvaluationTime;
  104406. },
  104407. /**
  104408. * Enable or disable the active meshes evaluation time capture
  104409. */
  104410. set: function (value) {
  104411. var _this = this;
  104412. if (value === this._captureActiveMeshesEvaluationTime) {
  104413. return;
  104414. }
  104415. this._captureActiveMeshesEvaluationTime = value;
  104416. if (value) {
  104417. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  104418. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  104419. _this._activeMeshesEvaluationTime.beginMonitoring();
  104420. });
  104421. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  104422. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  104423. _this._activeMeshesEvaluationTime.endMonitoring();
  104424. });
  104425. }
  104426. else {
  104427. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  104428. this._onBeforeActiveMeshesEvaluationObserver = null;
  104429. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  104430. this._onAfterActiveMeshesEvaluationObserver = null;
  104431. }
  104432. },
  104433. enumerable: true,
  104434. configurable: true
  104435. });
  104436. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  104437. /**
  104438. * Gets the perf counter used for render targets render time
  104439. */
  104440. get: function () {
  104441. return this._renderTargetsRenderTime;
  104442. },
  104443. enumerable: true,
  104444. configurable: true
  104445. });
  104446. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  104447. /**
  104448. * Gets the render targets render time capture status
  104449. */
  104450. get: function () {
  104451. return this._captureRenderTargetsRenderTime;
  104452. },
  104453. /**
  104454. * Enable or disable the render targets render time capture
  104455. */
  104456. set: function (value) {
  104457. var _this = this;
  104458. if (value === this._captureRenderTargetsRenderTime) {
  104459. return;
  104460. }
  104461. this._captureRenderTargetsRenderTime = value;
  104462. if (value) {
  104463. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  104464. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  104465. _this._renderTargetsRenderTime.beginMonitoring();
  104466. });
  104467. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  104468. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  104469. _this._renderTargetsRenderTime.endMonitoring(false);
  104470. });
  104471. }
  104472. else {
  104473. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  104474. this._onBeforeRenderTargetsRenderObserver = null;
  104475. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  104476. this._onAfterRenderTargetsRenderObserver = null;
  104477. }
  104478. },
  104479. enumerable: true,
  104480. configurable: true
  104481. });
  104482. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  104483. /**
  104484. * Gets the perf counter used for particles render time
  104485. */
  104486. get: function () {
  104487. return this._particlesRenderTime;
  104488. },
  104489. enumerable: true,
  104490. configurable: true
  104491. });
  104492. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  104493. /**
  104494. * Gets the particles render time capture status
  104495. */
  104496. get: function () {
  104497. return this._captureParticlesRenderTime;
  104498. },
  104499. /**
  104500. * Enable or disable the particles render time capture
  104501. */
  104502. set: function (value) {
  104503. var _this = this;
  104504. if (value === this._captureParticlesRenderTime) {
  104505. return;
  104506. }
  104507. this._captureParticlesRenderTime = value;
  104508. if (value) {
  104509. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  104510. BABYLON.Tools.StartPerformanceCounter("Particles");
  104511. _this._particlesRenderTime.beginMonitoring();
  104512. });
  104513. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  104514. BABYLON.Tools.EndPerformanceCounter("Particles");
  104515. _this._particlesRenderTime.endMonitoring(false);
  104516. });
  104517. }
  104518. else {
  104519. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  104520. this._onBeforeParticlesRenderingObserver = null;
  104521. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  104522. this._onAfterParticlesRenderingObserver = null;
  104523. }
  104524. },
  104525. enumerable: true,
  104526. configurable: true
  104527. });
  104528. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  104529. /**
  104530. * Gets the perf counter used for sprites render time
  104531. */
  104532. get: function () {
  104533. return this._spritesRenderTime;
  104534. },
  104535. enumerable: true,
  104536. configurable: true
  104537. });
  104538. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  104539. /**
  104540. * Gets the sprites render time capture status
  104541. */
  104542. get: function () {
  104543. return this._captureSpritesRenderTime;
  104544. },
  104545. /**
  104546. * Enable or disable the sprites render time capture
  104547. */
  104548. set: function (value) {
  104549. var _this = this;
  104550. if (value === this._captureSpritesRenderTime) {
  104551. return;
  104552. }
  104553. this._captureSpritesRenderTime = value;
  104554. if (value) {
  104555. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  104556. BABYLON.Tools.StartPerformanceCounter("Sprites");
  104557. _this._spritesRenderTime.beginMonitoring();
  104558. });
  104559. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  104560. BABYLON.Tools.EndPerformanceCounter("Sprites");
  104561. _this._spritesRenderTime.endMonitoring(false);
  104562. });
  104563. }
  104564. else {
  104565. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  104566. this._onBeforeSpritesRenderingObserver = null;
  104567. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  104568. this._onAfterSpritesRenderingObserver = null;
  104569. }
  104570. },
  104571. enumerable: true,
  104572. configurable: true
  104573. });
  104574. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  104575. /**
  104576. * Gets the perf counter used for physics time
  104577. */
  104578. get: function () {
  104579. return this._physicsTime;
  104580. },
  104581. enumerable: true,
  104582. configurable: true
  104583. });
  104584. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  104585. /**
  104586. * Gets the physics time capture status
  104587. */
  104588. get: function () {
  104589. return this._capturePhysicsTime;
  104590. },
  104591. /**
  104592. * Enable or disable the physics time capture
  104593. */
  104594. set: function (value) {
  104595. var _this = this;
  104596. if (value === this._capturePhysicsTime) {
  104597. return;
  104598. }
  104599. this._capturePhysicsTime = value;
  104600. if (value) {
  104601. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  104602. BABYLON.Tools.StartPerformanceCounter("Physics");
  104603. _this._physicsTime.beginMonitoring();
  104604. });
  104605. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  104606. BABYLON.Tools.EndPerformanceCounter("Physics");
  104607. _this._physicsTime.endMonitoring();
  104608. });
  104609. }
  104610. else {
  104611. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  104612. this._onBeforePhysicsObserver = null;
  104613. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  104614. this._onAfterPhysicsObserver = null;
  104615. }
  104616. },
  104617. enumerable: true,
  104618. configurable: true
  104619. });
  104620. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  104621. /**
  104622. * Gets the perf counter used for animations time
  104623. */
  104624. get: function () {
  104625. return this._animationsTime;
  104626. },
  104627. enumerable: true,
  104628. configurable: true
  104629. });
  104630. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  104631. /**
  104632. * Gets the animations time capture status
  104633. */
  104634. get: function () {
  104635. return this._captureAnimationsTime;
  104636. },
  104637. /**
  104638. * Enable or disable the animations time capture
  104639. */
  104640. set: function (value) {
  104641. var _this = this;
  104642. if (value === this._captureAnimationsTime) {
  104643. return;
  104644. }
  104645. this._captureAnimationsTime = value;
  104646. if (value) {
  104647. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  104648. _this._animationsTime.endMonitoring();
  104649. });
  104650. }
  104651. else {
  104652. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  104653. this._onAfterAnimationsObserver = null;
  104654. }
  104655. },
  104656. enumerable: true,
  104657. configurable: true
  104658. });
  104659. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  104660. /**
  104661. * Gets the perf counter used for frame time capture
  104662. */
  104663. get: function () {
  104664. return this._frameTime;
  104665. },
  104666. enumerable: true,
  104667. configurable: true
  104668. });
  104669. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  104670. /**
  104671. * Gets the frame time capture status
  104672. */
  104673. get: function () {
  104674. return this._captureFrameTime;
  104675. },
  104676. /**
  104677. * Enable or disable the frame time capture
  104678. */
  104679. set: function (value) {
  104680. this._captureFrameTime = value;
  104681. },
  104682. enumerable: true,
  104683. configurable: true
  104684. });
  104685. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  104686. /**
  104687. * Gets the perf counter used for inter-frames time capture
  104688. */
  104689. get: function () {
  104690. return this._interFrameTime;
  104691. },
  104692. enumerable: true,
  104693. configurable: true
  104694. });
  104695. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  104696. /**
  104697. * Gets the inter-frames time capture status
  104698. */
  104699. get: function () {
  104700. return this._captureInterFrameTime;
  104701. },
  104702. /**
  104703. * Enable or disable the inter-frames time capture
  104704. */
  104705. set: function (value) {
  104706. this._captureInterFrameTime = value;
  104707. },
  104708. enumerable: true,
  104709. configurable: true
  104710. });
  104711. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  104712. /**
  104713. * Gets the perf counter used for render time capture
  104714. */
  104715. get: function () {
  104716. return this._renderTime;
  104717. },
  104718. enumerable: true,
  104719. configurable: true
  104720. });
  104721. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  104722. /**
  104723. * Gets the render time capture status
  104724. */
  104725. get: function () {
  104726. return this._captureRenderTime;
  104727. },
  104728. /**
  104729. * Enable or disable the render time capture
  104730. */
  104731. set: function (value) {
  104732. var _this = this;
  104733. if (value === this._captureRenderTime) {
  104734. return;
  104735. }
  104736. this._captureRenderTime = value;
  104737. if (value) {
  104738. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  104739. _this._renderTime.beginMonitoring();
  104740. BABYLON.Tools.StartPerformanceCounter("Main render");
  104741. });
  104742. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  104743. _this._renderTime.endMonitoring(false);
  104744. BABYLON.Tools.EndPerformanceCounter("Main render");
  104745. });
  104746. }
  104747. else {
  104748. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  104749. this._onBeforeDrawPhaseObserver = null;
  104750. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  104751. this._onAfterDrawPhaseObserver = null;
  104752. }
  104753. },
  104754. enumerable: true,
  104755. configurable: true
  104756. });
  104757. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  104758. /**
  104759. * Gets the perf counter used for camera render time capture
  104760. */
  104761. get: function () {
  104762. return this._cameraRenderTime;
  104763. },
  104764. enumerable: true,
  104765. configurable: true
  104766. });
  104767. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  104768. /**
  104769. * Gets the camera render time capture status
  104770. */
  104771. get: function () {
  104772. return this._captureCameraRenderTime;
  104773. },
  104774. /**
  104775. * Enable or disable the camera render time capture
  104776. */
  104777. set: function (value) {
  104778. var _this = this;
  104779. if (value === this._captureCameraRenderTime) {
  104780. return;
  104781. }
  104782. this._captureCameraRenderTime = value;
  104783. if (value) {
  104784. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  104785. _this._cameraRenderTime.beginMonitoring();
  104786. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  104787. });
  104788. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  104789. _this._cameraRenderTime.endMonitoring(false);
  104790. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  104791. });
  104792. }
  104793. else {
  104794. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  104795. this._onBeforeCameraRenderObserver = null;
  104796. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  104797. this._onAfterCameraRenderObserver = null;
  104798. }
  104799. },
  104800. enumerable: true,
  104801. configurable: true
  104802. });
  104803. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  104804. /**
  104805. * Gets the perf counter used for draw calls
  104806. */
  104807. get: function () {
  104808. return this.scene.getEngine()._drawCalls;
  104809. },
  104810. enumerable: true,
  104811. configurable: true
  104812. });
  104813. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  104814. /**
  104815. * Gets the perf counter used for texture collisions
  104816. */
  104817. get: function () {
  104818. return this.scene.getEngine()._textureCollisions;
  104819. },
  104820. enumerable: true,
  104821. configurable: true
  104822. });
  104823. SceneInstrumentation.prototype.dispose = function () {
  104824. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  104825. this._onAfterRenderObserver = null;
  104826. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  104827. this._onBeforeActiveMeshesEvaluationObserver = null;
  104828. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  104829. this._onAfterActiveMeshesEvaluationObserver = null;
  104830. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  104831. this._onBeforeRenderTargetsRenderObserver = null;
  104832. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  104833. this._onAfterRenderTargetsRenderObserver = null;
  104834. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  104835. this._onBeforeAnimationsObserver = null;
  104836. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  104837. this._onBeforeParticlesRenderingObserver = null;
  104838. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  104839. this._onAfterParticlesRenderingObserver = null;
  104840. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  104841. this._onBeforeSpritesRenderingObserver = null;
  104842. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  104843. this._onAfterSpritesRenderingObserver = null;
  104844. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  104845. this._onBeforeDrawPhaseObserver = null;
  104846. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  104847. this._onAfterDrawPhaseObserver = null;
  104848. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  104849. this._onBeforePhysicsObserver = null;
  104850. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  104851. this._onAfterPhysicsObserver = null;
  104852. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  104853. this._onAfterAnimationsObserver = null;
  104854. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  104855. this._onBeforeCameraRenderObserver = null;
  104856. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  104857. this._onAfterCameraRenderObserver = null;
  104858. this.scene = null;
  104859. };
  104860. return SceneInstrumentation;
  104861. }());
  104862. BABYLON.SceneInstrumentation = SceneInstrumentation;
  104863. })(BABYLON || (BABYLON = {}));
  104864. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  104865. var BABYLON;
  104866. (function (BABYLON) {
  104867. /**
  104868. * @hidden
  104869. **/
  104870. var _TimeToken = /** @class */ (function () {
  104871. function _TimeToken() {
  104872. this._timeElapsedQueryEnded = false;
  104873. }
  104874. return _TimeToken;
  104875. }());
  104876. BABYLON._TimeToken = _TimeToken;
  104877. })(BABYLON || (BABYLON = {}));
  104878. //# sourceMappingURL=babylon.timeToken.js.map
  104879. var BABYLON;
  104880. (function (BABYLON) {
  104881. /**
  104882. * Background material defines definition.
  104883. * @hidden Mainly internal Use
  104884. */
  104885. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  104886. __extends(BackgroundMaterialDefines, _super);
  104887. /**
  104888. * Constructor of the defines.
  104889. */
  104890. function BackgroundMaterialDefines() {
  104891. var _this = _super.call(this) || this;
  104892. /**
  104893. * True if the diffuse texture is in use.
  104894. */
  104895. _this.DIFFUSE = false;
  104896. /**
  104897. * The direct UV channel to use.
  104898. */
  104899. _this.DIFFUSEDIRECTUV = 0;
  104900. /**
  104901. * True if the diffuse texture is in gamma space.
  104902. */
  104903. _this.GAMMADIFFUSE = false;
  104904. /**
  104905. * True if the diffuse texture has opacity in the alpha channel.
  104906. */
  104907. _this.DIFFUSEHASALPHA = false;
  104908. /**
  104909. * True if you want the material to fade to transparent at grazing angle.
  104910. */
  104911. _this.OPACITYFRESNEL = false;
  104912. /**
  104913. * True if an extra blur needs to be added in the reflection.
  104914. */
  104915. _this.REFLECTIONBLUR = false;
  104916. /**
  104917. * True if you want the material to fade to reflection at grazing angle.
  104918. */
  104919. _this.REFLECTIONFRESNEL = false;
  104920. /**
  104921. * True if you want the material to falloff as far as you move away from the scene center.
  104922. */
  104923. _this.REFLECTIONFALLOFF = false;
  104924. /**
  104925. * False if the current Webgl implementation does not support the texture lod extension.
  104926. */
  104927. _this.TEXTURELODSUPPORT = false;
  104928. /**
  104929. * True to ensure the data are premultiplied.
  104930. */
  104931. _this.PREMULTIPLYALPHA = false;
  104932. /**
  104933. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  104934. */
  104935. _this.USERGBCOLOR = false;
  104936. /**
  104937. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  104938. * stays aligned with the desired configuration.
  104939. */
  104940. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  104941. /**
  104942. * True to add noise in order to reduce the banding effect.
  104943. */
  104944. _this.NOISE = false;
  104945. /**
  104946. * is the reflection texture in BGR color scheme?
  104947. * Mainly used to solve a bug in ios10 video tag
  104948. */
  104949. _this.REFLECTIONBGR = false;
  104950. _this.IMAGEPROCESSING = false;
  104951. _this.VIGNETTE = false;
  104952. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  104953. _this.VIGNETTEBLENDMODEOPAQUE = false;
  104954. _this.TONEMAPPING = false;
  104955. _this.TONEMAPPING_ACES = false;
  104956. _this.CONTRAST = false;
  104957. _this.COLORCURVES = false;
  104958. _this.COLORGRADING = false;
  104959. _this.COLORGRADING3D = false;
  104960. _this.SAMPLER3DGREENDEPTH = false;
  104961. _this.SAMPLER3DBGRMAP = false;
  104962. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  104963. _this.EXPOSURE = false;
  104964. // Reflection.
  104965. _this.REFLECTION = false;
  104966. _this.REFLECTIONMAP_3D = false;
  104967. _this.REFLECTIONMAP_SPHERICAL = false;
  104968. _this.REFLECTIONMAP_PLANAR = false;
  104969. _this.REFLECTIONMAP_CUBIC = false;
  104970. _this.REFLECTIONMAP_PROJECTION = false;
  104971. _this.REFLECTIONMAP_SKYBOX = false;
  104972. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  104973. _this.REFLECTIONMAP_EXPLICIT = false;
  104974. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  104975. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  104976. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  104977. _this.INVERTCUBICMAP = false;
  104978. _this.REFLECTIONMAP_OPPOSITEZ = false;
  104979. _this.LODINREFLECTIONALPHA = false;
  104980. _this.GAMMAREFLECTION = false;
  104981. _this.RGBDREFLECTION = false;
  104982. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  104983. // Default BJS.
  104984. _this.MAINUV1 = false;
  104985. _this.MAINUV2 = false;
  104986. _this.UV1 = false;
  104987. _this.UV2 = false;
  104988. _this.CLIPPLANE = false;
  104989. _this.CLIPPLANE2 = false;
  104990. _this.CLIPPLANE3 = false;
  104991. _this.CLIPPLANE4 = false;
  104992. _this.POINTSIZE = false;
  104993. _this.FOG = false;
  104994. _this.NORMAL = false;
  104995. _this.NUM_BONE_INFLUENCERS = 0;
  104996. _this.BonesPerMesh = 0;
  104997. _this.INSTANCES = false;
  104998. _this.SHADOWFLOAT = false;
  104999. _this.rebuild();
  105000. return _this;
  105001. }
  105002. return BackgroundMaterialDefines;
  105003. }(BABYLON.MaterialDefines));
  105004. /**
  105005. * Background material used to create an efficient environement around your scene.
  105006. */
  105007. var BackgroundMaterial = /** @class */ (function (_super) {
  105008. __extends(BackgroundMaterial, _super);
  105009. /**
  105010. * Instantiates a Background Material in the given scene
  105011. * @param name The friendly name of the material
  105012. * @param scene The scene to add the material to
  105013. */
  105014. function BackgroundMaterial(name, scene) {
  105015. var _this = _super.call(this, name, scene) || this;
  105016. /**
  105017. * Key light Color (multiply against the environement texture)
  105018. */
  105019. _this.primaryColor = BABYLON.Color3.White();
  105020. _this._primaryColorShadowLevel = 0;
  105021. _this._primaryColorHighlightLevel = 0;
  105022. /**
  105023. * Reflection Texture used in the material.
  105024. * Should be author in a specific way for the best result (refer to the documentation).
  105025. */
  105026. _this.reflectionTexture = null;
  105027. /**
  105028. * Reflection Texture level of blur.
  105029. *
  105030. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  105031. * texture twice.
  105032. */
  105033. _this.reflectionBlur = 0;
  105034. /**
  105035. * Diffuse Texture used in the material.
  105036. * Should be author in a specific way for the best result (refer to the documentation).
  105037. */
  105038. _this.diffuseTexture = null;
  105039. _this._shadowLights = null;
  105040. /**
  105041. * Specify the list of lights casting shadow on the material.
  105042. * All scene shadow lights will be included if null.
  105043. */
  105044. _this.shadowLights = null;
  105045. /**
  105046. * Helps adjusting the shadow to a softer level if required.
  105047. * 0 means black shadows and 1 means no shadows.
  105048. */
  105049. _this.shadowLevel = 0;
  105050. /**
  105051. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  105052. * It is usually zero but might be interesting to modify according to your setup.
  105053. */
  105054. _this.sceneCenter = BABYLON.Vector3.Zero();
  105055. /**
  105056. * This helps specifying that the material is falling off to the sky box at grazing angle.
  105057. * This helps ensuring a nice transition when the camera goes under the ground.
  105058. */
  105059. _this.opacityFresnel = true;
  105060. /**
  105061. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  105062. * This helps adding a mirror texture on the ground.
  105063. */
  105064. _this.reflectionFresnel = false;
  105065. /**
  105066. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  105067. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  105068. */
  105069. _this.reflectionFalloffDistance = 0.0;
  105070. /**
  105071. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  105072. */
  105073. _this.reflectionAmount = 1.0;
  105074. /**
  105075. * This specifies the weight of the reflection at grazing angle.
  105076. */
  105077. _this.reflectionReflectance0 = 0.05;
  105078. /**
  105079. * This specifies the weight of the reflection at a perpendicular point of view.
  105080. */
  105081. _this.reflectionReflectance90 = 0.5;
  105082. /**
  105083. * Helps to directly use the maps channels instead of their level.
  105084. */
  105085. _this.useRGBColor = true;
  105086. /**
  105087. * This helps reducing the banding effect that could occur on the background.
  105088. */
  105089. _this.enableNoise = false;
  105090. _this._fovMultiplier = 1.0;
  105091. /**
  105092. * Enable the FOV adjustment feature controlled by fovMultiplier.
  105093. */
  105094. _this.useEquirectangularFOV = false;
  105095. _this._maxSimultaneousLights = 4;
  105096. /**
  105097. * Number of Simultaneous lights allowed on the material.
  105098. */
  105099. _this.maxSimultaneousLights = 4;
  105100. /**
  105101. * Keep track of the image processing observer to allow dispose and replace.
  105102. */
  105103. _this._imageProcessingObserver = null;
  105104. /**
  105105. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  105106. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  105107. */
  105108. _this.switchToBGR = false;
  105109. // Temp values kept as cache in the material.
  105110. _this._renderTargets = new BABYLON.SmartArray(16);
  105111. _this._reflectionControls = BABYLON.Vector4.Zero();
  105112. _this._white = BABYLON.Color3.White();
  105113. _this._primaryShadowColor = BABYLON.Color3.Black();
  105114. _this._primaryHighlightColor = BABYLON.Color3.Black();
  105115. // Setup the default processing configuration to the scene.
  105116. _this._attachImageProcessingConfiguration(null);
  105117. _this.getRenderTargetTextures = function () {
  105118. _this._renderTargets.reset();
  105119. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  105120. _this._renderTargets.push(_this._diffuseTexture);
  105121. }
  105122. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  105123. _this._renderTargets.push(_this._reflectionTexture);
  105124. }
  105125. return _this._renderTargets;
  105126. };
  105127. return _this;
  105128. }
  105129. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  105130. /**
  105131. * Experimental Internal Use Only.
  105132. *
  105133. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  105134. * This acts as a helper to set the primary color to a more "human friendly" value.
  105135. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  105136. * output color as close as possible from the chosen value.
  105137. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  105138. * part of lighting setup.)
  105139. */
  105140. get: function () {
  105141. return this.__perceptualColor;
  105142. },
  105143. set: function (value) {
  105144. this.__perceptualColor = value;
  105145. this._computePrimaryColorFromPerceptualColor();
  105146. this._markAllSubMeshesAsLightsDirty();
  105147. },
  105148. enumerable: true,
  105149. configurable: true
  105150. });
  105151. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  105152. /**
  105153. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  105154. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  105155. */
  105156. get: function () {
  105157. return this._primaryColorShadowLevel;
  105158. },
  105159. set: function (value) {
  105160. this._primaryColorShadowLevel = value;
  105161. this._computePrimaryColors();
  105162. this._markAllSubMeshesAsLightsDirty();
  105163. },
  105164. enumerable: true,
  105165. configurable: true
  105166. });
  105167. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  105168. /**
  105169. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  105170. * The primary color is used at the level chosen to define what the white area would look.
  105171. */
  105172. get: function () {
  105173. return this._primaryColorHighlightLevel;
  105174. },
  105175. set: function (value) {
  105176. this._primaryColorHighlightLevel = value;
  105177. this._computePrimaryColors();
  105178. this._markAllSubMeshesAsLightsDirty();
  105179. },
  105180. enumerable: true,
  105181. configurable: true
  105182. });
  105183. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  105184. /**
  105185. * Sets the reflection reflectance fresnel values according to the default standard
  105186. * empirically know to work well :-)
  105187. */
  105188. set: function (value) {
  105189. var reflectionWeight = value;
  105190. if (reflectionWeight < 0.5) {
  105191. reflectionWeight = reflectionWeight * 2.0;
  105192. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  105193. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  105194. }
  105195. else {
  105196. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  105197. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  105198. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  105199. }
  105200. },
  105201. enumerable: true,
  105202. configurable: true
  105203. });
  105204. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  105205. /**
  105206. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  105207. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  105208. * Recommended to be keep at 1.0 except for special cases.
  105209. */
  105210. get: function () {
  105211. return this._fovMultiplier;
  105212. },
  105213. set: function (value) {
  105214. if (isNaN(value)) {
  105215. value = 1.0;
  105216. }
  105217. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  105218. },
  105219. enumerable: true,
  105220. configurable: true
  105221. });
  105222. /**
  105223. * Attaches a new image processing configuration to the PBR Material.
  105224. * @param configuration (if null the scene configuration will be use)
  105225. */
  105226. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  105227. var _this = this;
  105228. if (configuration === this._imageProcessingConfiguration) {
  105229. return;
  105230. }
  105231. // Detaches observer.
  105232. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  105233. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  105234. }
  105235. // Pick the scene configuration if needed.
  105236. if (!configuration) {
  105237. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  105238. }
  105239. else {
  105240. this._imageProcessingConfiguration = configuration;
  105241. }
  105242. // Attaches observer.
  105243. if (this._imageProcessingConfiguration) {
  105244. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  105245. _this._computePrimaryColorFromPerceptualColor();
  105246. _this._markAllSubMeshesAsImageProcessingDirty();
  105247. });
  105248. }
  105249. };
  105250. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  105251. /**
  105252. * Gets the image processing configuration used either in this material.
  105253. */
  105254. get: function () {
  105255. return this._imageProcessingConfiguration;
  105256. },
  105257. /**
  105258. * Sets the Default image processing configuration used either in the this material.
  105259. *
  105260. * If sets to null, the scene one is in use.
  105261. */
  105262. set: function (value) {
  105263. this._attachImageProcessingConfiguration(value);
  105264. // Ensure the effect will be rebuilt.
  105265. this._markAllSubMeshesAsTexturesDirty();
  105266. },
  105267. enumerable: true,
  105268. configurable: true
  105269. });
  105270. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  105271. /**
  105272. * Gets wether the color curves effect is enabled.
  105273. */
  105274. get: function () {
  105275. return this.imageProcessingConfiguration.colorCurvesEnabled;
  105276. },
  105277. /**
  105278. * Sets wether the color curves effect is enabled.
  105279. */
  105280. set: function (value) {
  105281. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  105282. },
  105283. enumerable: true,
  105284. configurable: true
  105285. });
  105286. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  105287. /**
  105288. * Gets wether the color grading effect is enabled.
  105289. */
  105290. get: function () {
  105291. return this.imageProcessingConfiguration.colorGradingEnabled;
  105292. },
  105293. /**
  105294. * Gets wether the color grading effect is enabled.
  105295. */
  105296. set: function (value) {
  105297. this.imageProcessingConfiguration.colorGradingEnabled = value;
  105298. },
  105299. enumerable: true,
  105300. configurable: true
  105301. });
  105302. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  105303. /**
  105304. * Gets wether tonemapping is enabled or not.
  105305. */
  105306. get: function () {
  105307. return this._imageProcessingConfiguration.toneMappingEnabled;
  105308. },
  105309. /**
  105310. * Sets wether tonemapping is enabled or not
  105311. */
  105312. set: function (value) {
  105313. this._imageProcessingConfiguration.toneMappingEnabled = value;
  105314. },
  105315. enumerable: true,
  105316. configurable: true
  105317. });
  105318. ;
  105319. ;
  105320. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  105321. /**
  105322. * The camera exposure used on this material.
  105323. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  105324. * This corresponds to a photographic exposure.
  105325. */
  105326. get: function () {
  105327. return this._imageProcessingConfiguration.exposure;
  105328. },
  105329. /**
  105330. * The camera exposure used on this material.
  105331. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  105332. * This corresponds to a photographic exposure.
  105333. */
  105334. set: function (value) {
  105335. this._imageProcessingConfiguration.exposure = value;
  105336. },
  105337. enumerable: true,
  105338. configurable: true
  105339. });
  105340. ;
  105341. ;
  105342. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  105343. /**
  105344. * Gets The camera contrast used on this material.
  105345. */
  105346. get: function () {
  105347. return this._imageProcessingConfiguration.contrast;
  105348. },
  105349. /**
  105350. * Sets The camera contrast used on this material.
  105351. */
  105352. set: function (value) {
  105353. this._imageProcessingConfiguration.contrast = value;
  105354. },
  105355. enumerable: true,
  105356. configurable: true
  105357. });
  105358. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  105359. /**
  105360. * Gets the Color Grading 2D Lookup Texture.
  105361. */
  105362. get: function () {
  105363. return this._imageProcessingConfiguration.colorGradingTexture;
  105364. },
  105365. /**
  105366. * Sets the Color Grading 2D Lookup Texture.
  105367. */
  105368. set: function (value) {
  105369. this.imageProcessingConfiguration.colorGradingTexture = value;
  105370. },
  105371. enumerable: true,
  105372. configurable: true
  105373. });
  105374. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  105375. /**
  105376. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  105377. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  105378. * 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;
  105379. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  105380. */
  105381. get: function () {
  105382. return this.imageProcessingConfiguration.colorCurves;
  105383. },
  105384. /**
  105385. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  105386. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  105387. * 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;
  105388. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  105389. */
  105390. set: function (value) {
  105391. this.imageProcessingConfiguration.colorCurves = value;
  105392. },
  105393. enumerable: true,
  105394. configurable: true
  105395. });
  105396. /**
  105397. * The entire material has been created in order to prevent overdraw.
  105398. * @returns false
  105399. */
  105400. BackgroundMaterial.prototype.needAlphaTesting = function () {
  105401. return true;
  105402. };
  105403. /**
  105404. * The entire material has been created in order to prevent overdraw.
  105405. * @returns true if blending is enable
  105406. */
  105407. BackgroundMaterial.prototype.needAlphaBlending = function () {
  105408. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  105409. };
  105410. /**
  105411. * Checks wether the material is ready to be rendered for a given mesh.
  105412. * @param mesh The mesh to render
  105413. * @param subMesh The submesh to check against
  105414. * @param useInstances Specify wether or not the material is used with instances
  105415. * @returns true if all the dependencies are ready (Textures, Effects...)
  105416. */
  105417. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  105418. var _this = this;
  105419. if (useInstances === void 0) { useInstances = false; }
  105420. if (subMesh.effect && this.isFrozen) {
  105421. if (this._wasPreviouslyReady) {
  105422. return true;
  105423. }
  105424. }
  105425. if (!subMesh._materialDefines) {
  105426. subMesh._materialDefines = new BackgroundMaterialDefines();
  105427. }
  105428. var scene = this.getScene();
  105429. var defines = subMesh._materialDefines;
  105430. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  105431. if (defines._renderId === scene.getRenderId()) {
  105432. return true;
  105433. }
  105434. }
  105435. var engine = scene.getEngine();
  105436. // Lights
  105437. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  105438. defines._needNormals = true;
  105439. // Textures
  105440. if (defines._areTexturesDirty) {
  105441. defines._needUVs = false;
  105442. if (scene.texturesEnabled) {
  105443. if (scene.getEngine().getCaps().textureLOD) {
  105444. defines.TEXTURELODSUPPORT = true;
  105445. }
  105446. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105447. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  105448. return false;
  105449. }
  105450. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  105451. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  105452. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  105453. defines.OPACITYFRESNEL = this._opacityFresnel;
  105454. }
  105455. else {
  105456. defines.DIFFUSE = false;
  105457. defines.DIFFUSEHASALPHA = false;
  105458. defines.GAMMADIFFUSE = false;
  105459. defines.OPACITYFRESNEL = false;
  105460. }
  105461. var reflectionTexture = this._reflectionTexture;
  105462. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105463. if (!reflectionTexture.isReadyOrNotBlocking()) {
  105464. return false;
  105465. }
  105466. defines.REFLECTION = true;
  105467. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  105468. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  105469. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  105470. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  105471. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  105472. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  105473. defines.REFLECTIONBGR = this.switchToBGR;
  105474. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  105475. defines.INVERTCUBICMAP = true;
  105476. }
  105477. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  105478. switch (reflectionTexture.coordinatesMode) {
  105479. case BABYLON.Texture.EXPLICIT_MODE:
  105480. defines.REFLECTIONMAP_EXPLICIT = true;
  105481. break;
  105482. case BABYLON.Texture.PLANAR_MODE:
  105483. defines.REFLECTIONMAP_PLANAR = true;
  105484. break;
  105485. case BABYLON.Texture.PROJECTION_MODE:
  105486. defines.REFLECTIONMAP_PROJECTION = true;
  105487. break;
  105488. case BABYLON.Texture.SKYBOX_MODE:
  105489. defines.REFLECTIONMAP_SKYBOX = true;
  105490. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  105491. break;
  105492. case BABYLON.Texture.SPHERICAL_MODE:
  105493. defines.REFLECTIONMAP_SPHERICAL = true;
  105494. break;
  105495. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  105496. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  105497. break;
  105498. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  105499. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  105500. break;
  105501. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  105502. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  105503. break;
  105504. case BABYLON.Texture.CUBIC_MODE:
  105505. case BABYLON.Texture.INVCUBIC_MODE:
  105506. default:
  105507. defines.REFLECTIONMAP_CUBIC = true;
  105508. break;
  105509. }
  105510. if (this.reflectionFresnel) {
  105511. defines.REFLECTIONFRESNEL = true;
  105512. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  105513. this._reflectionControls.x = this.reflectionAmount;
  105514. this._reflectionControls.y = this.reflectionReflectance0;
  105515. this._reflectionControls.z = this.reflectionReflectance90;
  105516. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  105517. }
  105518. else {
  105519. defines.REFLECTIONFRESNEL = false;
  105520. defines.REFLECTIONFALLOFF = false;
  105521. }
  105522. }
  105523. else {
  105524. defines.REFLECTION = false;
  105525. defines.REFLECTIONFRESNEL = false;
  105526. defines.REFLECTIONFALLOFF = false;
  105527. defines.REFLECTIONBLUR = false;
  105528. defines.REFLECTIONMAP_3D = false;
  105529. defines.REFLECTIONMAP_SPHERICAL = false;
  105530. defines.REFLECTIONMAP_PLANAR = false;
  105531. defines.REFLECTIONMAP_CUBIC = false;
  105532. defines.REFLECTIONMAP_PROJECTION = false;
  105533. defines.REFLECTIONMAP_SKYBOX = false;
  105534. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  105535. defines.REFLECTIONMAP_EXPLICIT = false;
  105536. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  105537. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  105538. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  105539. defines.INVERTCUBICMAP = false;
  105540. defines.REFLECTIONMAP_OPPOSITEZ = false;
  105541. defines.LODINREFLECTIONALPHA = false;
  105542. defines.GAMMAREFLECTION = false;
  105543. defines.RGBDREFLECTION = false;
  105544. }
  105545. }
  105546. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  105547. defines.USERGBCOLOR = this._useRGBColor;
  105548. defines.NOISE = this._enableNoise;
  105549. }
  105550. if (defines._areLightsDirty) {
  105551. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  105552. }
  105553. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  105554. if (!this._imageProcessingConfiguration.isReady()) {
  105555. return false;
  105556. }
  105557. this._imageProcessingConfiguration.prepareDefines(defines);
  105558. }
  105559. // Misc.
  105560. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  105561. // Values that need to be evaluated on every frame
  105562. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  105563. // Attribs
  105564. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  105565. if (mesh) {
  105566. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  105567. mesh.createNormals(true);
  105568. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  105569. }
  105570. }
  105571. }
  105572. // Get correct effect
  105573. if (defines.isDirty) {
  105574. defines.markAsProcessed();
  105575. scene.resetCachedMaterial();
  105576. // Fallbacks
  105577. var fallbacks = new BABYLON.EffectFallbacks();
  105578. if (defines.FOG) {
  105579. fallbacks.addFallback(0, "FOG");
  105580. }
  105581. if (defines.POINTSIZE) {
  105582. fallbacks.addFallback(1, "POINTSIZE");
  105583. }
  105584. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  105585. if (defines.NUM_BONE_INFLUENCERS > 0) {
  105586. fallbacks.addCPUSkinningFallback(0, mesh);
  105587. }
  105588. //Attributes
  105589. var attribs = [BABYLON.VertexBuffer.PositionKind];
  105590. if (defines.NORMAL) {
  105591. attribs.push(BABYLON.VertexBuffer.NormalKind);
  105592. }
  105593. if (defines.UV1) {
  105594. attribs.push(BABYLON.VertexBuffer.UVKind);
  105595. }
  105596. if (defines.UV2) {
  105597. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  105598. }
  105599. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  105600. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  105601. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  105602. "vFogInfos", "vFogColor", "pointSize",
  105603. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  105604. "vPrimaryColor", "vPrimaryColorShadow",
  105605. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  105606. "shadowLevel", "alpha",
  105607. "vBackgroundCenter", "vReflectionControl",
  105608. "vDiffuseInfos", "diffuseMatrix",
  105609. ];
  105610. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  105611. var uniformBuffers = ["Material", "Scene"];
  105612. if (BABYLON.ImageProcessingConfiguration) {
  105613. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  105614. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  105615. }
  105616. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  105617. uniformsNames: uniforms,
  105618. uniformBuffersNames: uniformBuffers,
  105619. samplers: samplers,
  105620. defines: defines,
  105621. maxSimultaneousLights: this._maxSimultaneousLights
  105622. });
  105623. var onCompiled = function (effect) {
  105624. if (_this.onCompiled) {
  105625. _this.onCompiled(effect);
  105626. }
  105627. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  105628. };
  105629. var join = defines.toString();
  105630. subMesh.setEffect(scene.getEngine().createEffect("background", {
  105631. attributes: attribs,
  105632. uniformsNames: uniforms,
  105633. uniformBuffersNames: uniformBuffers,
  105634. samplers: samplers,
  105635. defines: join,
  105636. fallbacks: fallbacks,
  105637. onCompiled: onCompiled,
  105638. onError: this.onError,
  105639. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  105640. }, engine), defines);
  105641. this.buildUniformLayout();
  105642. }
  105643. if (!subMesh.effect || !subMesh.effect.isReady()) {
  105644. return false;
  105645. }
  105646. defines._renderId = scene.getRenderId();
  105647. this._wasPreviouslyReady = true;
  105648. return true;
  105649. };
  105650. /**
  105651. * Compute the primary color according to the chosen perceptual color.
  105652. */
  105653. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  105654. if (!this.__perceptualColor) {
  105655. return;
  105656. }
  105657. this._primaryColor.copyFrom(this.__perceptualColor);
  105658. // Revert gamma space.
  105659. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  105660. // Revert image processing configuration.
  105661. if (this._imageProcessingConfiguration) {
  105662. // Revert Exposure.
  105663. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  105664. }
  105665. this._computePrimaryColors();
  105666. };
  105667. /**
  105668. * Compute the highlights and shadow colors according to their chosen levels.
  105669. */
  105670. BackgroundMaterial.prototype._computePrimaryColors = function () {
  105671. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  105672. return;
  105673. }
  105674. // Find the highlight color based on the configuration.
  105675. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  105676. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  105677. // Find the shadow color based on the configuration.
  105678. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  105679. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  105680. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  105681. };
  105682. /**
  105683. * Build the uniform buffer used in the material.
  105684. */
  105685. BackgroundMaterial.prototype.buildUniformLayout = function () {
  105686. // Order is important !
  105687. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  105688. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  105689. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  105690. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  105691. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  105692. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  105693. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  105694. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  105695. this._uniformBuffer.addUniform("pointSize", 1);
  105696. this._uniformBuffer.addUniform("shadowLevel", 1);
  105697. this._uniformBuffer.addUniform("alpha", 1);
  105698. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  105699. this._uniformBuffer.addUniform("vReflectionControl", 4);
  105700. this._uniformBuffer.create();
  105701. };
  105702. /**
  105703. * Unbind the material.
  105704. */
  105705. BackgroundMaterial.prototype.unbind = function () {
  105706. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  105707. this._uniformBuffer.setTexture("diffuseSampler", null);
  105708. }
  105709. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  105710. this._uniformBuffer.setTexture("reflectionSampler", null);
  105711. }
  105712. _super.prototype.unbind.call(this);
  105713. };
  105714. /**
  105715. * Bind only the world matrix to the material.
  105716. * @param world The world matrix to bind.
  105717. */
  105718. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  105719. this._activeEffect.setMatrix("world", world);
  105720. };
  105721. /**
  105722. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  105723. * @param world The world matrix to bind.
  105724. * @param subMesh The submesh to bind for.
  105725. */
  105726. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  105727. var scene = this.getScene();
  105728. var defines = subMesh._materialDefines;
  105729. if (!defines) {
  105730. return;
  105731. }
  105732. var effect = subMesh.effect;
  105733. if (!effect) {
  105734. return;
  105735. }
  105736. this._activeEffect = effect;
  105737. // Matrices
  105738. this.bindOnlyWorldMatrix(world);
  105739. // Bones
  105740. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  105741. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  105742. if (mustRebind) {
  105743. this._uniformBuffer.bindToEffect(effect, "Material");
  105744. this.bindViewProjection(effect);
  105745. var reflectionTexture = this._reflectionTexture;
  105746. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  105747. // Texture uniforms
  105748. if (scene.texturesEnabled) {
  105749. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105750. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  105751. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  105752. }
  105753. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105754. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  105755. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  105756. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  105757. }
  105758. }
  105759. if (this.shadowLevel > 0) {
  105760. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  105761. }
  105762. this._uniformBuffer.updateFloat("alpha", this.alpha);
  105763. // Point size
  105764. if (this.pointsCloud) {
  105765. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  105766. }
  105767. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  105768. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  105769. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  105770. }
  105771. else {
  105772. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  105773. }
  105774. }
  105775. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  105776. // Textures
  105777. if (scene.texturesEnabled) {
  105778. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105779. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  105780. }
  105781. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105782. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  105783. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  105784. }
  105785. else if (!defines.REFLECTIONBLUR) {
  105786. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  105787. }
  105788. else {
  105789. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  105790. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  105791. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  105792. }
  105793. if (defines.REFLECTIONFRESNEL) {
  105794. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  105795. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  105796. }
  105797. }
  105798. }
  105799. // Clip plane
  105800. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  105801. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  105802. }
  105803. if (mustRebind || !this.isFrozen) {
  105804. if (scene.lightsEnabled) {
  105805. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  105806. }
  105807. // View
  105808. this.bindView(effect);
  105809. // Fog
  105810. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  105811. // image processing
  105812. if (this._imageProcessingConfiguration) {
  105813. this._imageProcessingConfiguration.bind(this._activeEffect);
  105814. }
  105815. }
  105816. this._uniformBuffer.update();
  105817. this._afterBind(mesh, this._activeEffect);
  105818. };
  105819. /**
  105820. * Dispose the material.
  105821. * @param forceDisposeEffect Force disposal of the associated effect.
  105822. * @param forceDisposeTextures Force disposal of the associated textures.
  105823. */
  105824. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  105825. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  105826. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  105827. if (forceDisposeTextures) {
  105828. if (this.diffuseTexture) {
  105829. this.diffuseTexture.dispose();
  105830. }
  105831. if (this.reflectionTexture) {
  105832. this.reflectionTexture.dispose();
  105833. }
  105834. }
  105835. this._renderTargets.dispose();
  105836. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  105837. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  105838. }
  105839. _super.prototype.dispose.call(this, forceDisposeEffect);
  105840. };
  105841. /**
  105842. * Clones the material.
  105843. * @param name The cloned name.
  105844. * @returns The cloned material.
  105845. */
  105846. BackgroundMaterial.prototype.clone = function (name) {
  105847. var _this = this;
  105848. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  105849. };
  105850. /**
  105851. * Serializes the current material to its JSON representation.
  105852. * @returns The JSON representation.
  105853. */
  105854. BackgroundMaterial.prototype.serialize = function () {
  105855. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  105856. serializationObject.customType = "BABYLON.BackgroundMaterial";
  105857. return serializationObject;
  105858. };
  105859. /**
  105860. * Gets the class name of the material
  105861. * @returns "BackgroundMaterial"
  105862. */
  105863. BackgroundMaterial.prototype.getClassName = function () {
  105864. return "BackgroundMaterial";
  105865. };
  105866. /**
  105867. * Parse a JSON input to create back a background material.
  105868. * @param source The JSON data to parse
  105869. * @param scene The scene to create the parsed material in
  105870. * @param rootUrl The root url of the assets the material depends upon
  105871. * @returns the instantiated BackgroundMaterial.
  105872. */
  105873. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  105874. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  105875. };
  105876. /**
  105877. * Standard reflectance value at parallel view angle.
  105878. */
  105879. BackgroundMaterial.StandardReflectance0 = 0.05;
  105880. /**
  105881. * Standard reflectance value at grazing angle.
  105882. */
  105883. BackgroundMaterial.StandardReflectance90 = 0.5;
  105884. __decorate([
  105885. BABYLON.serializeAsColor3()
  105886. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  105887. __decorate([
  105888. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  105889. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  105890. __decorate([
  105891. BABYLON.serializeAsColor3()
  105892. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  105893. __decorate([
  105894. BABYLON.serialize()
  105895. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  105896. __decorate([
  105897. BABYLON.serialize()
  105898. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  105899. __decorate([
  105900. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  105901. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  105902. __decorate([
  105903. BABYLON.serializeAsTexture()
  105904. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  105905. __decorate([
  105906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105907. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  105908. __decorate([
  105909. BABYLON.serialize()
  105910. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  105911. __decorate([
  105912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105913. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  105914. __decorate([
  105915. BABYLON.serializeAsTexture()
  105916. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  105917. __decorate([
  105918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105919. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  105920. __decorate([
  105921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105922. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  105923. __decorate([
  105924. BABYLON.serialize()
  105925. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  105926. __decorate([
  105927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105928. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  105929. __decorate([
  105930. BABYLON.serializeAsVector3()
  105931. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  105932. __decorate([
  105933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105934. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  105935. __decorate([
  105936. BABYLON.serialize()
  105937. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  105938. __decorate([
  105939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105940. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  105941. __decorate([
  105942. BABYLON.serialize()
  105943. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  105944. __decorate([
  105945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105946. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  105947. __decorate([
  105948. BABYLON.serialize()
  105949. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  105950. __decorate([
  105951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105952. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  105953. __decorate([
  105954. BABYLON.serialize()
  105955. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  105956. __decorate([
  105957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105958. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  105959. __decorate([
  105960. BABYLON.serialize()
  105961. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  105962. __decorate([
  105963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105964. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  105965. __decorate([
  105966. BABYLON.serialize()
  105967. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  105968. __decorate([
  105969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105970. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  105971. __decorate([
  105972. BABYLON.serialize()
  105973. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  105974. __decorate([
  105975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105976. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  105977. __decorate([
  105978. BABYLON.serialize()
  105979. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  105980. __decorate([
  105981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105982. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  105983. __decorate([
  105984. BABYLON.serialize()
  105985. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  105986. __decorate([
  105987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105988. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  105989. __decorate([
  105990. BABYLON.serializeAsImageProcessingConfiguration()
  105991. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  105992. return BackgroundMaterial;
  105993. }(BABYLON.PushMaterial));
  105994. BABYLON.BackgroundMaterial = BackgroundMaterial;
  105995. })(BABYLON || (BABYLON = {}));
  105996. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  105997. var __assign = (this && this.__assign) || function () {
  105998. __assign = Object.assign || function(t) {
  105999. for (var s, i = 1, n = arguments.length; i < n; i++) {
  106000. s = arguments[i];
  106001. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  106002. t[p] = s[p];
  106003. }
  106004. return t;
  106005. };
  106006. return __assign.apply(this, arguments);
  106007. };
  106008. var BABYLON;
  106009. (function (BABYLON) {
  106010. /**
  106011. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  106012. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  106013. * It also helps with the default setup of your imageProcessing configuration.
  106014. */
  106015. var EnvironmentHelper = /** @class */ (function () {
  106016. /**
  106017. * constructor
  106018. * @param options
  106019. * @param scene The scene to add the material to
  106020. */
  106021. function EnvironmentHelper(options, scene) {
  106022. var _this = this;
  106023. this._errorHandler = function (message, exception) {
  106024. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  106025. };
  106026. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  106027. this._scene = scene;
  106028. this.onErrorObservable = new BABYLON.Observable();
  106029. this._setupBackground();
  106030. this._setupImageProcessing();
  106031. }
  106032. /**
  106033. * Creates the default options for the helper.
  106034. */
  106035. EnvironmentHelper._getDefaultOptions = function () {
  106036. return {
  106037. createGround: true,
  106038. groundSize: 15,
  106039. groundTexture: this._groundTextureCDNUrl,
  106040. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  106041. groundOpacity: 0.9,
  106042. enableGroundShadow: true,
  106043. groundShadowLevel: 0.5,
  106044. enableGroundMirror: false,
  106045. groundMirrorSizeRatio: 0.3,
  106046. groundMirrorBlurKernel: 64,
  106047. groundMirrorAmount: 1,
  106048. groundMirrorFresnelWeight: 1,
  106049. groundMirrorFallOffDistance: 0,
  106050. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  106051. groundYBias: 0.00001,
  106052. createSkybox: true,
  106053. skyboxSize: 20,
  106054. skyboxTexture: this._skyboxTextureCDNUrl,
  106055. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  106056. backgroundYRotation: 0,
  106057. sizeAuto: true,
  106058. rootPosition: BABYLON.Vector3.Zero(),
  106059. setupImageProcessing: true,
  106060. environmentTexture: this._environmentTextureCDNUrl,
  106061. cameraExposure: 0.8,
  106062. cameraContrast: 1.2,
  106063. toneMappingEnabled: true,
  106064. };
  106065. };
  106066. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  106067. /**
  106068. * Gets the root mesh created by the helper.
  106069. */
  106070. get: function () {
  106071. return this._rootMesh;
  106072. },
  106073. enumerable: true,
  106074. configurable: true
  106075. });
  106076. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  106077. /**
  106078. * Gets the skybox created by the helper.
  106079. */
  106080. get: function () {
  106081. return this._skybox;
  106082. },
  106083. enumerable: true,
  106084. configurable: true
  106085. });
  106086. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  106087. /**
  106088. * Gets the skybox texture created by the helper.
  106089. */
  106090. get: function () {
  106091. return this._skyboxTexture;
  106092. },
  106093. enumerable: true,
  106094. configurable: true
  106095. });
  106096. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  106097. /**
  106098. * Gets the skybox material created by the helper.
  106099. */
  106100. get: function () {
  106101. return this._skyboxMaterial;
  106102. },
  106103. enumerable: true,
  106104. configurable: true
  106105. });
  106106. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  106107. /**
  106108. * Gets the ground mesh created by the helper.
  106109. */
  106110. get: function () {
  106111. return this._ground;
  106112. },
  106113. enumerable: true,
  106114. configurable: true
  106115. });
  106116. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  106117. /**
  106118. * Gets the ground texture created by the helper.
  106119. */
  106120. get: function () {
  106121. return this._groundTexture;
  106122. },
  106123. enumerable: true,
  106124. configurable: true
  106125. });
  106126. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  106127. /**
  106128. * Gets the ground mirror created by the helper.
  106129. */
  106130. get: function () {
  106131. return this._groundMirror;
  106132. },
  106133. enumerable: true,
  106134. configurable: true
  106135. });
  106136. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  106137. /**
  106138. * Gets the ground mirror render list to helps pushing the meshes
  106139. * you wish in the ground reflection.
  106140. */
  106141. get: function () {
  106142. if (this._groundMirror) {
  106143. return this._groundMirror.renderList;
  106144. }
  106145. return null;
  106146. },
  106147. enumerable: true,
  106148. configurable: true
  106149. });
  106150. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  106151. /**
  106152. * Gets the ground material created by the helper.
  106153. */
  106154. get: function () {
  106155. return this._groundMaterial;
  106156. },
  106157. enumerable: true,
  106158. configurable: true
  106159. });
  106160. /**
  106161. * Updates the background according to the new options
  106162. * @param options
  106163. */
  106164. EnvironmentHelper.prototype.updateOptions = function (options) {
  106165. var newOptions = __assign({}, this._options, options);
  106166. if (this._ground && !newOptions.createGround) {
  106167. this._ground.dispose();
  106168. this._ground = null;
  106169. }
  106170. if (this._groundMaterial && !newOptions.createGround) {
  106171. this._groundMaterial.dispose();
  106172. this._groundMaterial = null;
  106173. }
  106174. if (this._groundTexture) {
  106175. if (this._options.groundTexture != newOptions.groundTexture) {
  106176. this._groundTexture.dispose();
  106177. this._groundTexture = null;
  106178. }
  106179. }
  106180. if (this._skybox && !newOptions.createSkybox) {
  106181. this._skybox.dispose();
  106182. this._skybox = null;
  106183. }
  106184. if (this._skyboxMaterial && !newOptions.createSkybox) {
  106185. this._skyboxMaterial.dispose();
  106186. this._skyboxMaterial = null;
  106187. }
  106188. if (this._skyboxTexture) {
  106189. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  106190. this._skyboxTexture.dispose();
  106191. this._skyboxTexture = null;
  106192. }
  106193. }
  106194. if (this._groundMirror && !newOptions.enableGroundMirror) {
  106195. this._groundMirror.dispose();
  106196. this._groundMirror = null;
  106197. }
  106198. if (this._scene.environmentTexture) {
  106199. if (this._options.environmentTexture != newOptions.environmentTexture) {
  106200. this._scene.environmentTexture.dispose();
  106201. }
  106202. }
  106203. this._options = newOptions;
  106204. this._setupBackground();
  106205. this._setupImageProcessing();
  106206. };
  106207. /**
  106208. * Sets the primary color of all the available elements.
  106209. * @param color the main color to affect to the ground and the background
  106210. */
  106211. EnvironmentHelper.prototype.setMainColor = function (color) {
  106212. if (this.groundMaterial) {
  106213. this.groundMaterial.primaryColor = color;
  106214. }
  106215. if (this.skyboxMaterial) {
  106216. this.skyboxMaterial.primaryColor = color;
  106217. }
  106218. if (this.groundMirror) {
  106219. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  106220. }
  106221. };
  106222. /**
  106223. * Setup the image processing according to the specified options.
  106224. */
  106225. EnvironmentHelper.prototype._setupImageProcessing = function () {
  106226. if (this._options.setupImageProcessing) {
  106227. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  106228. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  106229. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  106230. this._setupEnvironmentTexture();
  106231. }
  106232. };
  106233. /**
  106234. * Setup the environment texture according to the specified options.
  106235. */
  106236. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  106237. if (this._scene.environmentTexture) {
  106238. return;
  106239. }
  106240. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  106241. this._scene.environmentTexture = this._options.environmentTexture;
  106242. return;
  106243. }
  106244. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  106245. this._scene.environmentTexture = environmentTexture;
  106246. };
  106247. /**
  106248. * Setup the background according to the specified options.
  106249. */
  106250. EnvironmentHelper.prototype._setupBackground = function () {
  106251. if (!this._rootMesh) {
  106252. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  106253. }
  106254. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  106255. var sceneSize = this._getSceneSize();
  106256. if (this._options.createGround) {
  106257. this._setupGround(sceneSize);
  106258. this._setupGroundMaterial();
  106259. this._setupGroundDiffuseTexture();
  106260. if (this._options.enableGroundMirror) {
  106261. this._setupGroundMirrorTexture(sceneSize);
  106262. }
  106263. this._setupMirrorInGroundMaterial();
  106264. }
  106265. if (this._options.createSkybox) {
  106266. this._setupSkybox(sceneSize);
  106267. this._setupSkyboxMaterial();
  106268. this._setupSkyboxReflectionTexture();
  106269. }
  106270. this._rootMesh.position.x = sceneSize.rootPosition.x;
  106271. this._rootMesh.position.z = sceneSize.rootPosition.z;
  106272. this._rootMesh.position.y = sceneSize.rootPosition.y;
  106273. };
  106274. /**
  106275. * Get the scene sizes according to the setup.
  106276. */
  106277. EnvironmentHelper.prototype._getSceneSize = function () {
  106278. var _this = this;
  106279. var groundSize = this._options.groundSize;
  106280. var skyboxSize = this._options.skyboxSize;
  106281. var rootPosition = this._options.rootPosition;
  106282. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  106283. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  106284. }
  106285. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  106286. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  106287. });
  106288. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  106289. if (this._options.sizeAuto) {
  106290. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  106291. this._scene.activeCamera.upperRadiusLimit) {
  106292. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  106293. skyboxSize = groundSize;
  106294. }
  106295. var sceneDiagonalLenght = sceneDiagonal.length();
  106296. if (sceneDiagonalLenght > groundSize) {
  106297. groundSize = sceneDiagonalLenght * 2;
  106298. skyboxSize = groundSize;
  106299. }
  106300. // 10 % bigger.
  106301. groundSize *= 1.1;
  106302. skyboxSize *= 1.5;
  106303. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  106304. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  106305. }
  106306. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  106307. };
  106308. /**
  106309. * Setup the ground according to the specified options.
  106310. */
  106311. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  106312. var _this = this;
  106313. if (!this._ground || this._ground.isDisposed()) {
  106314. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  106315. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  106316. this._ground.parent = this._rootMesh;
  106317. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  106318. }
  106319. this._ground.receiveShadows = this._options.enableGroundShadow;
  106320. };
  106321. /**
  106322. * Setup the ground material according to the specified options.
  106323. */
  106324. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  106325. if (!this._groundMaterial) {
  106326. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  106327. }
  106328. this._groundMaterial.alpha = this._options.groundOpacity;
  106329. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  106330. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  106331. this._groundMaterial.primaryColor = this._options.groundColor;
  106332. this._groundMaterial.useRGBColor = false;
  106333. this._groundMaterial.enableNoise = true;
  106334. if (this._ground) {
  106335. this._ground.material = this._groundMaterial;
  106336. }
  106337. };
  106338. /**
  106339. * Setup the ground diffuse texture according to the specified options.
  106340. */
  106341. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  106342. if (!this._groundMaterial) {
  106343. return;
  106344. }
  106345. if (this._groundTexture) {
  106346. return;
  106347. }
  106348. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  106349. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  106350. return;
  106351. }
  106352. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  106353. diffuseTexture.gammaSpace = false;
  106354. diffuseTexture.hasAlpha = true;
  106355. this._groundMaterial.diffuseTexture = diffuseTexture;
  106356. };
  106357. /**
  106358. * Setup the ground mirror texture according to the specified options.
  106359. */
  106360. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  106361. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106362. if (!this._groundMirror) {
  106363. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  106364. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  106365. this._groundMirror.anisotropicFilteringLevel = 1;
  106366. this._groundMirror.wrapU = wrapping;
  106367. this._groundMirror.wrapV = wrapping;
  106368. this._groundMirror.gammaSpace = false;
  106369. if (this._groundMirror.renderList) {
  106370. for (var i = 0; i < this._scene.meshes.length; i++) {
  106371. var mesh = this._scene.meshes[i];
  106372. if (mesh !== this._ground &&
  106373. mesh !== this._skybox &&
  106374. mesh !== this._rootMesh) {
  106375. this._groundMirror.renderList.push(mesh);
  106376. }
  106377. }
  106378. }
  106379. }
  106380. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  106381. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  106382. };
  106383. /**
  106384. * Setup the ground to receive the mirror texture.
  106385. */
  106386. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  106387. if (this._groundMaterial) {
  106388. this._groundMaterial.reflectionTexture = this._groundMirror;
  106389. this._groundMaterial.reflectionFresnel = true;
  106390. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  106391. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  106392. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  106393. }
  106394. };
  106395. /**
  106396. * Setup the skybox according to the specified options.
  106397. */
  106398. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  106399. var _this = this;
  106400. if (!this._skybox || this._skybox.isDisposed()) {
  106401. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  106402. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  106403. }
  106404. this._skybox.parent = this._rootMesh;
  106405. };
  106406. /**
  106407. * Setup the skybox material according to the specified options.
  106408. */
  106409. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  106410. if (!this._skybox) {
  106411. return;
  106412. }
  106413. if (!this._skyboxMaterial) {
  106414. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  106415. }
  106416. this._skyboxMaterial.useRGBColor = false;
  106417. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  106418. this._skyboxMaterial.enableNoise = true;
  106419. this._skybox.material = this._skyboxMaterial;
  106420. };
  106421. /**
  106422. * Setup the skybox reflection texture according to the specified options.
  106423. */
  106424. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  106425. if (!this._skyboxMaterial) {
  106426. return;
  106427. }
  106428. if (this._skyboxTexture) {
  106429. return;
  106430. }
  106431. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  106432. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  106433. return;
  106434. }
  106435. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  106436. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  106437. this._skyboxTexture.gammaSpace = false;
  106438. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  106439. };
  106440. /**
  106441. * Dispose all the elements created by the Helper.
  106442. */
  106443. EnvironmentHelper.prototype.dispose = function () {
  106444. if (this._groundMaterial) {
  106445. this._groundMaterial.dispose(true, true);
  106446. }
  106447. if (this._skyboxMaterial) {
  106448. this._skyboxMaterial.dispose(true, true);
  106449. }
  106450. this._rootMesh.dispose(false);
  106451. };
  106452. /**
  106453. * Default ground texture URL.
  106454. */
  106455. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  106456. /**
  106457. * Default skybox texture URL.
  106458. */
  106459. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  106460. /**
  106461. * Default environment texture URL.
  106462. */
  106463. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  106464. return EnvironmentHelper;
  106465. }());
  106466. BABYLON.EnvironmentHelper = EnvironmentHelper;
  106467. })(BABYLON || (BABYLON = {}));
  106468. //# sourceMappingURL=babylon.environmentHelper.js.map
  106469. var BABYLON;
  106470. (function (BABYLON) {
  106471. /** Internal class used to store shapes for emitters */
  106472. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  106473. function ParticleSystemSetEmitterCreationOptions() {
  106474. }
  106475. return ParticleSystemSetEmitterCreationOptions;
  106476. }());
  106477. /**
  106478. * Represents a set of particle systems working together to create a specific effect
  106479. */
  106480. var ParticleSystemSet = /** @class */ (function () {
  106481. function ParticleSystemSet() {
  106482. /**
  106483. * Gets the particle system list
  106484. */
  106485. this.systems = new Array();
  106486. }
  106487. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  106488. /**
  106489. * Gets the emitter node used with this set
  106490. */
  106491. get: function () {
  106492. return this._emitterNode;
  106493. },
  106494. enumerable: true,
  106495. configurable: true
  106496. });
  106497. /**
  106498. * Creates a new emitter mesh as a sphere
  106499. * @param options defines the options used to create the sphere
  106500. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  106501. * @param scene defines the hosting scene
  106502. */
  106503. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  106504. if (this._emitterNode) {
  106505. this._emitterNode.dispose();
  106506. }
  106507. this._emitterCreationOptions = {
  106508. kind: "Sphere",
  106509. options: options,
  106510. renderingGroupId: renderingGroupId
  106511. };
  106512. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  106513. emitterMesh.renderingGroupId = renderingGroupId;
  106514. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  106515. material.emissiveColor = options.color;
  106516. emitterMesh.material = material;
  106517. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106518. var system = _a[_i];
  106519. system.emitter = emitterMesh;
  106520. }
  106521. this._emitterNode = emitterMesh;
  106522. };
  106523. /**
  106524. * Starts all particle systems of the set
  106525. * @param emitter defines an optional mesh to use as emitter for the particle systems
  106526. */
  106527. ParticleSystemSet.prototype.start = function (emitter) {
  106528. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106529. var system = _a[_i];
  106530. if (emitter) {
  106531. system.emitter = emitter;
  106532. }
  106533. system.start();
  106534. }
  106535. };
  106536. /**
  106537. * Release all associated resources
  106538. */
  106539. ParticleSystemSet.prototype.dispose = function () {
  106540. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106541. var system = _a[_i];
  106542. system.dispose();
  106543. }
  106544. this.systems = [];
  106545. if (this._emitterNode) {
  106546. this._emitterNode.dispose();
  106547. this._emitterNode = null;
  106548. }
  106549. };
  106550. /**
  106551. * Serialize the set into a JSON compatible object
  106552. * @returns a JSON compatible representation of the set
  106553. */
  106554. ParticleSystemSet.prototype.serialize = function () {
  106555. var result = {};
  106556. result.systems = [];
  106557. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106558. var system = _a[_i];
  106559. result.systems.push(system.serialize());
  106560. }
  106561. if (this._emitterNode) {
  106562. result.emitter = this._emitterCreationOptions;
  106563. }
  106564. return result;
  106565. };
  106566. /**
  106567. * Parse a new ParticleSystemSet from a serialized source
  106568. * @param data defines a JSON compatible representation of the set
  106569. * @param scene defines the hosting scene
  106570. * @param gpu defines if we want GPU particles or CPU particles
  106571. * @returns a new ParticleSystemSet
  106572. */
  106573. ParticleSystemSet.Parse = function (data, scene, gpu) {
  106574. if (gpu === void 0) { gpu = false; }
  106575. var result = new ParticleSystemSet();
  106576. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  106577. scene = scene || BABYLON.Engine.LastCreatedScene;
  106578. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  106579. var system = _a[_i];
  106580. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  106581. }
  106582. if (data.emitter) {
  106583. var options = data.emitter.options;
  106584. switch (data.emitter.kind) {
  106585. case "Sphere":
  106586. result.setEmitterAsSphere({
  106587. diameter: options.diameter,
  106588. segments: options.segments,
  106589. color: BABYLON.Color3.FromArray(options.color)
  106590. }, data.emitter.renderingGroupId, scene);
  106591. break;
  106592. }
  106593. }
  106594. return result;
  106595. };
  106596. return ParticleSystemSet;
  106597. }());
  106598. BABYLON.ParticleSystemSet = ParticleSystemSet;
  106599. })(BABYLON || (BABYLON = {}));
  106600. //# sourceMappingURL=babylon.particleSystemSet.js.map
  106601. var BABYLON;
  106602. (function (BABYLON) {
  106603. /**
  106604. * This class is made for on one-liner static method to help creating particle system set.
  106605. */
  106606. var ParticleHelper = /** @class */ (function () {
  106607. function ParticleHelper() {
  106608. }
  106609. /**
  106610. * Create a default particle system that you can tweak
  106611. * @param emitter defines the emitter to use
  106612. * @param capacity defines the system capacity (default is 500 particles)
  106613. * @param scene defines the hosting scene
  106614. * @returns the new Particle system
  106615. */
  106616. ParticleHelper.CreateDefault = function (emitter, capacity, scene) {
  106617. if (capacity === void 0) { capacity = 500; }
  106618. var system = new BABYLON.ParticleSystem("default system", capacity, scene);
  106619. system.emitter = emitter;
  106620. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  106621. system.createConeEmitter(0.1, Math.PI / 4);
  106622. // Particle color
  106623. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  106624. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  106625. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  106626. // Particle Size
  106627. system.minSize = 0.1;
  106628. system.maxSize = 0.1;
  106629. // Emission speed
  106630. system.minEmitPower = 2;
  106631. system.maxEmitPower = 2;
  106632. // Update speed
  106633. system.updateSpeed = 1 / 60;
  106634. system.emitRate = 30;
  106635. return system;
  106636. };
  106637. /**
  106638. * This is the main static method (one-liner) of this helper to create different particle systems
  106639. * @param type This string represents the type to the particle system to create
  106640. * @param scene The scene where the particle system should live
  106641. * @param gpu If the system will use gpu
  106642. * @returns the ParticleSystemSet created
  106643. */
  106644. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  106645. if (gpu === void 0) { gpu = false; }
  106646. if (!scene) {
  106647. scene = BABYLON.Engine.LastCreatedScene;
  106648. ;
  106649. }
  106650. var token = {};
  106651. scene._addPendingData(token);
  106652. return new Promise(function (resolve, reject) {
  106653. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  106654. scene._removePendingData(token);
  106655. return reject("Particle system with GPU is not supported.");
  106656. }
  106657. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  106658. scene._removePendingData(token);
  106659. var newData = JSON.parse(data.toString());
  106660. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  106661. }, undefined, undefined, undefined, function (req, exception) {
  106662. scene._removePendingData(token);
  106663. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  106664. });
  106665. });
  106666. };
  106667. /**
  106668. * Static function used to export a particle system to a ParticleSystemSet variable.
  106669. * Please note that the emitter shape is not exported
  106670. * @param system defines the particle systems to export
  106671. */
  106672. ParticleHelper.ExportSet = function (systems) {
  106673. var set = new BABYLON.ParticleSystemSet();
  106674. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  106675. var system = systems_1[_i];
  106676. set.systems.push(system);
  106677. }
  106678. return set;
  106679. };
  106680. /**
  106681. * Gets or sets base Assets URL
  106682. */
  106683. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  106684. return ParticleHelper;
  106685. }());
  106686. BABYLON.ParticleHelper = ParticleHelper;
  106687. })(BABYLON || (BABYLON = {}));
  106688. //# sourceMappingURL=babylon.particleHelper.js.map
  106689. var BABYLON;
  106690. (function (BABYLON) {
  106691. /**
  106692. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  106693. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  106694. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  106695. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  106696. */
  106697. var VideoDome = /** @class */ (function (_super) {
  106698. __extends(VideoDome, _super);
  106699. /**
  106700. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  106701. * @param name Element's name, child elements will append suffixes for their own names.
  106702. * @param urlsOrVideo defines the url(s) or the video element to use
  106703. * @param options An object containing optional or exposed sub element properties
  106704. */
  106705. function VideoDome(name, urlsOrVideo, options, scene) {
  106706. var _this = _super.call(this, name, scene) || this;
  106707. _this._useDirectMapping = false;
  106708. // set defaults and manage values
  106709. name = name || "videoDome";
  106710. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  106711. options.clickToPlay = Boolean(options.clickToPlay);
  106712. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  106713. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  106714. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  106715. if (options.useDirectMapping === undefined) {
  106716. _this._useDirectMapping = true;
  106717. }
  106718. else {
  106719. _this._useDirectMapping = options.useDirectMapping;
  106720. }
  106721. _this._setReady(false);
  106722. // create
  106723. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  106724. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  106725. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  106726. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  106727. texture.onLoadObservable.addOnce(function () {
  106728. _this._setReady(true);
  106729. });
  106730. // configure material
  106731. material.useEquirectangularFOV = true;
  106732. material.fovMultiplier = 1.0;
  106733. material.opacityFresnel = false;
  106734. if (_this._useDirectMapping) {
  106735. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106736. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106737. material.diffuseTexture = texture;
  106738. }
  106739. else {
  106740. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  106741. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106742. material.reflectionTexture = texture;
  106743. }
  106744. // configure mesh
  106745. _this._mesh.material = material;
  106746. _this._mesh.parent = _this;
  106747. // optional configuration
  106748. if (options.clickToPlay) {
  106749. scene.onPointerUp = function () {
  106750. _this._videoTexture.video.play();
  106751. };
  106752. }
  106753. return _this;
  106754. }
  106755. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  106756. /**
  106757. * Gets the video texture being displayed on the sphere
  106758. */
  106759. get: function () {
  106760. return this._videoTexture;
  106761. },
  106762. enumerable: true,
  106763. configurable: true
  106764. });
  106765. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  106766. /**
  106767. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  106768. * Also see the options.resolution property.
  106769. */
  106770. get: function () {
  106771. return this._material.fovMultiplier;
  106772. },
  106773. set: function (value) {
  106774. this._material.fovMultiplier = value;
  106775. },
  106776. enumerable: true,
  106777. configurable: true
  106778. });
  106779. /**
  106780. * Releases resources associated with this node.
  106781. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  106782. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  106783. */
  106784. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  106785. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  106786. this._videoTexture.dispose();
  106787. this._mesh.dispose();
  106788. this._material.dispose();
  106789. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  106790. };
  106791. return VideoDome;
  106792. }(BABYLON.TransformNode));
  106793. BABYLON.VideoDome = VideoDome;
  106794. })(BABYLON || (BABYLON = {}));
  106795. //# sourceMappingURL=babylon.videoDome.js.map
  106796. var BABYLON;
  106797. (function (BABYLON) {
  106798. /**
  106799. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  106800. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  106801. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  106802. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  106803. */
  106804. var PhotoDome = /** @class */ (function (_super) {
  106805. __extends(PhotoDome, _super);
  106806. /**
  106807. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  106808. * @param name Element's name, child elements will append suffixes for their own names.
  106809. * @param urlsOfPhoto defines the url of the photo to display
  106810. * @param options defines an object containing optional or exposed sub element properties
  106811. * @param onError defines a callback called when an error occured while loading the texture
  106812. */
  106813. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  106814. if (onError === void 0) { onError = null; }
  106815. var _this = _super.call(this, name, scene) || this;
  106816. _this._useDirectMapping = false;
  106817. /**
  106818. * Observable raised when an error occured while loading the 360 image
  106819. */
  106820. _this.onLoadErrorObservable = new BABYLON.Observable();
  106821. // set defaults and manage values
  106822. name = name || "photoDome";
  106823. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  106824. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  106825. if (options.useDirectMapping === undefined) {
  106826. _this._useDirectMapping = true;
  106827. }
  106828. else {
  106829. _this._useDirectMapping = options.useDirectMapping;
  106830. }
  106831. _this._setReady(false);
  106832. // create
  106833. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  106834. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  106835. // configure material
  106836. material.opacityFresnel = false;
  106837. material.useEquirectangularFOV = true;
  106838. material.fovMultiplier = 1.0;
  106839. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  106840. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  106841. if (onError) {
  106842. onError(message, exception);
  106843. }
  106844. });
  106845. _this.photoTexture.onLoadObservable.addOnce(function () {
  106846. _this._setReady(true);
  106847. });
  106848. // configure mesh
  106849. _this._mesh.material = material;
  106850. _this._mesh.parent = _this;
  106851. return _this;
  106852. }
  106853. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  106854. /**
  106855. * Gets or sets the texture being displayed on the sphere
  106856. */
  106857. get: function () {
  106858. return this._photoTexture;
  106859. },
  106860. set: function (value) {
  106861. if (this._photoTexture === value) {
  106862. return;
  106863. }
  106864. this._photoTexture = value;
  106865. if (this._useDirectMapping) {
  106866. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106867. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106868. this._material.diffuseTexture = this._photoTexture;
  106869. }
  106870. else {
  106871. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  106872. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106873. this._material.reflectionTexture = this._photoTexture;
  106874. }
  106875. },
  106876. enumerable: true,
  106877. configurable: true
  106878. });
  106879. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  106880. /**
  106881. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  106882. * Also see the options.resolution property.
  106883. */
  106884. get: function () {
  106885. return this._material.fovMultiplier;
  106886. },
  106887. set: function (value) {
  106888. this._material.fovMultiplier = value;
  106889. },
  106890. enumerable: true,
  106891. configurable: true
  106892. });
  106893. /**
  106894. * Releases resources associated with this node.
  106895. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  106896. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  106897. */
  106898. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  106899. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  106900. this._photoTexture.dispose();
  106901. this._mesh.dispose();
  106902. this._material.dispose();
  106903. this.onLoadErrorObservable.clear();
  106904. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  106905. };
  106906. return PhotoDome;
  106907. }(BABYLON.TransformNode));
  106908. BABYLON.PhotoDome = PhotoDome;
  106909. })(BABYLON || (BABYLON = {}));
  106910. //# sourceMappingURL=babylon.photoDome.js.map
  106911. var BABYLON;
  106912. (function (BABYLON) {
  106913. BABYLON.Engine.prototype.createQuery = function () {
  106914. return this._gl.createQuery();
  106915. };
  106916. BABYLON.Engine.prototype.deleteQuery = function (query) {
  106917. this._gl.deleteQuery(query);
  106918. return this;
  106919. };
  106920. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  106921. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  106922. };
  106923. BABYLON.Engine.prototype.getQueryResult = function (query) {
  106924. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  106925. };
  106926. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  106927. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  106928. this._gl.beginQuery(glAlgorithm, query);
  106929. return this;
  106930. };
  106931. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  106932. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  106933. this._gl.endQuery(glAlgorithm);
  106934. return this;
  106935. };
  106936. BABYLON.Engine.prototype._createTimeQuery = function () {
  106937. var timerQuery = this.getCaps().timerQuery;
  106938. if (timerQuery.createQueryEXT) {
  106939. return timerQuery.createQueryEXT();
  106940. }
  106941. return this.createQuery();
  106942. };
  106943. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  106944. var timerQuery = this.getCaps().timerQuery;
  106945. if (timerQuery.deleteQueryEXT) {
  106946. timerQuery.deleteQueryEXT(query);
  106947. return;
  106948. }
  106949. this.deleteQuery(query);
  106950. };
  106951. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  106952. var timerQuery = this.getCaps().timerQuery;
  106953. if (timerQuery.getQueryObjectEXT) {
  106954. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  106955. }
  106956. return this.getQueryResult(query);
  106957. };
  106958. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  106959. var timerQuery = this.getCaps().timerQuery;
  106960. if (timerQuery.getQueryObjectEXT) {
  106961. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  106962. }
  106963. return this.isQueryResultAvailable(query);
  106964. };
  106965. BABYLON.Engine.prototype.startTimeQuery = function () {
  106966. var caps = this.getCaps();
  106967. var timerQuery = caps.timerQuery;
  106968. if (!timerQuery) {
  106969. return null;
  106970. }
  106971. var token = new BABYLON._TimeToken();
  106972. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  106973. if (caps.canUseTimestampForTimerQuery) {
  106974. token._startTimeQuery = this._createTimeQuery();
  106975. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  106976. }
  106977. else {
  106978. if (this._currentNonTimestampToken) {
  106979. return this._currentNonTimestampToken;
  106980. }
  106981. token._timeElapsedQuery = this._createTimeQuery();
  106982. if (timerQuery.beginQueryEXT) {
  106983. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  106984. }
  106985. else {
  106986. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  106987. }
  106988. this._currentNonTimestampToken = token;
  106989. }
  106990. return token;
  106991. };
  106992. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  106993. var caps = this.getCaps();
  106994. var timerQuery = caps.timerQuery;
  106995. if (!timerQuery || !token) {
  106996. return -1;
  106997. }
  106998. if (caps.canUseTimestampForTimerQuery) {
  106999. if (!token._startTimeQuery) {
  107000. return -1;
  107001. }
  107002. if (!token._endTimeQuery) {
  107003. token._endTimeQuery = this._createTimeQuery();
  107004. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  107005. }
  107006. }
  107007. else if (!token._timeElapsedQueryEnded) {
  107008. if (!token._timeElapsedQuery) {
  107009. return -1;
  107010. }
  107011. if (timerQuery.endQueryEXT) {
  107012. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  107013. }
  107014. else {
  107015. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  107016. }
  107017. token._timeElapsedQueryEnded = true;
  107018. }
  107019. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  107020. var available = false;
  107021. if (token._endTimeQuery) {
  107022. available = this._getTimeQueryAvailability(token._endTimeQuery);
  107023. }
  107024. else if (token._timeElapsedQuery) {
  107025. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  107026. }
  107027. if (available && !disjoint) {
  107028. var result = 0;
  107029. if (caps.canUseTimestampForTimerQuery) {
  107030. if (!token._startTimeQuery || !token._endTimeQuery) {
  107031. return -1;
  107032. }
  107033. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  107034. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  107035. result = timeEnd - timeStart;
  107036. this._deleteTimeQuery(token._startTimeQuery);
  107037. this._deleteTimeQuery(token._endTimeQuery);
  107038. token._startTimeQuery = null;
  107039. token._endTimeQuery = null;
  107040. }
  107041. else {
  107042. if (!token._timeElapsedQuery) {
  107043. return -1;
  107044. }
  107045. result = this._getTimeQueryResult(token._timeElapsedQuery);
  107046. this._deleteTimeQuery(token._timeElapsedQuery);
  107047. token._timeElapsedQuery = null;
  107048. token._timeElapsedQueryEnded = false;
  107049. this._currentNonTimestampToken = null;
  107050. }
  107051. return result;
  107052. }
  107053. return -1;
  107054. };
  107055. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  107056. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  107057. };
  107058. // We also need to update AbstractMesh as there is a portion of the code there
  107059. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  107060. var engine = this.getEngine();
  107061. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  107062. this._isOccluded = false;
  107063. return;
  107064. }
  107065. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  107066. this._isOccluded = false;
  107067. return;
  107068. }
  107069. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  107070. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  107071. if (isOcclusionQueryAvailable) {
  107072. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  107073. this._isOcclusionQueryInProgress = false;
  107074. this._occlusionInternalRetryCounter = 0;
  107075. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  107076. }
  107077. else {
  107078. this._occlusionInternalRetryCounter++;
  107079. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  107080. this._isOcclusionQueryInProgress = false;
  107081. this._occlusionInternalRetryCounter = 0;
  107082. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  107083. // if strict continue the last state of the object.
  107084. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  107085. }
  107086. else {
  107087. return;
  107088. }
  107089. }
  107090. }
  107091. var scene = this.getScene();
  107092. if (scene.getBoundingBoxRenderer) {
  107093. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  107094. if (!this._occlusionQuery) {
  107095. this._occlusionQuery = engine.createQuery();
  107096. }
  107097. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  107098. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  107099. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  107100. this._isOcclusionQueryInProgress = true;
  107101. }
  107102. };
  107103. })(BABYLON || (BABYLON = {}));
  107104. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  107105. var BABYLON;
  107106. (function (BABYLON) {
  107107. /**
  107108. * Class used to generate noise procedural textures
  107109. */
  107110. var NoiseProceduralTexture = /** @class */ (function (_super) {
  107111. __extends(NoiseProceduralTexture, _super);
  107112. /**
  107113. * Creates a new NoiseProceduralTexture
  107114. * @param name defines the name fo the texture
  107115. * @param size defines the size of the texture (default is 256)
  107116. * @param scene defines the hosting scene
  107117. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  107118. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  107119. */
  107120. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  107121. if (size === void 0) { size = 256; }
  107122. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  107123. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  107124. _this._time = 0;
  107125. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  107126. _this.brightness = 0.2;
  107127. /** Defines the number of octaves to process */
  107128. _this.octaves = 3;
  107129. /** Defines the level of persistence (0.8 by default) */
  107130. _this.persistence = 0.8;
  107131. /** Gets or sets animation speed factor (default is 1) */
  107132. _this.animationSpeedFactor = 1;
  107133. _this._updateShaderUniforms();
  107134. return _this;
  107135. }
  107136. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  107137. var scene = this.getScene();
  107138. if (!scene) {
  107139. return;
  107140. }
  107141. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  107142. this.setFloat("brightness", this.brightness);
  107143. this.setInt("octaves", this.octaves);
  107144. this.setFloat("persistence", this.persistence);
  107145. this.setFloat("timeScale", this._time);
  107146. };
  107147. /** Generate the current state of the procedural texture */
  107148. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  107149. this._updateShaderUniforms();
  107150. _super.prototype.render.call(this, useCameraPostProcess);
  107151. };
  107152. /**
  107153. * Serializes this noise procedural texture
  107154. * @returns a serialized noise procedural texture object
  107155. */
  107156. NoiseProceduralTexture.prototype.serialize = function () {
  107157. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  107158. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  107159. return serializationObject;
  107160. };
  107161. /**
  107162. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  107163. * @param parsedTexture defines parsed texture data
  107164. * @param scene defines the current scene
  107165. * @param rootUrl defines the root URL containing noise procedural texture information
  107166. * @returns a parsed NoiseProceduralTexture
  107167. */
  107168. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  107169. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  107170. return texture;
  107171. };
  107172. return NoiseProceduralTexture;
  107173. }(BABYLON.ProceduralTexture));
  107174. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  107175. })(BABYLON || (BABYLON = {}));
  107176. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  107177. var __assign = (this && this.__assign) || function () {
  107178. __assign = Object.assign || function(t) {
  107179. for (var s, i = 1, n = arguments.length; i < n; i++) {
  107180. s = arguments[i];
  107181. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  107182. t[p] = s[p];
  107183. }
  107184. return t;
  107185. };
  107186. return __assign.apply(this, arguments);
  107187. };
  107188. var BABYLON;
  107189. (function (BABYLON) {
  107190. /**
  107191. * This can helps recording videos from BabylonJS.
  107192. * This is based on the available WebRTC functionalities of the browser.
  107193. *
  107194. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  107195. */
  107196. var VideoRecorder = /** @class */ (function () {
  107197. /**
  107198. * Create a new VideoCapture object which can help converting what you see in Babylon to
  107199. * a video file.
  107200. * @param engine Defines the BabylonJS Engine you wish to record
  107201. * @param options Defines options that can be used to customized the capture
  107202. */
  107203. function VideoRecorder(engine, options) {
  107204. if (options === void 0) { options = null; }
  107205. if (!VideoRecorder.IsSupported(engine)) {
  107206. throw "Your browser does not support recording so far.";
  107207. }
  107208. var canvas = engine.getRenderingCanvas();
  107209. if (!canvas) {
  107210. throw "The babylon engine must have a canvas to be recorded";
  107211. }
  107212. this._canvas = canvas;
  107213. this._canvas.isRecording = false;
  107214. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  107215. var stream = this._canvas.captureStream(this._options.fps);
  107216. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  107217. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  107218. this._mediaRecorder.onerror = this._handleError.bind(this);
  107219. this._mediaRecorder.onstop = this._handleStop.bind(this);
  107220. }
  107221. /**
  107222. * Returns wehther or not the VideoRecorder is available in your browser.
  107223. * @param engine Defines the Babylon Engine to check the support for
  107224. * @returns true if supported otherwise false
  107225. */
  107226. VideoRecorder.IsSupported = function (engine) {
  107227. var canvas = engine.getRenderingCanvas();
  107228. return (!!canvas && typeof canvas.captureStream === "function");
  107229. };
  107230. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  107231. /**
  107232. * True wether a recording is already in progress.
  107233. */
  107234. get: function () {
  107235. return !!this._canvas && this._canvas.isRecording;
  107236. },
  107237. enumerable: true,
  107238. configurable: true
  107239. });
  107240. /**
  107241. * Stops the current recording before the default capture timeout passed in the startRecording
  107242. * functions.
  107243. */
  107244. VideoRecorder.prototype.stopRecording = function () {
  107245. if (!this._canvas || !this._mediaRecorder) {
  107246. return;
  107247. }
  107248. if (!this.isRecording) {
  107249. return;
  107250. }
  107251. this._canvas.isRecording = false;
  107252. this._mediaRecorder.stop();
  107253. };
  107254. /**
  107255. * Starts recording the canvas for a max duration specified in parameters.
  107256. * @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.
  107257. * @param maxDuration Defines the maximum recording time in seconds.
  107258. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  107259. * @return a promise callback at the end of the recording with the video data in Blob.
  107260. */
  107261. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  107262. var _this = this;
  107263. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  107264. if (maxDuration === void 0) { maxDuration = 7; }
  107265. if (!this._canvas || !this._mediaRecorder) {
  107266. throw "Recorder has already been disposed";
  107267. }
  107268. if (this.isRecording) {
  107269. throw "Recording already in progress";
  107270. }
  107271. if (maxDuration > 0) {
  107272. setTimeout(function () {
  107273. _this.stopRecording();
  107274. }, maxDuration * 1000);
  107275. }
  107276. this._fileName = fileName;
  107277. this._recordedChunks = [];
  107278. this._resolve = null;
  107279. this._reject = null;
  107280. this._canvas.isRecording = true;
  107281. this._mediaRecorder.start(this._options.recordChunckSize);
  107282. return new Promise(function (resolve, reject) {
  107283. _this._resolve = resolve;
  107284. _this._reject = reject;
  107285. });
  107286. };
  107287. /**
  107288. * Releases internal resources used during the recording.
  107289. */
  107290. VideoRecorder.prototype.dispose = function () {
  107291. this._canvas = null;
  107292. this._mediaRecorder = null;
  107293. this._recordedChunks = [];
  107294. this._fileName = null;
  107295. this._resolve = null;
  107296. this._reject = null;
  107297. };
  107298. VideoRecorder.prototype._handleDataAvailable = function (event) {
  107299. if (event.data.size > 0) {
  107300. this._recordedChunks.push(event.data);
  107301. }
  107302. };
  107303. VideoRecorder.prototype._handleError = function (event) {
  107304. this.stopRecording();
  107305. if (this._reject) {
  107306. this._reject(event.error);
  107307. }
  107308. else {
  107309. throw new event.error;
  107310. }
  107311. };
  107312. VideoRecorder.prototype._handleStop = function () {
  107313. this.stopRecording();
  107314. var superBuffer = new Blob(this._recordedChunks);
  107315. if (this._resolve) {
  107316. this._resolve(superBuffer);
  107317. }
  107318. window.URL.createObjectURL(superBuffer);
  107319. if (this._fileName) {
  107320. BABYLON.Tools.Download(superBuffer, this._fileName);
  107321. }
  107322. };
  107323. VideoRecorder._defaultOptions = {
  107324. mimeType: "video/webm",
  107325. fps: 25,
  107326. recordChunckSize: 3000
  107327. };
  107328. return VideoRecorder;
  107329. }());
  107330. BABYLON.VideoRecorder = VideoRecorder;
  107331. })(BABYLON || (BABYLON = {}));
  107332. //# sourceMappingURL=babylon.videoRecorder.js.map
  107333. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 baseColor=texture2D(diffuseSampler,vUV);\nbaseColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \noutFragColor=texture(textureSampler,vUV)*vColor;\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;\nuniform float directionRandomizer;\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#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#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 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;\nif (newAge>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\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\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\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#endif\n} else { \nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,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\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*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 int octaves;\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"};
  107334. 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};"};